blob: a4680cab4b567e549624fc144f4f8bcfd7fce847 [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;
4086 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
4087 // If the start clock time has changed by more than a year, then presumably
4088 // the previous time was completely bogus. So we are going to figure out a
4089 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08004090 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004091 return true;
4092 }
4093 return false;
4094 }
4095
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004096 public void noteCurrentTimeChangedLocked() {
4097 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08004098 final long elapsedRealtime = mClocks.elapsedRealtime();
4099 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004100 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07004101 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07004102 }
4103
Dianne Hackborn61659e52014-07-09 16:13:01 -07004104 public void noteProcessStartLocked(String name, int uid) {
4105 uid = mapUid(uid);
4106 if (isOnBattery()) {
4107 Uid u = getUidStatsLocked(uid);
4108 u.getProcessStatsLocked(name).incStartsLocked();
4109 }
4110 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
4111 return;
4112 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004113 if (!mRecordAllHistory) {
4114 return;
4115 }
Joe Onoratoabded112016-02-08 16:49:39 -08004116 final long elapsedRealtime = mClocks.elapsedRealtime();
4117 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07004118 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
4119 }
4120
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004121 public void noteProcessCrashLocked(String name, int uid) {
4122 uid = mapUid(uid);
4123 if (isOnBattery()) {
4124 Uid u = getUidStatsLocked(uid);
4125 u.getProcessStatsLocked(name).incNumCrashesLocked();
4126 }
4127 }
4128
4129 public void noteProcessAnrLocked(String name, int uid) {
4130 uid = mapUid(uid);
4131 if (isOnBattery()) {
4132 Uid u = getUidStatsLocked(uid);
4133 u.getProcessStatsLocked(name).incNumAnrsLocked();
4134 }
4135 }
4136
Dianne Hackborna8d10942015-11-19 17:55:19 -08004137 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07004138 int parentUid = mapUid(uid);
4139 if (uid != parentUid) {
4140 // Isolated UIDs process state is already rolled up into parent, so no need to track
4141 // Otherwise the parent's process state will get downgraded incorrectly
4142 return;
4143 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08004144 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004145 }
4146
4147 public void noteProcessFinishLocked(String name, int uid) {
4148 uid = mapUid(uid);
4149 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4150 return;
4151 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004152 if (!mRecordAllHistory) {
4153 return;
4154 }
Joe Onoratoabded112016-02-08 16:49:39 -08004155 final long elapsedRealtime = mClocks.elapsedRealtime();
4156 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004157 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004158 }
4159
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004160 public void noteSyncStartLocked(String name, int uid) {
4161 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004162 final long elapsedRealtime = mClocks.elapsedRealtime();
4163 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004164 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4165 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4166 return;
4167 }
4168 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4169 }
4170
4171 public void noteSyncFinishLocked(String name, int uid) {
4172 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004173 final long elapsedRealtime = mClocks.elapsedRealtime();
4174 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004175 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4176 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4177 return;
4178 }
4179 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4180 }
4181
4182 public void noteJobStartLocked(String name, int uid) {
4183 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004184 final long elapsedRealtime = mClocks.elapsedRealtime();
4185 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004186 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4187 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4188 return;
4189 }
4190 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4191 }
4192
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004193 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004194 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004195 final long elapsedRealtime = mClocks.elapsedRealtime();
4196 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004197 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004198 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4199 return;
4200 }
4201 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4202 }
4203
Amith Yamasani977e11f2018-02-16 11:29:54 -08004204 public void noteJobsDeferredLocked(int uid, int numDeferred, long sinceLast) {
4205 uid = mapUid(uid);
4206 getUidStatsLocked(uid).noteJobsDeferredLocked(numDeferred, sinceLast);
4207 }
4208
Narayan Kamath695cf722017-12-21 18:32:47 +00004209 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4210 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004211 }
4212
Narayan Kamath695cf722017-12-21 18:32:47 +00004213 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4214 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4215 }
4216
4217 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4218 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004219 if (!mRecordAllHistory) {
4220 return;
4221 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004222
Joe Onoratoabded112016-02-08 16:49:39 -08004223 final long elapsedRealtime = mClocks.elapsedRealtime();
4224 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004225
4226 if (workSource != null) {
4227 for (int i = 0; i < workSource.size(); ++i) {
4228 uid = mapUid(workSource.get(i));
4229 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4230 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4231 }
4232 }
4233
4234 List<WorkChain> workChains = workSource.getWorkChains();
4235 if (workChains != null) {
4236 for (int i = 0; i < workChains.size(); ++i) {
4237 uid = mapUid(workChains.get(i).getAttributionUid());
4238 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4239 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4240 }
4241 }
4242 }
4243 } else {
4244 uid = mapUid(uid);
4245
4246 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4247 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4248 }
4249 }
4250 }
4251
4252 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4253 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004254 if (workSource != null) {
4255 for (int i = 0; i < workSource.size(); ++i) {
4256 uid = workSource.get(i);
4257 final String workSourceName = workSource.getName(i);
4258
Tej Singh6f724c42018-01-03 20:02:03 -08004259 if (isOnBattery()) {
4260 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4261 workSourceName != null ? workSourceName : packageName);
4262 pkg.noteWakeupAlarmLocked(tag);
4263 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004264 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4265 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004266 }
4267
4268 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4269 if (workChains != null) {
4270 for (int i = 0; i < workChains.size(); ++i) {
4271 final WorkChain wc = workChains.get(i);
4272 uid = wc.getAttributionUid();
4273
Tej Singh6f724c42018-01-03 20:02:03 -08004274 if (isOnBattery()) {
4275 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4276 pkg.noteWakeupAlarmLocked(tag);
4277 }
Yangster-macafad8c62018-01-05 22:30:49 -08004278 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004279 }
4280 }
4281 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004282 if (isOnBattery()) {
4283 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4284 pkg.noteWakeupAlarmLocked(tag);
4285 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004286 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004287 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004288 }
4289
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004290 private void requestWakelockCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004291 mExternalSync.scheduleCpuSyncDueToWakelockChange(DELAY_UPDATE_WAKELOCKS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004292 }
4293
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004294 private void requestImmediateCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004295 mExternalSync.scheduleCpuSyncDueToWakelockChange(0 /* delayMillis */);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004296 }
4297
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004298 public void setRecordAllHistoryLocked(boolean enabled) {
4299 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004300 if (!enabled) {
4301 // Clear out any existing state.
4302 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004303 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004304 // Record the currently running processes as stopping, now that we are no
4305 // longer tracking them.
4306 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4307 HistoryItem.EVENT_PROC);
4308 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004309 long mSecRealtime = mClocks.elapsedRealtime();
4310 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004311 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4312 SparseIntArray uids = ent.getValue();
4313 for (int j=0; j<uids.size(); j++) {
4314 addHistoryEventLocked(mSecRealtime, mSecUptime,
4315 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4316 }
4317 }
4318 }
4319 } else {
4320 // Record the currently running processes as starting, now that we are tracking them.
4321 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4322 HistoryItem.EVENT_PROC);
4323 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004324 long mSecRealtime = mClocks.elapsedRealtime();
4325 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004326 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4327 SparseIntArray uids = ent.getValue();
4328 for (int j=0; j<uids.size(); j++) {
4329 addHistoryEventLocked(mSecRealtime, mSecUptime,
4330 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4331 }
4332 }
4333 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004334 }
4335 }
4336
Dianne Hackborn9a755432014-05-15 17:05:22 -07004337 public void setNoAutoReset(boolean enabled) {
4338 mNoAutoReset = enabled;
4339 }
4340
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004341 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004342 if (mPretendScreenOff != pretendScreenOff) {
4343 mPretendScreenOff = pretendScreenOff;
4344 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4345 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004346 }
4347
Dianne Hackborn9a755432014-05-15 17:05:22 -07004348 private String mInitialAcquireWakeName;
4349 private int mInitialAcquireWakeUid = -1;
4350
Narayan Kamath81822022017-12-08 11:56:01 +00004351 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4352 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004353 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004354 if (type == WAKE_TYPE_PARTIAL) {
4355 // Only care about partial wake locks, since full wake locks
4356 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004357 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004358 if (historyName == null) {
4359 historyName = name;
4360 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004361 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004362 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4363 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004364 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004365 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004366 }
4367 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004368 if (mWakeLockNesting == 0) {
4369 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4370 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4371 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004372 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004373 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004374 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004375 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004376 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004377 } else if (!mWakeLockImportant && !unimportantForLogging
4378 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004379 if (mHistoryLastWritten.wakelockTag != null) {
4380 // We'll try to update the last tag.
4381 mHistoryLastWritten.wakelockTag = null;
4382 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004383 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004384 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004385 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004386 }
4387 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004388 }
4389 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004390 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004391 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004392 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4393 // We only update the cpu time when a wake lock is acquired if the screen is off.
4394 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4395 if (DEBUG_ENERGY_CPU) {
4396 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4397 }
4398 requestWakelockCpuUpdate();
4399 }
Narayan Kamath81822022017-12-08 11:56:01 +00004400
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004401 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004402
Yangster-mac20877162017-12-22 17:19:39 -08004403 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004404 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004405 getPowerManagerWakeLockLevel(type), name,
4406 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Yangster-macafad8c62018-01-05 22:30:49 -08004407 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004408 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004409 getPowerManagerWakeLockLevel(type), name,
4410 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Narayan Kamath81822022017-12-08 11:56:01 +00004411 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004412 }
4413 }
4414
Narayan Kamath81822022017-12-08 11:56:01 +00004415 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4416 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004417 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004418 if (type == WAKE_TYPE_PARTIAL) {
4419 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004420 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004421 if (historyName == null) {
4422 historyName = name;
4423 }
4424 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4425 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004426 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004427 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004428 }
4429 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004430 if (mWakeLockNesting == 0) {
4431 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4432 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4433 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004434 mInitialAcquireWakeName = null;
4435 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004436 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004437 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004438 }
4439 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004440 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4441 if (DEBUG_ENERGY_CPU) {
4442 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4443 }
4444 requestWakelockCpuUpdate();
4445 }
Narayan Kamath81822022017-12-08 11:56:01 +00004446
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004447 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004448 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004449 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004450 getPowerManagerWakeLockLevel(type), name,
4451 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Yangster-macafad8c62018-01-05 22:30:49 -08004452 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004453 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004454 getPowerManagerWakeLockLevel(type), name,
4455 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Narayan Kamath81822022017-12-08 11:56:01 +00004456 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004457 }
4458 }
4459
Bookatz1a1b0462018-01-12 11:47:03 -08004460 /**
4461 * Converts BatteryStats wakelock types back into PowerManager wakelock levels.
4462 * This is the inverse map of Notifier.getBatteryStatsWakeLockMonitorType().
4463 * These are estimations, since batterystats loses some of the original data.
4464 * TODO: Delete this. Instead, StatsLog.write should be called from PowerManager's Notifier.
4465 */
4466 private int getPowerManagerWakeLockLevel(int battertStatsWakelockType) {
4467 switch (battertStatsWakelockType) {
4468 // PowerManager.PARTIAL_WAKE_LOCK or PROXIMITY_SCREEN_OFF_WAKE_LOCK
4469 case BatteryStats.WAKE_TYPE_PARTIAL:
4470 return PowerManager.PARTIAL_WAKE_LOCK;
4471
4472 // PowerManager.SCREEN_DIM_WAKE_LOCK or SCREEN_BRIGHT_WAKE_LOCK
4473 case BatteryStats.WAKE_TYPE_FULL:
4474 return PowerManager.FULL_WAKE_LOCK;
4475
4476 case BatteryStats.WAKE_TYPE_DRAW:
4477 return PowerManager.DRAW_WAKE_LOCK;
4478
4479 // It appears that nothing can ever make a Window and PowerManager lacks an equivalent.
4480 case BatteryStats.WAKE_TYPE_WINDOW:
4481 Slog.e(TAG, "Illegal window wakelock type observed in batterystats.");
4482 return -1;
4483
4484 default:
4485 Slog.e(TAG, "Illegal wakelock type in batterystats: " + battertStatsWakelockType);
4486 return -1;
4487 }
4488 }
4489
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004490 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4491 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004492 final long elapsedRealtime = mClocks.elapsedRealtime();
4493 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004494 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004495 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004496 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4497 unimportantForLogging, elapsedRealtime, uptime);
4498 }
4499
4500 List<WorkChain> wcs = ws.getWorkChains();
4501 if (wcs != null) {
4502 for (int i = 0; i < wcs.size(); ++i) {
4503 final WorkChain wc = wcs.get(i);
4504 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4505 unimportantForLogging, elapsedRealtime, uptime);
4506 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004507 }
4508 }
4509
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004510 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4511 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004512 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004513 final long elapsedRealtime = mClocks.elapsedRealtime();
4514 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004515
4516 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4517
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004518 // For correct semantics, we start the need worksources first, so that we won't
4519 // make inappropriate history items as if all wake locks went away and new ones
4520 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004521 //
4522 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004523 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004524 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004525 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004526 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004527 }
Narayan Kamath81822022017-12-08 11:56:01 +00004528 if (wcs != null) {
4529 List<WorkChain> newChains = wcs[0];
4530 if (newChains != null) {
4531 for (int i = 0; i < newChains.size(); ++i) {
4532 final WorkChain newChain = newChains.get(i);
4533 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4534 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4535 uptime);
4536 }
4537 }
4538 }
4539
4540 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004541 final int NO = ws.size();
4542 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004543 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4544 uptime);
4545 }
4546 if (wcs != null) {
4547 List<WorkChain> goneChains = wcs[1];
4548 if (goneChains != null) {
4549 for (int i = 0; i < goneChains.size(); ++i) {
4550 final WorkChain goneChain = goneChains.get(i);
4551 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4552 historyName, type, elapsedRealtime, uptime);
4553 }
4554 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004555 }
4556 }
4557
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004558 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4559 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004560 final long elapsedRealtime = mClocks.elapsedRealtime();
4561 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004562 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004563 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004564 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4565 uptime);
4566 }
4567
4568 List<WorkChain> wcs = ws.getWorkChains();
4569 if (wcs != null) {
4570 for (int i = 0; i < wcs.size(); ++i) {
4571 final WorkChain wc = wcs.get(i);
4572 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4573 elapsedRealtime, uptime);
4574 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004575 }
4576 }
4577
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004578 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004579 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004580 uid, null, name, historyName,
4581 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08004582
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004583 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004584 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004585 }
4586
4587 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4588 WorkSource workSource) {
4589 final int N = workSource.size();
4590 for (int i = 0; i < N; ++i) {
4591 final int uid = mapUid(workSource.get(i));
4592 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004593 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004594 workSource.get(i), workSource.getName(i), name, historyName,
4595 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004596 }
4597
4598 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4599 if (workChains != null) {
4600 for (int i = 0; i < workChains.size(); ++i) {
4601 final WorkChain workChain = workChains.get(i);
4602 final int uid = workChain.getAttributionUid();
4603 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4604
Yangster-macafad8c62018-01-05 22:30:49 -08004605 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004606 workChain.getUids(), workChain.getTags(), name, historyName,
4607 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004608 }
4609 }
4610 }
4611
4612 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004613 final long elapsedRealtime = mClocks.elapsedRealtime();
4614 final long uptime = mClocks.uptimeMillis();
4615 if (historyName == null) {
4616 historyName = name;
4617 }
4618 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4619 0)) {
4620 return;
4621 }
4622 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4623 historyName, uid);
4624 }
4625
4626 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Bookatz90867622018-01-31 15:05:57 -08004627 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, null,
4628 name, historyName, StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08004629
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004630 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004631 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004632 }
4633
4634 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4635 WorkSource workSource) {
4636 final int N = workSource.size();
4637 for (int i = 0; i < N; ++i) {
4638 final int uid = mapUid(workSource.get(i));
4639 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004640 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004641 workSource.get(i), workSource.getName(i), name, historyName,
4642 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004643 }
4644
4645 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4646 if (workChains != null) {
4647 for (int i = 0; i < workChains.size(); ++i) {
4648 final WorkChain workChain = workChains.get(i);
4649 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004650 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004651 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004652 workChain.getUids(), workChain.getTags(), name, historyName,
4653 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004654 }
4655 }
4656 }
4657
4658 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004659 final long elapsedRealtime = mClocks.elapsedRealtime();
4660 final long uptime = mClocks.uptimeMillis();
4661 if (historyName == null) {
4662 historyName = name;
4663 }
4664 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4665 0)) {
4666 return;
4667 }
4668 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4669 historyName, uid);
4670 }
4671
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004672 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4673 if (mLastWakeupReason != null) {
4674 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004675 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004676 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz90867622018-01-31 15:05:57 -08004677 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
4678 /* duration_usec */ deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004679 mLastWakeupReason = null;
4680 }
4681 }
4682
4683 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004684 final long elapsedRealtime = mClocks.elapsedRealtime();
4685 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004686 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004687 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004688 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004689 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4690 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004691 mHistoryCur.wakeReasonTag.uid = 0;
4692 mLastWakeupReason = reason;
4693 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004694 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004695 }
4696
Adam Lesinski72478f02015-06-17 15:39:43 -07004697 public boolean startAddingCpuLocked() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004698 mExternalSync.cancelCpuSyncDueToWakelockChange();
Adam Lesinski72478f02015-06-17 15:39:43 -07004699 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004700 }
4701
Adam Lesinski72478f02015-06-17 15:39:43 -07004702 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4703 int statSystemTime, int statIOWaitTime, int statIrqTime,
4704 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004705 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4706 + " user=" + statUserTime + " sys=" + statSystemTime
4707 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4708 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4709 mCurStepCpuUserTime += totalUTime;
4710 mCurStepCpuSystemTime += totalSTime;
4711 mCurStepStatUserTime += statUserTime;
4712 mCurStepStatSystemTime += statSystemTime;
4713 mCurStepStatIOWaitTime += statIOWaitTime;
4714 mCurStepStatIrqTime += statIrqTime;
4715 mCurStepStatSoftIrqTime += statSoftIrqTime;
4716 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004717 }
4718
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004719 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004720 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004721 Uid u = mUidStats.get(uid);
4722 if (u != null) {
4723 u.mPids.remove(pid);
4724 }
4725 }
4726
4727 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004728 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004729 Uid u = mUidStats.get(uid);
4730 if (u != null) {
4731 Uid.Pid p = u.mPids.get(pid);
4732 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004733 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004734 }
4735 }
4736 return 0;
4737 }
4738
Dianne Hackborn287952c2010-09-22 22:34:31 -07004739 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004740 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004741 Uid u = mUidStats.get(uid);
4742 if (u != null) {
4743 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4744 }
4745 }
4746
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004747 int mSensorNesting;
4748
4749 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004750 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004751 final long elapsedRealtime = mClocks.elapsedRealtime();
4752 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004753 if (mSensorNesting == 0) {
4754 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4755 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4756 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004757 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004758 }
4759 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004760 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004761 }
4762
4763 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004764 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004765 final long elapsedRealtime = mClocks.elapsedRealtime();
4766 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004767 mSensorNesting--;
4768 if (mSensorNesting == 0) {
4769 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4770 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4771 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004772 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004773 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004774 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004775 }
4776
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004777 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004778
Narayan Kamath32684dd2018-01-08 17:32:51 +00004779 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4780 for (int i = 0; i < newWs.size(); ++i) {
4781 noteStartGpsLocked(newWs.get(i), null);
4782 }
4783
4784 for (int i = 0; i < oldWs.size(); ++i) {
4785 noteStopGpsLocked((oldWs.get(i)), null);
4786 }
4787
4788 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4789 if (wcs != null) {
4790 if (wcs[0] != null) {
4791 final List<WorkChain> newChains = wcs[0];
4792 for (int i = 0; i < newChains.size(); ++i) {
4793 noteStartGpsLocked(-1, newChains.get(i));
4794 }
4795 }
4796
4797 if (wcs[1] != null) {
4798 final List<WorkChain> goneChains = wcs[1];
4799 for (int i = 0; i < goneChains.size(); ++i) {
4800 noteStopGpsLocked(-1, goneChains.get(i));
4801 }
4802 }
4803 }
4804 }
4805
4806 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4807 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004808 final long elapsedRealtime = mClocks.elapsedRealtime();
4809 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004810 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004811 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004812 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4813 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004814 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004815 }
4816 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004817
4818 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004819 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4820 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004821 } else {
4822 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004823 workChain.getUids(), workChain.getTags(),
4824 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004825 }
4826
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004827 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004828 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004829
Narayan Kamath32684dd2018-01-08 17:32:51 +00004830 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4831 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004832 final long elapsedRealtime = mClocks.elapsedRealtime();
4833 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004834 mGpsNesting--;
4835 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004836 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004837 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4838 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004839 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004840 stopAllGpsSignalQualityTimersLocked(-1);
4841 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004842 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004843
4844 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004845 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4846 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004847 } else {
4848 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08004849 workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004850 }
4851
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004852 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004853 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004854
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004855 public void noteGpsSignalQualityLocked(int signalLevel) {
4856 if (mGpsNesting == 0) {
4857 return;
4858 }
4859 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4860 stopAllGpsSignalQualityTimersLocked(-1);
4861 return;
4862 }
4863 final long elapsedRealtime = mClocks.elapsedRealtime();
4864 final long uptime = mClocks.uptimeMillis();
4865 if (mGpsSignalQualityBin != signalLevel) {
4866 if (mGpsSignalQualityBin >= 0) {
4867 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4868 }
4869 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4870 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4871 }
4872 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4873 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4874 addHistoryRecordLocked(elapsedRealtime, uptime);
4875 mGpsSignalQualityBin = signalLevel;
4876 }
4877 return;
4878 }
4879
Andreas Gampe3f24e692018-02-05 13:24:28 -08004880 @GuardedBy("this")
Jeff Browne95c3cd2014-05-02 16:59:26 -07004881 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004882 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004883
4884 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4885 // original 4 are mapped to one of the originals.
4886 if (state > MAX_TRACKED_SCREEN_STATE) {
4887 switch (state) {
4888 case Display.STATE_VR:
4889 state = Display.STATE_ON;
4890 break;
4891 default:
4892 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4893 break;
4894 }
4895 }
4896
Jeff Browne95c3cd2014-05-02 16:59:26 -07004897 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004898 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004899 final int oldState = mScreenState;
4900 mScreenState = state;
4901 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4902 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004903
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004904 if (state != Display.STATE_UNKNOWN) {
4905 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004906 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4907 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4908 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004909 } else {
4910 Slog.wtf(TAG, "Unexpected screen state: " + state);
4911 }
4912 }
4913
Mike Mac2f518a2017-09-19 16:06:03 -07004914 final long elapsedRealtime = mClocks.elapsedRealtime();
4915 final long uptime = mClocks.uptimeMillis();
4916
4917 boolean updateHistory = false;
4918 if (isScreenDoze(state)) {
4919 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4920 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4921 updateHistory = true;
4922 } else if (isScreenDoze(oldState)) {
4923 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4924 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4925 updateHistory = true;
4926 }
4927 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004928 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4929 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4930 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004931 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4932 if (mScreenBrightnessBin >= 0) {
4933 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4934 }
Mike Mac2f518a2017-09-19 16:06:03 -07004935 updateHistory = true;
4936 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004937 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4938 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4939 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004940 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4941 if (mScreenBrightnessBin >= 0) {
4942 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4943 }
Mike Mac2f518a2017-09-19 16:06:03 -07004944 updateHistory = true;
4945 }
4946 if (updateHistory) {
4947 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4948 + Display.stateToString(state));
4949 addHistoryRecordLocked(elapsedRealtime, uptime);
4950 }
Sudheer Shankac57729a2018-02-09 15:44:42 -08004951 mExternalSync.scheduleCpuSyncDueToScreenStateChange(
4952 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
Mike Mac2f518a2017-09-19 16:06:03 -07004953 if (isScreenOn(state)) {
4954 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4955 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4956 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004957 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004958 elapsedRealtime, uptime);
4959 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004960 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004961 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004962 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004963 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004964 }
4965 // Update discharge amounts.
4966 if (mOnBatteryInternal) {
4967 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004968 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004969 }
4970 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004971
Dianne Hackborn617f8772009-03-31 15:04:46 -07004972 public void noteScreenBrightnessLocked(int brightness) {
4973 // Bin the brightness.
4974 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4975 if (bin < 0) bin = 0;
4976 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4977 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004978 final long elapsedRealtime = mClocks.elapsedRealtime();
4979 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004980 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4981 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004982 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4983 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004984 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004985 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004986 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004987 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004988 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004989 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004990 }
4991 mScreenBrightnessBin = bin;
4992 }
4993 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004994
Dianne Hackborn617f8772009-03-31 15:04:46 -07004995 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004996 if (mOnBatteryInternal) {
4997 uid = mapUid(uid);
4998 getUidStatsLocked(uid).noteUserActivityLocked(event);
4999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005001
Dianne Hackborn280a64e2015-07-13 14:48:08 -07005002 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005003 final long elapsedRealtime = mClocks.elapsedRealtime();
5004 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07005005 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
5006 reason, reasonUid);
5007 }
5008
Jeff Browne95c3cd2014-05-02 16:59:26 -07005009 public void noteInteractiveLocked(boolean interactive) {
5010 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08005011 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07005012 mInteractive = interactive;
5013 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
5014 if (interactive) {
5015 mInteractiveTimer.startRunningLocked(elapsedRealtime);
5016 } else {
5017 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
5018 }
5019 }
5020 }
5021
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005022 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08005023 final long elapsedRealtime = mClocks.elapsedRealtime();
5024 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005025 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
5026 extra, type);
5027 mNumConnectivityChange++;
5028 }
5029
Adam Lesinski5f056f62016-07-14 16:56:08 -07005030 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
5031 final long uptimeMillis, int uid) {
5032 uid = mapUid(uid);
5033 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5034 uid);
5035 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
5036 }
5037
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005038 /**
5039 * Updates the radio power state and returns true if an external stats collection should occur.
5040 */
5041 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005042 final long elapsedRealtime = mClocks.elapsedRealtime();
5043 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005044 if (mMobileRadioPowerState != powerState) {
5045 long realElapsedRealtimeMs;
5046 final boolean active =
5047 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5048 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5049 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005050 if (uid > 0) {
5051 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5052 }
5053
Adam Lesinski9acfd812016-04-19 18:29:50 -07005054 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005055 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5056 } else {
5057 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07005058 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005059 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
5060 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
5061 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005062 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005063 } else if (realElapsedRealtimeMs < elapsedRealtime) {
5064 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
5065 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005066 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005067 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
5068 }
5069 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
5070 + Integer.toHexString(mHistoryCur.states));
5071 addHistoryRecordLocked(elapsedRealtime, uptime);
5072 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005073 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005074 if (active) {
5075 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
5076 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
5077 } else {
5078 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07005079 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005080 // Tell the caller to collect radio network/power stats.
5081 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005082 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005083 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005084 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005085 }
5086
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005087 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005088 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07005089 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
5090 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
5091 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08005092 final long elapsedRealtime = mClocks.elapsedRealtime();
5093 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005094 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005095 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005096 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
5097 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005098 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005099 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005100 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005101 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
5102 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005103 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005104 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005105 }
5106 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatz90867622018-01-31 15:05:57 -08005107 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
5108 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
5109 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005110 }
5111 }
5112
Bookatzddccf0a2017-11-28 16:48:14 -08005113 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005114 final long elapsedRealtime = mClocks.elapsedRealtime();
5115 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005116 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005117 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005118 // We don't go out of general idling mode until explicitly taken out of
5119 // device idle through going active or significant motion.
5120 nowIdling = true;
5121 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005122 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
5123 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
5124 // We don't go out of general light idling mode until explicitly taken out of
5125 // device idle through going active or significant motion.
5126 nowLightIdling = true;
5127 }
5128 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
5129 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
5130 activeReason, activeUid);
5131 }
Bookatzddccf0a2017-11-28 16:48:14 -08005132 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
5133 int statsmode;
5134 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
5135 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
5136 else statsmode = DEVICE_IDLE_MODE_OFF;
5137 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
5138 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005139 if (mDeviceIdling != nowIdling) {
5140 mDeviceIdling = nowIdling;
5141 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
5142 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
5143 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005144 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005145 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
5146 } else {
5147 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
5148 }
5149 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005150 if (mDeviceLightIdling != nowLightIdling) {
5151 mDeviceLightIdling = nowLightIdling;
5152 if (nowLightIdling) {
5153 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005154 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005155 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005156 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005157 }
5158 if (mDeviceIdleMode != mode) {
5159 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
5160 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
5161 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
5162 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005163 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005164 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
5165 mLastIdleTimeStart = elapsedRealtime;
5166 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
5167 if (lastDuration > mLongestLightIdleTime) {
5168 mLongestLightIdleTime = lastDuration;
5169 }
5170 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005171 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005172 if (lastDuration > mLongestFullIdleTime) {
5173 mLongestFullIdleTime = lastDuration;
5174 }
5175 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
5176 }
5177 if (mode == DEVICE_IDLE_MODE_LIGHT) {
5178 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005179 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005180 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
5181 }
5182 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08005183 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005184 }
5185 }
5186
Dianne Hackborn3accca02013-09-20 09:32:11 -07005187 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08005188 final long elapsedRealtime = mClocks.elapsedRealtime();
5189 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07005190 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005191 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07005192 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005193 PackageChange pc = new PackageChange();
5194 pc.mPackageName = pkgName;
5195 pc.mUpdate = true;
5196 pc.mVersionCode = versionCode;
5197 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005198 }
5199
5200 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005201 final long elapsedRealtime = mClocks.elapsedRealtime();
5202 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005203 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5204 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005205 PackageChange pc = new PackageChange();
5206 pc.mPackageName = pkgName;
5207 pc.mUpdate = true;
5208 addPackageChange(pc);
5209 }
5210
5211 private void addPackageChange(PackageChange pc) {
5212 if (mDailyPackageChanges == null) {
5213 mDailyPackageChanges = new ArrayList<>();
5214 }
5215 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005216 }
5217
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005218 void stopAllGpsSignalQualityTimersLocked(int except) {
5219 final long elapsedRealtime = mClocks.elapsedRealtime();
5220 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5221 if (i == except) {
5222 continue;
5223 }
5224 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5225 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5226 }
5227 }
5228 }
5229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230 public void notePhoneOnLocked() {
5231 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005232 final long elapsedRealtime = mClocks.elapsedRealtime();
5233 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005234 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005235 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5236 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005237 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005239 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240 }
5241 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005243 public void notePhoneOffLocked() {
5244 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005245 final long elapsedRealtime = mClocks.elapsedRealtime();
5246 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005247 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005248 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5249 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005250 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005251 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005252 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005253 }
5254 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005255
Mike Mafbc01fc2018-04-02 10:28:28 -07005256 private void registerUsbStateReceiver(Context context) {
5257 final IntentFilter usbStateFilter = new IntentFilter();
5258 usbStateFilter.addAction(UsbManager.ACTION_USB_STATE);
5259 context.registerReceiver(new BroadcastReceiver() {
5260 @Override
5261 public void onReceive(Context context, Intent intent) {
5262 final boolean state = intent.getBooleanExtra(UsbManager.USB_CONNECTED, false);
5263 synchronized (BatteryStatsImpl.this) {
5264 noteUsbConnectionStateLocked(state);
5265 }
5266 }
5267 }, usbStateFilter);
5268 synchronized (this) {
5269 if (mUsbDataState == USB_DATA_UNKNOWN) {
5270 final Intent usbState = context.registerReceiver(null, usbStateFilter);
5271 final boolean initState = usbState != null && usbState.getBooleanExtra(
5272 UsbManager.USB_CONNECTED, false);
5273 noteUsbConnectionStateLocked(initState);
5274 }
5275 }
5276 }
5277
5278 private void noteUsbConnectionStateLocked(boolean connected) {
5279 int newState = connected ? USB_DATA_CONNECTED : USB_DATA_DISCONNECTED;
Mike Ma926a97c2018-03-25 02:32:35 -07005280 if (mUsbDataState != newState) {
5281 mUsbDataState = newState;
5282 if (connected) {
5283 mHistoryCur.states2 |= HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5284 } else {
5285 mHistoryCur.states2 &= ~HistoryItem.STATE2_USB_DATA_LINK_FLAG;
5286 }
5287 addHistoryRecordLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
5288 }
5289 }
5290
Dianne Hackborn3251b902014-06-20 14:40:53 -07005291 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005292 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005293 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005294 if (i == except) {
5295 continue;
5296 }
5297 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005298 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005299 }
5300 }
5301 }
5302
Dianne Hackborne4a59512010-12-07 11:08:07 -08005303 private int fixPhoneServiceState(int state, int signalBin) {
5304 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5305 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5306 // to infer that we are scanning from other data.
5307 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005308 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005309 state = ServiceState.STATE_IN_SERVICE;
5310 }
5311 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005312
Dianne Hackborne4a59512010-12-07 11:08:07 -08005313 return state;
5314 }
5315
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005316 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005317 boolean scanning = false;
5318 boolean newHistory = false;
5319
5320 mPhoneServiceStateRaw = state;
5321 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005322 mPhoneSignalStrengthBinRaw = strengthBin;
5323
Joe Onoratoabded112016-02-08 16:49:39 -08005324 final long elapsedRealtime = mClocks.elapsedRealtime();
5325 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005326
5327 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5328 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5329 // to infer that we are scanning from other data.
5330 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005331 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005332 state = ServiceState.STATE_IN_SERVICE;
5333 }
5334 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005335
5336 // If the phone is powered off, stop all timers.
5337 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005338 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005339
Dianne Hackborne4a59512010-12-07 11:08:07 -08005340 // If we are in service, make sure the correct signal string timer is running.
5341 } else if (state == ServiceState.STATE_IN_SERVICE) {
5342 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005343
5344 // If we're out of service, we are in the lowest signal strength
5345 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005346 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005347 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005348 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005349 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005350 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005351 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005352 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5353 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005354 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005355 }
5356 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005357
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005358 if (!scanning) {
5359 // If we are no longer scanning, then stop the scanning timer.
5360 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5361 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5362 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5363 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005364 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005365 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005366 }
5367 }
5368
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005369 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005370 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5371 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005372 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005373 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005374 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005375 mPhoneServiceState = state;
5376 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005377
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005378 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005379 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005380 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005381 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005382 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005383 if (strengthBin >= 0) {
5384 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005385 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005386 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005387 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5388 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005389 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005390 + Integer.toHexString(mHistoryCur.states));
5391 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005392 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005393 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005394 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005395 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005396 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005397 }
5398
5399 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005400 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005401 }
5402 }
5403
5404 /**
5405 * Telephony stack updates the phone state.
5406 * @param state phone state from ServiceState.getState()
5407 */
5408 public void notePhoneStateLocked(int state, int simState) {
5409 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005410 }
5411
Wink Savillee9b06d72009-05-18 21:47:50 -07005412 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005413 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005414 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005415 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005416 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005417
Dianne Hackborn627bba72009-03-24 22:32:56 -07005418 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005419 // BatteryStats uses 0 to represent no network type.
5420 // Telephony does not have a concept of no network type, and uses 0 to represent unknown.
5421 // Unknown is included in DATA_CONNECTION_OTHER.
Dianne Hackborn627bba72009-03-24 22:32:56 -07005422 int bin = DATA_CONNECTION_NONE;
5423 if (hasData) {
Tej Singheee317b2018-03-07 19:28:05 -08005424 if (dataType > 0 && dataType <= TelephonyManager.MAX_NETWORK_TYPE) {
5425 bin = dataType;
5426 } else {
5427 bin = DATA_CONNECTION_OTHER;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005428 }
5429 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005430 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005431 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005432 final long elapsedRealtime = mClocks.elapsedRealtime();
5433 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005434 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5435 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005436 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5437 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005438 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005439 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005440 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005441 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005442 }
5443 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005444 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005445 }
5446 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005447
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005448 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005449 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005450 final long elapsedRealtime = mClocks.elapsedRealtime();
5451 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005452 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005453 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5454 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005455 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005456 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005457 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005458 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005459 }
5460 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005461
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005462 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005463 final long elapsedRealtime = mClocks.elapsedRealtime();
5464 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005465 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005466 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005467 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5468 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005469 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005470 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005471 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005472 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005473 }
5474 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005475
5476 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005477 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005478 final long elapsedRealtime = mClocks.elapsedRealtime();
5479 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005480 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005481 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005482 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5483 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005484 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005485 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005486 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005487 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005488 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005489 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005490
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005491 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005492 if (mAudioOnNesting == 0) {
5493 return;
5494 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005495 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005496 final long elapsedRealtime = mClocks.elapsedRealtime();
5497 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005498 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005499 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005500 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5501 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005502 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005503 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005504 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005505 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005506 }
5507
5508 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005509 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005510 final long elapsedRealtime = mClocks.elapsedRealtime();
5511 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005512 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005513 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005514 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5515 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005516 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005517 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005518 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005519 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005520 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005521 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005522
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005523 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005524 if (mVideoOnNesting == 0) {
5525 return;
5526 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005527 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005528 final long elapsedRealtime = mClocks.elapsedRealtime();
5529 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005530 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005531 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005532 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5533 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005534 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005535 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005536 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005537 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005538 }
5539
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005540 public void noteResetAudioLocked() {
5541 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005542 final long elapsedRealtime = mClocks.elapsedRealtime();
5543 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005544 mAudioOnNesting = 0;
5545 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5546 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5547 + Integer.toHexString(mHistoryCur.states));
5548 addHistoryRecordLocked(elapsedRealtime, uptime);
5549 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5550 for (int i=0; i<mUidStats.size(); i++) {
5551 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5552 uid.noteResetAudioLocked(elapsedRealtime);
5553 }
5554 }
5555 }
5556
5557 public void noteResetVideoLocked() {
5558 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005559 final long elapsedRealtime = mClocks.elapsedRealtime();
5560 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005561 mAudioOnNesting = 0;
5562 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5563 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5564 + Integer.toHexString(mHistoryCur.states));
5565 addHistoryRecordLocked(elapsedRealtime, uptime);
5566 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5567 for (int i=0; i<mUidStats.size(); i++) {
5568 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5569 uid.noteResetVideoLocked(elapsedRealtime);
5570 }
5571 }
5572 }
5573
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005574 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005575 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005576 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005577 }
5578
5579 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005580 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005581 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005582 }
5583
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005584 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005585 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005586 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5587 }
5588
5589 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005590 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005591 getUidStatsLocked(uid).noteVibratorOffLocked();
5592 }
5593
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005594 public void noteFlashlightOnLocked(int uid) {
5595 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005596 final long elapsedRealtime = mClocks.elapsedRealtime();
5597 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005598 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005599 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5600 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005601 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005602 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005603 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5604 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005605 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5606 }
5607
5608 public void noteFlashlightOffLocked(int uid) {
5609 if (mFlashlightOnNesting == 0) {
5610 return;
5611 }
5612 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005613 final long elapsedRealtime = mClocks.elapsedRealtime();
5614 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005615 if (--mFlashlightOnNesting == 0) {
5616 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5617 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5618 + Integer.toHexString(mHistoryCur.states2));
5619 addHistoryRecordLocked(elapsedRealtime, uptime);
5620 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5621 }
5622 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5623 }
5624
5625 public void noteCameraOnLocked(int uid) {
5626 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005627 final long elapsedRealtime = mClocks.elapsedRealtime();
5628 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005629 if (mCameraOnNesting++ == 0) {
5630 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5631 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5632 + Integer.toHexString(mHistoryCur.states2));
5633 addHistoryRecordLocked(elapsedRealtime, uptime);
5634 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5635 }
5636 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5637 }
5638
5639 public void noteCameraOffLocked(int uid) {
5640 if (mCameraOnNesting == 0) {
5641 return;
5642 }
5643 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005644 final long elapsedRealtime = mClocks.elapsedRealtime();
5645 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005646 if (--mCameraOnNesting == 0) {
5647 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5648 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5649 + Integer.toHexString(mHistoryCur.states2));
5650 addHistoryRecordLocked(elapsedRealtime, uptime);
5651 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5652 }
5653 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5654 }
5655
5656 public void noteResetCameraLocked() {
5657 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005658 final long elapsedRealtime = mClocks.elapsedRealtime();
5659 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005660 mCameraOnNesting = 0;
5661 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5662 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5663 + Integer.toHexString(mHistoryCur.states2));
5664 addHistoryRecordLocked(elapsedRealtime, uptime);
5665 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5666 for (int i=0; i<mUidStats.size(); i++) {
5667 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5668 uid.noteResetCameraLocked(elapsedRealtime);
5669 }
5670 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005671 }
5672
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005673 public void noteResetFlashlightLocked() {
5674 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005675 final long elapsedRealtime = mClocks.elapsedRealtime();
5676 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005677 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005678 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5679 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005680 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005681 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005682 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5683 for (int i=0; i<mUidStats.size(); i++) {
5684 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5685 uid.noteResetFlashlightLocked(elapsedRealtime);
5686 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005687 }
5688 }
5689
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005690 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5691 boolean isUnoptimized) {
5692 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005693 final long elapsedRealtime = mClocks.elapsedRealtime();
5694 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005695 if (mBluetoothScanNesting == 0) {
5696 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5697 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5698 + Integer.toHexString(mHistoryCur.states2));
5699 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005700 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005701 }
5702 mBluetoothScanNesting++;
Bookatzb1f04f32017-05-19 13:57:32 -07005703 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005704 }
5705
Bookatzb1f04f32017-05-19 13:57:32 -07005706 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005707 final int N = ws.size();
5708 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005709 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5710 }
5711
5712 final List<WorkChain> workChains = ws.getWorkChains();
5713 if (workChains != null) {
5714 for (int i = 0; i < workChains.size(); ++i) {
5715 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5716 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005717 }
5718 }
5719
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005720 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5721 boolean isUnoptimized) {
5722 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005723 final long elapsedRealtime = mClocks.elapsedRealtime();
5724 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005725 mBluetoothScanNesting--;
5726 if (mBluetoothScanNesting == 0) {
5727 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5728 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5729 + Integer.toHexString(mHistoryCur.states2));
5730 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005731 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005732 }
Bookatz94c5a312017-07-11 16:49:17 -07005733 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005734 }
5735
5736 private int getAttributionUid(int uid, WorkChain workChain) {
5737 if (workChain != null) {
5738 return mapUid(workChain.getAttributionUid());
5739 }
5740
5741 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005742 }
5743
Bookatz94c5a312017-07-11 16:49:17 -07005744 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005745 final int N = ws.size();
5746 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005747 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5748 }
5749
5750 final List<WorkChain> workChains = ws.getWorkChains();
5751 if (workChains != null) {
5752 for (int i = 0; i < workChains.size(); ++i) {
5753 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5754 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005755 }
5756 }
5757
5758 public void noteResetBluetoothScanLocked() {
5759 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005760 final long elapsedRealtime = mClocks.elapsedRealtime();
5761 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005762 mBluetoothScanNesting = 0;
5763 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5764 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5765 + Integer.toHexString(mHistoryCur.states2));
5766 addHistoryRecordLocked(elapsedRealtime, uptime);
5767 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
5768 for (int i=0; i<mUidStats.size(); i++) {
5769 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5770 uid.noteResetBluetoothScanLocked(elapsedRealtime);
5771 }
5772 }
5773 }
5774
Bookatz4ebc0642017-05-11 12:21:19 -07005775 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005776 final int N = ws.size();
5777 for (int i = 0; i < N; i++) {
5778 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005779 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005780 StatsLog.write_non_chained(StatsLog.BLE_SCAN_RESULT_RECEIVED, ws.get(i), ws.getName(i),
5781 numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005782 }
5783
5784 final List<WorkChain> workChains = ws.getWorkChains();
5785 if (workChains != null) {
5786 for (int i = 0; i < workChains.size(); ++i) {
5787 final WorkChain wc = workChains.get(i);
5788 int uid = mapUid(wc.getAttributionUid());
5789 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-macafad8c62018-01-05 22:30:49 -08005790 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED,
5791 wc.getUids(), wc.getTags(), numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005792 }
Bookatz956f36bf2017-04-28 09:48:17 -07005793 }
5794 }
5795
Adam Lesinski5f056f62016-07-14 16:56:08 -07005796 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5797 final long uptimeMillis, int uid) {
5798 uid = mapUid(uid);
5799 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5800 uid);
5801 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5802 }
5803
5804 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005805 final long elapsedRealtime = mClocks.elapsedRealtime();
5806 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005807 if (mWifiRadioPowerState != powerState) {
5808 final boolean active =
5809 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5810 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5811 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005812 if (uid > 0) {
5813 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5814 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005815 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005816 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005817 } else {
5818 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005819 mWifiActiveTimer.stopRunningLocked(
5820 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005821 }
5822 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5823 + Integer.toHexString(mHistoryCur.states));
5824 addHistoryRecordLocked(elapsedRealtime, uptime);
5825 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005826 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005827 }
5828 }
5829
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005830 public void noteWifiRunningLocked(WorkSource ws) {
5831 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005832 final long elapsedRealtime = mClocks.elapsedRealtime();
5833 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005834 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005835 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5836 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005837 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005838 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005839 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005840 int N = ws.size();
5841 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005842 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005843 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005844 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005845
5846 List<WorkChain> workChains = ws.getWorkChains();
5847 if (workChains != null) {
5848 for (int i = 0; i < workChains.size(); ++i) {
5849 int uid = mapUid(workChains.get(i).getAttributionUid());
5850 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5851 }
5852 }
5853
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005854 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005855 } else {
5856 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005857 }
5858 }
5859
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005860 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5861 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005862 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005863 int N = oldWs.size();
5864 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005865 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005866 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005867 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005868
5869 List<WorkChain> workChains = oldWs.getWorkChains();
5870 if (workChains != null) {
5871 for (int i = 0; i < workChains.size(); ++i) {
5872 int uid = mapUid(workChains.get(i).getAttributionUid());
5873 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5874 }
5875 }
5876
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005877 N = newWs.size();
5878 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005879 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005880 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005881 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005882
5883 workChains = newWs.getWorkChains();
5884 if (workChains != null) {
5885 for (int i = 0; i < workChains.size(); ++i) {
5886 int uid = mapUid(workChains.get(i).getAttributionUid());
5887 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5888 }
5889 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005890 } else {
5891 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5892 }
5893 }
5894
5895 public void noteWifiStoppedLocked(WorkSource ws) {
5896 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005897 final long elapsedRealtime = mClocks.elapsedRealtime();
5898 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005899 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005900 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5901 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005902 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005903 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005904 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005905 int N = ws.size();
5906 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005907 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005908 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005909 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005910
5911 List<WorkChain> workChains = ws.getWorkChains();
5912 if (workChains != null) {
5913 for (int i = 0; i < workChains.size(); ++i) {
5914 int uid = mapUid(workChains.get(i).getAttributionUid());
5915 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5916 }
5917 }
5918
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005919 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005920 } else {
5921 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005922 }
5923 }
5924
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005925 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5926 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5927 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005928 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005929 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005930 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005931 }
5932 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005933 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005934 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005935 }
5936 }
5937
Dianne Hackborn3251b902014-06-20 14:40:53 -07005938 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5939 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5940 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005941 final long elapsedRealtime = mClocks.elapsedRealtime();
5942 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005943 if (mWifiSupplState >= 0) {
5944 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5945 }
5946 mWifiSupplState = supplState;
5947 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5948 mHistoryCur.states2 =
5949 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5950 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5951 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5952 + Integer.toHexString(mHistoryCur.states2));
5953 addHistoryRecordLocked(elapsedRealtime, uptime);
5954 }
5955 }
5956
5957 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005958 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005959 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5960 if (i == except) {
5961 continue;
5962 }
5963 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5964 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5965 }
5966 }
5967 }
5968
5969 public void noteWifiRssiChangedLocked(int newRssi) {
5970 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5971 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5972 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005973 final long elapsedRealtime = mClocks.elapsedRealtime();
5974 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005975 if (mWifiSignalStrengthBin >= 0) {
5976 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5977 elapsedRealtime);
5978 }
5979 if (strengthBin >= 0) {
5980 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5981 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
5982 }
5983 mHistoryCur.states2 =
5984 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5985 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5986 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5987 + Integer.toHexString(mHistoryCur.states2));
5988 addHistoryRecordLocked(elapsedRealtime, uptime);
5989 } else {
5990 stopAllWifiSignalStrengthTimersLocked(-1);
5991 }
Bookatz235343d2018-03-26 13:03:50 -07005992 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07005993 mWifiSignalStrengthBin = strengthBin;
5994 }
5995 }
5996
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005997 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005998
The Android Open Source Project10592532009-03-18 17:39:46 -07005999 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006000 final long elapsedRealtime = mClocks.elapsedRealtime();
6001 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006002 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006003 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006004 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
6005 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006006 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006007 }
6008 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006009 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006010 }
6011
6012 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006013 final long elapsedRealtime = mClocks.elapsedRealtime();
6014 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006015 mWifiFullLockNesting--;
6016 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006017 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006018 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
6019 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006020 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006021 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006022 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006023 }
6024
Nick Pelly6ccaa542012-06-15 15:22:47 -07006025 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006026
Nick Pelly6ccaa542012-06-15 15:22:47 -07006027 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006028 final long elapsedRealtime = mClocks.elapsedRealtime();
6029 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006030 if (mWifiScanNesting == 0) {
6031 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
6032 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006033 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006034 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006035 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006036 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006037 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006038 }
6039
Nick Pelly6ccaa542012-06-15 15:22:47 -07006040 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006041 final long elapsedRealtime = mClocks.elapsedRealtime();
6042 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006043 mWifiScanNesting--;
6044 if (mWifiScanNesting == 0) {
6045 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
6046 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006047 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006048 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006049 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006050 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006051 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006052
Robert Greenwalta029ea12013-09-25 16:38:12 -07006053 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006054 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006055 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006056 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006057 }
6058
6059 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006060 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006061 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006062 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006063 }
6064
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006065 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006066
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006067 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006068 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006069 final long elapsedRealtime = mClocks.elapsedRealtime();
6070 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006071 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006072 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006073 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
6074 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006075 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006076
6077 // Start Wifi Multicast overall timer
6078 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
6079 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
6080 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
6081 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006082 }
6083 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006084 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006085 }
6086
6087 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006088 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006089 final long elapsedRealtime = mClocks.elapsedRealtime();
6090 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006091 mWifiMulticastNesting--;
6092 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006093 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006094 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
6095 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006096 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006097
6098 // Stop Wifi Multicast overall timer
6099 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
6100 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
6101 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
6102 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006103 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006104 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006105 }
6106
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006107 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
6108 int N = ws.size();
6109 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006110 final int uid = mapUid(ws.get(i));
6111 noteFullWifiLockAcquiredLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006112 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6113 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006114 }
6115
6116 final List<WorkChain> workChains = ws.getWorkChains();
6117 if (workChains != null) {
6118 for (int i = 0; i < workChains.size(); ++i) {
6119 final WorkChain workChain = workChains.get(i);
6120 final int uid = mapUid(workChain.getAttributionUid());
6121 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006122 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006123 workChain.getUids(), workChain.getTags(),
6124 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006125 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006126 }
6127 }
6128
6129 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
6130 int N = ws.size();
6131 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006132 final int uid = mapUid(ws.get(i));
6133 noteFullWifiLockReleasedLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006134 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6135 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006136 }
6137
6138 final List<WorkChain> workChains = ws.getWorkChains();
6139 if (workChains != null) {
6140 for (int i = 0; i < workChains.size(); ++i) {
6141 final WorkChain workChain = workChains.get(i);
6142 final int uid = mapUid(workChain.getAttributionUid());
6143 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006144 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006145 workChain.getUids(), workChain.getTags(),
6146 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006147 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006148 }
6149 }
6150
Nick Pelly6ccaa542012-06-15 15:22:47 -07006151 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006152 int N = ws.size();
6153 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006154 final int uid = mapUid(ws.get(i));
6155 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006156 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006157 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006158 }
6159
6160 final List<WorkChain> workChains = ws.getWorkChains();
6161 if (workChains != null) {
6162 for (int i = 0; i < workChains.size(); ++i) {
6163 final WorkChain workChain = workChains.get(i);
6164 final int uid = mapUid(workChain.getAttributionUid());
6165 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006166 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08006167 workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006168 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006169 }
6170 }
6171
Nick Pelly6ccaa542012-06-15 15:22:47 -07006172 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006173 int N = ws.size();
6174 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006175 final int uid = mapUid(ws.get(i));
6176 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006177 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006178 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006179 }
6180
6181 final List<WorkChain> workChains = ws.getWorkChains();
6182 if (workChains != null) {
6183 for (int i = 0; i < workChains.size(); ++i) {
6184 final WorkChain workChain = workChains.get(i);
6185 final int uid = mapUid(workChain.getAttributionUid());
6186 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006187 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006188 workChain.getUids(), workChain.getTags(),
6189 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006190 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006191 }
6192 }
6193
Robert Greenwalta029ea12013-09-25 16:38:12 -07006194 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6195 int N = ws.size();
6196 for (int i=0; i<N; i++) {
6197 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6198 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006199
6200 final List<WorkChain> workChains = ws.getWorkChains();
6201 if (workChains != null) {
6202 for (int i = 0; i < workChains.size(); ++i) {
6203 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6204 }
6205 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006206 }
6207
6208 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6209 int N = ws.size();
6210 for (int i=0; i<N; i++) {
6211 noteWifiBatchedScanStoppedLocked(ws.get(i));
6212 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006213
6214 final List<WorkChain> workChains = ws.getWorkChains();
6215 if (workChains != null) {
6216 for (int i = 0; i < workChains.size(); ++i) {
6217 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6218 }
6219 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006220 }
6221
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006222 private static String[] includeInStringArray(String[] array, String str) {
6223 if (ArrayUtils.indexOf(array, str) >= 0) {
6224 return array;
6225 }
6226 String[] newArray = new String[array.length+1];
6227 System.arraycopy(array, 0, newArray, 0, array.length);
6228 newArray[array.length] = str;
6229 return newArray;
6230 }
6231
6232 private static String[] excludeFromStringArray(String[] array, String str) {
6233 int index = ArrayUtils.indexOf(array, str);
6234 if (index >= 0) {
6235 String[] newArray = new String[array.length-1];
6236 if (index > 0) {
6237 System.arraycopy(array, 0, newArray, 0, index);
6238 }
6239 if (index < array.length-1) {
6240 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6241 }
6242 return newArray;
6243 }
6244 return array;
6245 }
6246
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006247 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006248 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006249
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006250 synchronized (mModemNetworkLock) {
6251 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6252 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6253 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6254 } else {
6255 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6256 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6257 }
6258 }
6259
6260 synchronized (mWifiNetworkLock) {
6261 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6262 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6263 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6264 } else {
6265 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6266 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6267 }
6268 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006269 }
6270
David Chenc8a43242017-10-17 16:23:28 -07006271 public String[] getWifiIfaces() {
6272 synchronized (mWifiNetworkLock) {
6273 return mWifiIfaces;
6274 }
6275 }
6276
6277 public String[] getMobileIfaces() {
6278 synchronized (mModemNetworkLock) {
6279 return mModemIfaces;
6280 }
6281 }
6282
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006283 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6284 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006286
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006287 @Override public int getScreenOnCount(int which) {
6288 return mScreenOnTimer.getCountLocked(which);
6289 }
6290
Mike Mac2f518a2017-09-19 16:06:03 -07006291 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6292 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6293 }
6294
6295 @Override public int getScreenDozeCount(int which) {
6296 return mScreenDozeTimer.getCountLocked(which);
6297 }
6298
Dianne Hackborn617f8772009-03-31 15:04:46 -07006299 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006300 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006301 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006302 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006303 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006304
Kweku Adams87b19ec2017-10-09 12:40:03 -07006305 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6306 return mScreenBrightnessTimer[brightnessBin];
6307 }
6308
Jeff Browne95c3cd2014-05-02 16:59:26 -07006309 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6310 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006311 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006312
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006313 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6314 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006315 }
6316
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006317 @Override public int getPowerSaveModeEnabledCount(int which) {
6318 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6319 }
6320
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006321 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6322 int which) {
6323 switch (mode) {
6324 case DEVICE_IDLE_MODE_LIGHT:
6325 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006326 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006327 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6328 }
6329 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006330 }
6331
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006332 @Override public int getDeviceIdleModeCount(int mode, int which) {
6333 switch (mode) {
6334 case DEVICE_IDLE_MODE_LIGHT:
6335 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006336 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006337 return mDeviceIdleModeFullTimer.getCountLocked(which);
6338 }
6339 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006340 }
6341
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006342 @Override public long getLongestDeviceIdleModeTime(int mode) {
6343 switch (mode) {
6344 case DEVICE_IDLE_MODE_LIGHT:
6345 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006346 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006347 return mLongestFullIdleTime;
6348 }
6349 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006350 }
6351
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006352 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6353 switch (mode) {
6354 case DEVICE_IDLE_MODE_LIGHT:
6355 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006356 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006357 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6358 }
6359 return 0;
6360 }
6361
6362 @Override public int getDeviceIdlingCount(int mode, int which) {
6363 switch (mode) {
6364 case DEVICE_IDLE_MODE_LIGHT:
6365 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006366 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006367 return mDeviceIdlingTimer.getCountLocked(which);
6368 }
6369 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006370 }
6371
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006372 @Override public int getNumConnectivityChange(int which) {
6373 int val = mNumConnectivityChange;
6374 if (which == STATS_CURRENT) {
6375 val -= mLoadedNumConnectivityChange;
6376 } else if (which == STATS_SINCE_UNPLUGGED) {
6377 val -= mUnpluggedNumConnectivityChange;
6378 }
6379 return val;
6380 }
6381
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006382 @Override public long getGpsSignalQualityTime(int strengthBin,
6383 long elapsedRealtimeUs, int which) {
6384 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6385 return 0;
6386 }
6387 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6388 elapsedRealtimeUs, which);
6389 }
6390
6391 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006392 final double opVolt = mPowerProfile.getAveragePower(
6393 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6394 if (opVolt == 0) {
6395 return 0;
6396 }
6397 double energyUsedMaMs = 0.0;
6398 final int which = STATS_SINCE_CHARGED;
6399 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6400 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6401 energyUsedMaMs
6402 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6403 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6404 }
6405 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006406 }
6407
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006408 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6409 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006411
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006412 @Override public int getPhoneOnCount(int which) {
6413 return mPhoneOnTimer.getCountLocked(which);
6414 }
6415
Dianne Hackborn627bba72009-03-24 22:32:56 -07006416 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006417 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006418 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006419 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006420 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006421
6422 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006423 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006424 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006425 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006426 }
6427
Kweku Adams87b19ec2017-10-09 12:40:03 -07006428 @Override public Timer getPhoneSignalScanningTimer() {
6429 return mPhoneSignalScanningTimer;
6430 }
6431
Catherine Liufb900812012-07-17 14:12:56 -05006432 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6433 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006434 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006435
Kweku Adams87b19ec2017-10-09 12:40:03 -07006436 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6437 return mPhoneSignalStrengthsTimer[strengthBin];
6438 }
6439
Dianne Hackborn627bba72009-03-24 22:32:56 -07006440 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006441 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006442 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006443 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006444 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006445
Dianne Hackborn617f8772009-03-31 15:04:46 -07006446 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006447 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006448 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006449
Kweku Adams87b19ec2017-10-09 12:40:03 -07006450 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6451 return mPhoneDataConnectionsTimer[dataType];
6452 }
6453
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006454 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6455 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006456 }
6457
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006458 @Override public int getMobileRadioActiveCount(int which) {
6459 return mMobileRadioActiveTimer.getCountLocked(which);
6460 }
6461
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006462 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6463 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6464 }
6465
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006466 @Override public long getMobileRadioActiveUnknownTime(int which) {
6467 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6468 }
6469
6470 @Override public int getMobileRadioActiveUnknownCount(int which) {
6471 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6472 }
6473
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006474 @Override public long getWifiMulticastWakelockTime(
6475 long elapsedRealtimeUs, int which) {
6476 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6477 elapsedRealtimeUs, which);
6478 }
6479
6480 @Override public int getWifiMulticastWakelockCount(int which) {
6481 return mWifiMulticastWakelockTimer.getCountLocked(which);
6482 }
6483
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006484 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6485 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006486 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006487
Siddharth Rayb50a6842017-12-14 15:15:28 -08006488 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6489 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6490 }
6491
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006492 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6493 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006494 }
6495
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006496 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006497 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006498 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006499 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006500 }
6501
6502 @Override public int getWifiStateCount(int wifiState, int which) {
6503 return mWifiStateTimer[wifiState].getCountLocked(which);
6504 }
6505
Kweku Adams87b19ec2017-10-09 12:40:03 -07006506 @Override public Timer getWifiStateTimer(int wifiState) {
6507 return mWifiStateTimer[wifiState];
6508 }
6509
Dianne Hackborn3251b902014-06-20 14:40:53 -07006510 @Override public long getWifiSupplStateTime(int state,
6511 long elapsedRealtimeUs, int which) {
6512 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6513 elapsedRealtimeUs, which);
6514 }
6515
6516 @Override public int getWifiSupplStateCount(int state, int which) {
6517 return mWifiSupplStateTimer[state].getCountLocked(which);
6518 }
6519
Kweku Adams87b19ec2017-10-09 12:40:03 -07006520 @Override public Timer getWifiSupplStateTimer(int state) {
6521 return mWifiSupplStateTimer[state];
6522 }
6523
Dianne Hackborn3251b902014-06-20 14:40:53 -07006524 @Override public long getWifiSignalStrengthTime(int strengthBin,
6525 long elapsedRealtimeUs, int which) {
6526 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6527 elapsedRealtimeUs, which);
6528 }
6529
6530 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6531 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6532 }
6533
Kweku Adams87b19ec2017-10-09 12:40:03 -07006534 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6535 return mWifiSignalStrengthsTimer[strengthBin];
6536 }
6537
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006538 @Override
6539 public ControllerActivityCounter getBluetoothControllerActivity() {
6540 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006541 }
6542
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006543 @Override
6544 public ControllerActivityCounter getWifiControllerActivity() {
6545 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006546 }
6547
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006548 @Override
6549 public ControllerActivityCounter getModemControllerActivity() {
6550 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006551 }
6552
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006553 @Override
6554 public boolean hasBluetoothActivityReporting() {
6555 return mHasBluetoothReporting;
6556 }
6557
6558 @Override
6559 public boolean hasWifiActivityReporting() {
6560 return mHasWifiReporting;
6561 }
6562
6563 @Override
6564 public boolean hasModemActivityReporting() {
6565 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006566 }
6567
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006568 @Override
6569 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006570 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6571 }
6572
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006573 @Override
6574 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006575 return mFlashlightOnTimer.getCountLocked(which);
6576 }
6577
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006578 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006579 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6580 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6581 }
6582
6583 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006584 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6585 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6586 }
6587
6588 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006589 public long getNetworkActivityBytes(int type, int which) {
6590 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6591 return mNetworkByteActivityCounters[type].getCountLocked(which);
6592 } else {
6593 return 0;
6594 }
6595 }
6596
6597 @Override
6598 public long getNetworkActivityPackets(int type, int which) {
6599 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6600 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006601 } else {
6602 return 0;
6603 }
6604 }
6605
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006606 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006607 final long currentTime = System.currentTimeMillis();
6608 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006609 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6610 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006611 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006612 return mStartClockTime;
6613 }
6614
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006615 @Override public String getStartPlatformVersion() {
6616 return mStartPlatformVersion;
6617 }
6618
6619 @Override public String getEndPlatformVersion() {
6620 return mEndPlatformVersion;
6621 }
6622
6623 @Override public int getParcelVersion() {
6624 return VERSION;
6625 }
6626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627 @Override public boolean getIsOnBattery() {
6628 return mOnBattery;
6629 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6632 return mUidStats;
6633 }
6634
Adam Lesinski5f056f62016-07-14 16:56:08 -07006635 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6636 if (timer != null) {
6637 timer.detach();
6638 }
6639 }
6640
6641 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6642 boolean detachIfReset) {
6643 if (timer != null) {
6644 return timer.reset(detachIfReset);
6645 }
6646 return true;
6647 }
6648
Bookatz867c0d72017-03-07 18:23:42 -08006649 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6650 if (timer != null) {
6651 return timer.reset(detachIfReset);
6652 }
6653 return true;
6654 }
6655
Adam Lesinski5f056f62016-07-14 16:56:08 -07006656 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6657 if (counter != null) {
6658 counter.detach();
6659 }
6660 }
6661
6662 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6663 boolean detachIfReset) {
6664 if (counter != null) {
6665 counter.reset(detachIfReset);
6666 }
6667 }
6668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 /**
6670 * The statistics associated with a particular uid.
6671 */
Joe Onoratoabded112016-02-08 16:49:39 -08006672 public static class Uid extends BatteryStats.Uid {
6673 /**
6674 * BatteryStatsImpl that we are associated with.
6675 */
6676 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006678 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006679
Bookatz867c0d72017-03-07 18:23:42 -08006680 /** TimeBase for when uid is in background and device is on battery. */
6681 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6682 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006683 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6684 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006685
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006686 boolean mWifiRunning;
6687 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006688
The Android Open Source Project10592532009-03-18 17:39:46 -07006689 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006690 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006691
Nick Pelly6ccaa542012-06-15 15:22:47 -07006692 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006693 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006694
Dianne Hackborn61659e52014-07-09 16:13:01 -07006695 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006696 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6697 StopwatchTimer[] mWifiBatchedScanTimer;
6698
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006699 boolean mWifiMulticastEnabled;
6700 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006701
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006702 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006703 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006704 StopwatchTimer mFlashlightTurnedOnTimer;
6705 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006706 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006707 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006708 /** Total time spent by the uid holding any partial wakelocks. */
6709 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006710 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006711 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006712 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006713 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006714
Dianne Hackborna8d10942015-11-19 17:55:19 -08006715 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006716 StopwatchTimer[] mProcessStateTimer;
6717
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006718 boolean mInForegroundService = false;
6719
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006720 BatchTimer mVibratorOnTimer;
6721
Dianne Hackborn617f8772009-03-31 15:04:46 -07006722 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006723
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006724 LongSamplingCounter[] mNetworkByteActivityCounters;
6725 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006726 LongSamplingCounter mMobileRadioActiveTime;
6727 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006730 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6731 */
6732 private LongSamplingCounter mMobileRadioApWakeupCount;
6733
6734 /**
6735 * How many times this UID woke up the Application Processor due to a Wifi packet.
6736 */
6737 private LongSamplingCounter mWifiRadioApWakeupCount;
6738
6739 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006740 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006741 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006742 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006743 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006744
6745 /**
6746 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006747 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006748 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006749 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6750
6751 /**
6752 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6753 * Can be null if the UID has had no such activity.
6754 */
6755 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006756
6757 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006758 * The CPU times we had at the last history details update.
6759 */
6760 long mLastStepUserTime;
6761 long mLastStepSystemTime;
6762 long mCurStepUserTime;
6763 long mCurStepSystemTime;
6764
Joe Onoratoabded112016-02-08 16:49:39 -08006765 LongSamplingCounter mUserCpuTime;
6766 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006767 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006768 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006769
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006770 LongSamplingCounterArray mCpuFreqTimeMs;
6771 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006772 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006773
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006774 LongSamplingCounterArray[] mProcStateTimeMs;
6775 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6776
6777 IntArray mChildUids;
6778
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006779 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006780 * The statistics we have collected for this uid's wake locks.
6781 */
Joe Onoratoabded112016-02-08 16:49:39 -08006782 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783
6784 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006785 * The statistics we have collected for this uid's syncs.
6786 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006787 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006788
6789 /**
6790 * The statistics we have collected for this uid's jobs.
6791 */
Bookatzaa4594a2017-03-24 12:39:56 -07006792 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006793
6794 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006795 * Count of the jobs that have completed and the reasons why they completed.
6796 */
6797 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6798
6799 /**
Amith Yamasani977e11f2018-02-16 11:29:54 -08006800 * Count of app launch events that had associated deferred job counts or info about
6801 * last time a job was run.
6802 */
6803 Counter mJobsDeferredEventCount;
6804
6805 /**
6806 * Count of deferred jobs that were pending when the app was launched or brought to
6807 * the foreground through a user interaction.
6808 */
6809 Counter mJobsDeferredCount;
6810
6811 /**
6812 * Sum of time since the last time a job was run for this app before it was launched.
6813 */
6814 LongSamplingCounter mJobsFreshnessTimeMs;
6815
6816 /**
6817 * Array of counts of instances where the time since the last job was run for the app
6818 * fell within one of the thresholds in {@link #JOB_FRESHNESS_BUCKETS}.
6819 */
6820 final Counter[] mJobsFreshnessBuckets;
6821
6822 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006823 * The statistics we have collected for this uid's sensor activations.
6824 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006825 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006826
6827 /**
6828 * The statistics we have collected for this uid's processes.
6829 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006830 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006831
6832 /**
6833 * The statistics we have collected for this uid's processes.
6834 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006835 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006836
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006837 /**
6838 * The transient wake stats we have collected for this uid's pids.
6839 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006840 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006841
Joe Onoratoabded112016-02-08 16:49:39 -08006842 public Uid(BatteryStatsImpl bsi, int uid) {
6843 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006845
Bookatz867c0d72017-03-07 18:23:42 -08006846 mOnBatteryBackgroundTimeBase = new TimeBase();
6847 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6848 mBsi.mClocks.elapsedRealtime() * 1000);
6849
Bookatzc8c44962017-05-11 12:12:54 -07006850 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6851 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6852 mBsi.mClocks.elapsedRealtime() * 1000);
6853
Joe Onoratoabded112016-02-08 16:49:39 -08006854 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6855 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006856 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6857 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006858
Dianne Hackborn657153b2016-07-29 14:54:14 -07006859 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006860 @Override public Wakelock instantiateObject() {
6861 return new Wakelock(mBsi, Uid.this);
6862 }
6863 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006864 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6865 @Override public DualTimer instantiateObject() {
6866 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6867 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006868 }
6869 };
Bookatzaa4594a2017-03-24 12:39:56 -07006870 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6871 @Override public DualTimer instantiateObject() {
6872 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6873 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006874 }
6875 };
6876
6877 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6878 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6879 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6880 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006881 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6882 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006883 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006884 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6885 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006886 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
Amith Yamasani977e11f2018-02-16 11:29:54 -08006887 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase);
6888 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase);
6889 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6890 mJobsFreshnessBuckets = new Counter[JOB_FRESHNESS_BUCKETS.length];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006891 }
6892
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006893 @VisibleForTesting
6894 public void setProcessStateForTest(int procState) {
6895 mProcessState = procState;
6896 }
6897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006898 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006899 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006900 return nullIfAllZeros(mCpuFreqTimeMs, which);
6901 }
6902
6903 @Override
6904 public long[] getScreenOffCpuFreqTimes(int which) {
6905 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6906 }
6907
6908 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006909 public long getCpuActiveTime() {
6910 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6911 }
6912
6913 @Override
6914 public long[] getCpuClusterTimes() {
6915 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6916 }
6917
6918
6919 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006920 public long[] getCpuFreqTimes(int which, int procState) {
6921 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006922 return null;
6923 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006924 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006925 return null;
6926 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006927 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6928 mProcStateTimeMs = null;
6929 return null;
6930 }
6931 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6932 }
6933
6934 @Override
6935 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6936 if (which < 0 || which >= NUM_PROCESS_STATE) {
6937 return null;
6938 }
6939 if (mProcStateScreenOffTimeMs == null) {
6940 return null;
6941 }
6942 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6943 mProcStateScreenOffTimeMs = null;
6944 return null;
6945 }
6946 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6947 }
6948
6949 public void addIsolatedUid(int isolatedUid) {
6950 if (mChildUids == null) {
6951 mChildUids = new IntArray();
6952 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6953 return;
6954 }
6955 mChildUids.add(isolatedUid);
6956 }
6957
6958 public void removeIsolatedUid(int isolatedUid) {
6959 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6960 if (idx < 0) {
6961 return;
6962 }
6963 mChildUids.remove(idx);
6964 }
6965
6966 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6967 if (cpuTimesMs == null) {
6968 return null;
6969 }
6970 final long[] counts = cpuTimesMs.getCountsLocked(which);
6971 if (counts == null) {
6972 return null;
6973 }
6974 // Return counts only if at least one of the elements is non-zero.
6975 for (int i = counts.length - 1; i >= 0; --i) {
6976 if (counts[i] != 0) {
6977 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006978 }
6979 }
6980 return null;
6981 }
6982
Sudheer Shankae544d162017-12-28 17:06:20 -08006983 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006984 if (mProcStateTimeMs == null) {
6985 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006986 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006987 if (mProcStateTimeMs[procState] == null
6988 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
6989 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6990 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006991 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006992 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006993 }
6994
Sudheer Shankae544d162017-12-28 17:06:20 -08006995 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6996 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006997 if (mProcStateScreenOffTimeMs == null) {
6998 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006999 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007000 if (mProcStateScreenOffTimeMs[procState] == null
7001 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
7002 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
7003 mBsi.mOnBatteryScreenOffTimeBase);
7004 }
Sudheer Shankae544d162017-12-28 17:06:20 -08007005 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007006 }
7007
7008 @Override
Bookatzc8c44962017-05-11 12:12:54 -07007009 public Timer getAggregatedPartialWakelockTimer() {
7010 return mAggregatedPartialWakelockTimer;
7011 }
7012
7013 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007014 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007015 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007016 }
7017
7018 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07007019 public Timer getMulticastWakelockStats() {
7020 return mWifiMulticastTimer;
7021 }
7022
7023 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007024 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007025 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007026 }
7027
7028 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007029 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007030 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007031 }
7032
7033 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007034 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
7035 return mJobCompletions;
7036 }
7037
7038 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07007039 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007040 return mSensorStats;
7041 }
7042
7043 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007044 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007045 return mProcessStats;
7046 }
7047
7048 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007049 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 return mPackageStats;
7051 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007052
7053 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054 public int getUid() {
7055 return mUid;
7056 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007057
7058 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007059 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007060 if (!mWifiRunning) {
7061 mWifiRunning = true;
7062 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007063 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7064 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007065 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007066 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007067 }
7068 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007069
Dianne Hackborn617f8772009-03-31 15:04:46 -07007070 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007071 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007072 if (mWifiRunning) {
7073 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007074 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007075 }
7076 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007077
Dianne Hackborn617f8772009-03-31 15:04:46 -07007078 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007079 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007080 if (!mFullWifiLockOut) {
7081 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007082 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007083 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7084 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007085 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007086 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007087 }
7088 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007089
The Android Open Source Project10592532009-03-18 17:39:46 -07007090 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007091 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007092 if (mFullWifiLockOut) {
7093 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007094 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007095 }
7096 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007097
The Android Open Source Project10592532009-03-18 17:39:46 -07007098 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007099 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007100 if (!mWifiScanStarted) {
7101 mWifiScanStarted = true;
7102 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007103 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7104 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
7105 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007106 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007107 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007108 }
7109 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007110
The Android Open Source Project10592532009-03-18 17:39:46 -07007111 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007112 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007113 if (mWifiScanStarted) {
7114 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007115 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007116 }
7117 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007118
7119 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007120 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007121 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007122 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007123 csph = csph >> 3;
7124 bin++;
7125 }
7126
7127 if (mWifiBatchedScanBinStarted == bin) return;
7128
7129 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7130 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007131 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007132 }
7133 mWifiBatchedScanBinStarted = bin;
7134 if (mWifiBatchedScanTimer[bin] == null) {
7135 makeWifiBatchedScanBin(bin, null);
7136 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007137 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007138 }
7139
7140 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007141 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007142 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7143 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007144 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007145 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7146 }
7147 }
7148
7149 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007150 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007151 if (!mWifiMulticastEnabled) {
7152 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007153 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007154 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7155 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007156 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007157 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007158 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007159 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7160 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007161 }
7162 }
7163
7164 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007165 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007166 if (mWifiMulticastEnabled) {
7167 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007168 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007169 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007170 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7171 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007172 }
7173 }
7174
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007175 @Override
7176 public ControllerActivityCounter getWifiControllerActivity() {
7177 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007178 }
7179
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007180 @Override
7181 public ControllerActivityCounter getBluetoothControllerActivity() {
7182 return mBluetoothControllerActivity;
7183 }
7184
7185 @Override
7186 public ControllerActivityCounter getModemControllerActivity() {
7187 return mModemControllerActivity;
7188 }
7189
7190 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7191 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007192 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007193 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007194 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007195 return mWifiControllerActivity;
7196 }
7197
7198 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7199 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007200 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007201 NUM_BT_TX_LEVELS);
7202 }
7203 return mBluetoothControllerActivity;
7204 }
7205
7206 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7207 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007208 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007209 ModemActivityInfo.TX_POWER_LEVELS);
7210 }
7211 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007212 }
7213
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007214 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7215 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007216 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7217 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007218 }
7219 return mAudioTurnedOnTimer;
7220 }
7221
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007222 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007223 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7224 }
7225
7226 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7227 if (mAudioTurnedOnTimer != null) {
7228 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007229 }
7230 }
7231
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007232 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7233 if (mAudioTurnedOnTimer != null) {
7234 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007235 }
7236 }
7237
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007238 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7239 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007240 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7241 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007242 }
7243 return mVideoTurnedOnTimer;
7244 }
7245
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007246 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007247 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7248 }
7249
7250 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7251 if (mVideoTurnedOnTimer != null) {
7252 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007253 }
7254 }
7255
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007256 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7257 if (mVideoTurnedOnTimer != null) {
7258 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007259 }
7260 }
7261
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007262 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7263 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007264 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7265 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007266 }
7267 return mFlashlightTurnedOnTimer;
7268 }
7269
7270 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7271 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7272 }
7273
7274 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7275 if (mFlashlightTurnedOnTimer != null) {
7276 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7277 }
7278 }
7279
7280 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7281 if (mFlashlightTurnedOnTimer != null) {
7282 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7283 }
7284 }
7285
7286 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7287 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007288 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7289 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007290 }
7291 return mCameraTurnedOnTimer;
7292 }
7293
7294 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7295 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
7296 }
7297
7298 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7299 if (mCameraTurnedOnTimer != null) {
7300 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
7301 }
7302 }
7303
7304 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7305 if (mCameraTurnedOnTimer != null) {
7306 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
7307 }
7308 }
7309
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007310 public StopwatchTimer createForegroundActivityTimerLocked() {
7311 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007312 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7313 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007314 }
7315 return mForegroundActivityTimer;
7316 }
7317
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007318 public StopwatchTimer createForegroundServiceTimerLocked() {
7319 if (mForegroundServiceTimer == null) {
7320 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7321 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7322 }
7323 return mForegroundServiceTimer;
7324 }
7325
Bookatzc8c44962017-05-11 12:12:54 -07007326 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7327 if (mAggregatedPartialWakelockTimer == null) {
7328 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7329 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7330 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7331 }
7332 return mAggregatedPartialWakelockTimer;
7333 }
7334
Bookatz867c0d72017-03-07 18:23:42 -08007335 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007336 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007337 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7338 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7339 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007340 }
7341 return mBluetoothScanTimer;
7342 }
7343
Bookatzb1f04f32017-05-19 13:57:32 -07007344 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7345 if (mBluetoothUnoptimizedScanTimer == null) {
7346 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7347 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7348 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7349 }
7350 return mBluetoothUnoptimizedScanTimer;
7351 }
7352
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007353 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7354 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007355 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007356 if (isUnoptimized) {
7357 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7358 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007359 }
7360
Bookatz94c5a312017-07-11 16:49:17 -07007361 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007362 if (mBluetoothScanTimer != null) {
7363 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7364 }
Bookatz94c5a312017-07-11 16:49:17 -07007365 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007366 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7367 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007368 }
7369
7370 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7371 if (mBluetoothScanTimer != null) {
7372 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7373 }
Bookatzb1f04f32017-05-19 13:57:32 -07007374 if (mBluetoothUnoptimizedScanTimer != null) {
7375 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7376 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007377 }
7378
Bookatz956f36bf2017-04-28 09:48:17 -07007379 public Counter createBluetoothScanResultCounterLocked() {
7380 if (mBluetoothScanResultCounter == null) {
7381 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7382 }
7383 return mBluetoothScanResultCounter;
7384 }
7385
Bookatzb1f04f32017-05-19 13:57:32 -07007386 public Counter createBluetoothScanResultBgCounterLocked() {
7387 if (mBluetoothScanResultBgCounter == null) {
7388 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7389 }
7390 return mBluetoothScanResultBgCounter;
7391 }
7392
Bookatz4ebc0642017-05-11 12:21:19 -07007393 public void noteBluetoothScanResultsLocked(int numNewResults) {
7394 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007395 // Uses background timebase, so the count will only be incremented if uid in background.
7396 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007397 }
7398
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007399 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007400 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007401 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007402 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007403 }
7404
7405 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007406 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007407 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007408 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007409 }
7410 }
7411
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007412 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7413 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7414 }
7415
7416 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7417 if (mForegroundServiceTimer != null) {
7418 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7419 }
7420 }
7421
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007422 public BatchTimer createVibratorOnTimerLocked() {
7423 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007424 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7425 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007426 }
7427 return mVibratorOnTimer;
7428 }
7429
7430 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007431 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007432 }
7433
7434 public void noteVibratorOffLocked() {
7435 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007436 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007437 }
7438 }
7439
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007440 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007441 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007442 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007443 return 0;
7444 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007445 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007446 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007447
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007448 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007449 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007450 if (mFullWifiLockTimer == null) {
7451 return 0;
7452 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007453 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007454 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007455
7456 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007457 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007458 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007459 return 0;
7460 }
Bookatzaa4594a2017-03-24 12:39:56 -07007461 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007462 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007463
7464 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007465 public int getWifiScanCount(int which) {
7466 if (mWifiScanTimer == null) {
7467 return 0;
7468 }
Bookatzaa4594a2017-03-24 12:39:56 -07007469 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007470 }
7471
7472 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007473 public Timer getWifiScanTimer() {
7474 return mWifiScanTimer;
7475 }
7476
7477 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007478 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007479 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007480 return 0;
7481 }
7482 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7483 }
7484
7485 @Override
7486 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7487 if (mWifiScanTimer == null) {
7488 return 0;
7489 }
7490 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007491 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007492 }
7493
7494 @Override
7495 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007496 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007497 return 0;
7498 }
7499 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7500 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007501 }
7502
7503 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007504 public Timer getWifiScanBackgroundTimer() {
7505 if (mWifiScanTimer == null) {
7506 return null;
7507 }
7508 return mWifiScanTimer.getSubTimer();
7509 }
7510
7511 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007512 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007513 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7514 if (mWifiBatchedScanTimer[csphBin] == null) {
7515 return 0;
7516 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007517 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007518 }
7519
7520 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007521 public int getWifiBatchedScanCount(int csphBin, int which) {
7522 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7523 if (mWifiBatchedScanTimer[csphBin] == null) {
7524 return 0;
7525 }
7526 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7527 }
7528
7529 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007530 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007531 if (mWifiMulticastTimer == null) {
7532 return 0;
7533 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007534 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007535 }
7536
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007537 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007538 public Timer getAudioTurnedOnTimer() {
7539 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007540 }
7541
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007542 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007543 public Timer getVideoTurnedOnTimer() {
7544 return mVideoTurnedOnTimer;
7545 }
7546
7547 @Override
7548 public Timer getFlashlightTurnedOnTimer() {
7549 return mFlashlightTurnedOnTimer;
7550 }
7551
7552 @Override
7553 public Timer getCameraTurnedOnTimer() {
7554 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007555 }
7556
Dianne Hackborn617f8772009-03-31 15:04:46 -07007557 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007558 public Timer getForegroundActivityTimer() {
7559 return mForegroundActivityTimer;
7560 }
7561
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007562 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007563 public Timer getForegroundServiceTimer() {
7564 return mForegroundServiceTimer;
7565 }
7566
7567 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007568 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007569 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007570 }
7571
7572 @Override
7573 public Timer getBluetoothScanBackgroundTimer() {
7574 if (mBluetoothScanTimer == null) {
7575 return null;
7576 }
7577 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007578 }
7579
Bookatz956f36bf2017-04-28 09:48:17 -07007580 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007581 public Timer getBluetoothUnoptimizedScanTimer() {
7582 return mBluetoothUnoptimizedScanTimer;
7583 }
7584
7585 @Override
7586 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7587 if (mBluetoothUnoptimizedScanTimer == null) {
7588 return null;
7589 }
7590 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7591 }
7592
7593 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007594 public Counter getBluetoothScanResultCounter() {
7595 return mBluetoothScanResultCounter;
7596 }
7597
Bookatzb1f04f32017-05-19 13:57:32 -07007598 @Override
7599 public Counter getBluetoothScanResultBgCounter() {
7600 return mBluetoothScanResultBgCounter;
7601 }
7602
Dianne Hackborn61659e52014-07-09 16:13:01 -07007603 void makeProcessState(int i, Parcel in) {
7604 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7605
7606 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007607 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7608 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007609 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007610 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7611 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007612 }
7613 }
7614
7615 @Override
7616 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7617 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7618 if (mProcessStateTimer[state] == null) {
7619 return 0;
7620 }
7621 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7622 }
7623
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007624 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007625 public Timer getProcessStateTimer(int state) {
7626 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7627 return mProcessStateTimer[state];
7628 }
7629
7630 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007631 public Timer getVibratorOnTimer() {
7632 return mVibratorOnTimer;
7633 }
7634
7635 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007636 public void noteUserActivityLocked(int type) {
7637 if (mUserActivityCounters == null) {
7638 initUserActivityLocked();
7639 }
Jeff Browndf693de2012-07-27 12:03:38 -07007640 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7641 mUserActivityCounters[type].stepAtomic();
7642 } else {
7643 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7644 new Throwable());
7645 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007646 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007647
Dianne Hackborn617f8772009-03-31 15:04:46 -07007648 @Override
7649 public boolean hasUserActivity() {
7650 return mUserActivityCounters != null;
7651 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007652
Dianne Hackborn617f8772009-03-31 15:04:46 -07007653 @Override
7654 public int getUserActivityCount(int type, int which) {
7655 if (mUserActivityCounters == null) {
7656 return 0;
7657 }
Evan Millarc64edde2009-04-18 12:26:32 -07007658 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007659 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007660
Robert Greenwalta029ea12013-09-25 16:38:12 -07007661 void makeWifiBatchedScanBin(int i, Parcel in) {
7662 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7663
Joe Onoratoabded112016-02-08 16:49:39 -08007664 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007665 if (collected == null) {
7666 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007667 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007668 }
7669 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007670 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7671 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007672 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007673 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7674 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007675 }
7676 }
7677
7678
Dianne Hackborn617f8772009-03-31 15:04:46 -07007679 void initUserActivityLocked() {
7680 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7681 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007682 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007683 }
7684 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007685
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007686 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7687 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007688 initNetworkActivityLocked();
7689 }
7690 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007691 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7692 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007693 } else {
7694 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7695 new Throwable());
7696 }
7697 }
7698
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007699 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7700 if (mNetworkByteActivityCounters == null) {
7701 initNetworkActivityLocked();
7702 }
7703 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7704 mMobileRadioActiveCount.addCountLocked(1);
7705 }
7706
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007707 @Override
7708 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007709 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007710 }
7711
7712 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007713 public long getNetworkActivityBytes(int type, int which) {
7714 if (mNetworkByteActivityCounters != null && type >= 0
7715 && type < mNetworkByteActivityCounters.length) {
7716 return mNetworkByteActivityCounters[type].getCountLocked(which);
7717 } else {
7718 return 0;
7719 }
7720 }
7721
7722 @Override
7723 public long getNetworkActivityPackets(int type, int which) {
7724 if (mNetworkPacketActivityCounters != null && type >= 0
7725 && type < mNetworkPacketActivityCounters.length) {
7726 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007727 } else {
7728 return 0;
7729 }
7730 }
7731
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007732 @Override
7733 public long getMobileRadioActiveTime(int which) {
7734 return mMobileRadioActiveTime != null
7735 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7736 }
7737
7738 @Override
7739 public int getMobileRadioActiveCount(int which) {
7740 return mMobileRadioActiveCount != null
7741 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7742 }
7743
Adam Lesinskie08af192015-03-25 16:42:59 -07007744 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007745 public long getUserCpuTimeUs(int which) {
7746 return mUserCpuTime.getCountLocked(which);
7747 }
7748
7749 @Override
7750 public long getSystemCpuTimeUs(int which) {
7751 return mSystemCpuTime.getCountLocked(which);
7752 }
7753
7754 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007755 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007756 if (mCpuClusterSpeedTimesUs != null) {
7757 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7758 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7759 if (cpuSpeedTimesUs != null) {
7760 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7761 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007762 if (c != null) {
7763 return c.getCountLocked(which);
7764 }
7765 }
7766 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007767 }
7768 }
7769 return 0;
7770 }
7771
Adam Lesinski5f056f62016-07-14 16:56:08 -07007772 public void noteMobileRadioApWakeupLocked() {
7773 if (mMobileRadioApWakeupCount == null) {
7774 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7775 }
7776 mMobileRadioApWakeupCount.addCountLocked(1);
7777 }
7778
7779 @Override
7780 public long getMobileRadioApWakeupCount(int which) {
7781 if (mMobileRadioApWakeupCount != null) {
7782 return mMobileRadioApWakeupCount.getCountLocked(which);
7783 }
7784 return 0;
7785 }
7786
7787 public void noteWifiRadioApWakeupLocked() {
7788 if (mWifiRadioApWakeupCount == null) {
7789 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7790 }
7791 mWifiRadioApWakeupCount.addCountLocked(1);
7792 }
7793
7794 @Override
7795 public long getWifiRadioApWakeupCount(int which) {
7796 if (mWifiRadioApWakeupCount != null) {
7797 return mWifiRadioApWakeupCount.getCountLocked(which);
7798 }
7799 return 0;
7800 }
7801
Amith Yamasani977e11f2018-02-16 11:29:54 -08007802 @Override
7803 public void getDeferredJobsCheckinLineLocked(StringBuilder sb, int which) {
7804 sb.setLength(0);
7805 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7806 if (deferredEventCount == 0) {
7807 return;
7808 }
7809 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007810 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007811 sb.append(deferredEventCount); sb.append(',');
7812 sb.append(deferredCount); sb.append(',');
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007813 sb.append(totalLatency);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007814 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7815 if (mJobsFreshnessBuckets[i] == null) {
7816 sb.append(",0");
7817 } else {
7818 sb.append(",");
7819 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7820 }
7821 }
7822 }
7823
7824 @Override
7825 public void getDeferredJobsLineLocked(StringBuilder sb, int which) {
7826 sb.setLength(0);
7827 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7828 if (deferredEventCount == 0) {
7829 return;
7830 }
7831 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007832 final long totalLatency = mJobsFreshnessTimeMs.getCountLocked(which);
Amith Yamasani977e11f2018-02-16 11:29:54 -08007833 sb.append("times="); sb.append(deferredEventCount); sb.append(", ");
7834 sb.append("count="); sb.append(deferredCount); sb.append(", ");
Amith Yamasani0ca706b2018-03-01 17:28:59 -08007835 sb.append("totalLatencyMs="); sb.append(totalLatency); sb.append(", ");
Amith Yamasani977e11f2018-02-16 11:29:54 -08007836 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7837 sb.append("<"); sb.append(JOB_FRESHNESS_BUCKETS[i]); sb.append("ms=");
7838 if (mJobsFreshnessBuckets[i] == null) {
7839 sb.append("0");
7840 } else {
7841 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7842 }
7843 sb.append(" ");
7844 }
7845 }
7846
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007847 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007848 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7849 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007850 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007851 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7852 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007853 }
Joe Onoratoabded112016-02-08 16:49:39 -08007854 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7855 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007857
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007858 /**
7859 * Clear all stats for this uid. Returns true if the uid is completely
7860 * inactive so can be dropped.
7861 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007862 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007863 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007864 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007865
Bookatz993a0be2017-07-21 09:03:23 -07007866 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7867 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7868
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007869 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007870 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007871 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007872 }
7873 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007874 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007875 active |= mFullWifiLockOut;
7876 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007877 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007878 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007879 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007880 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007881 if (mWifiBatchedScanTimer != null) {
7882 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7883 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007884 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007885 }
7886 }
7887 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7888 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007889 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007890 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007891 active |= mWifiMulticastEnabled;
7892 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007893
7894 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7895 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7896 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7897 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7898 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007899 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007900 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007901 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007902 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007903 if (mBluetoothScanResultCounter != null) {
7904 mBluetoothScanResultCounter.reset(false);
7905 }
Bookatzb1f04f32017-05-19 13:57:32 -07007906 if (mBluetoothScanResultBgCounter != null) {
7907 mBluetoothScanResultBgCounter.reset(false);
7908 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007909
Dianne Hackborn61659e52014-07-09 16:13:01 -07007910 if (mProcessStateTimer != null) {
7911 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7912 if (mProcessStateTimer[i] != null) {
7913 active |= !mProcessStateTimer[i].reset(false);
7914 }
7915 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007916 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007917 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007918 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007919 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007920 mVibratorOnTimer.detach();
7921 mVibratorOnTimer = null;
7922 } else {
7923 active = true;
7924 }
7925 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007926
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007927 if (mUserActivityCounters != null) {
7928 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7929 mUserActivityCounters[i].reset(false);
7930 }
7931 }
7932
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007933 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007934 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007935 mNetworkByteActivityCounters[i].reset(false);
7936 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007937 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007938 mMobileRadioActiveTime.reset(false);
7939 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007940 }
7941
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007942 if (mWifiControllerActivity != null) {
7943 mWifiControllerActivity.reset(false);
7944 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007945
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007946 if (mBluetoothControllerActivity != null) {
7947 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007948 }
7949
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007950 if (mModemControllerActivity != null) {
7951 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007952 }
7953
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007954 mUserCpuTime.reset(false);
7955 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007956
Sudheer Shankaaf857412017-07-21 00:14:24 -07007957 if (mCpuClusterSpeedTimesUs != null) {
7958 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007959 if (speeds != null) {
7960 for (LongSamplingCounter speed : speeds) {
7961 if (speed != null) {
7962 speed.reset(false);
7963 }
7964 }
7965 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007966 }
7967 }
7968
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007969 if (mCpuFreqTimeMs != null) {
7970 mCpuFreqTimeMs.reset(false);
7971 }
7972 if (mScreenOffCpuFreqTimeMs != null) {
7973 mScreenOffCpuFreqTimeMs.reset(false);
7974 }
7975
Mike Ma3d422c32017-10-25 11:08:57 -07007976 mCpuActiveTimeMs.reset(false);
7977 mCpuClusterTimesMs.reset(false);
7978
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007979 if (mProcStateTimeMs != null) {
7980 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7981 if (counters != null) {
7982 counters.reset(false);
7983 }
7984 }
7985 }
7986 if (mProcStateScreenOffTimeMs != null) {
7987 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7988 if (counters != null) {
7989 counters.reset(false);
7990 }
7991 }
7992 }
7993
Adam Lesinski5f056f62016-07-14 16:56:08 -07007994 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
7995 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
7996
Dianne Hackbornd953c532014-08-16 18:17:38 -07007997 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7998 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
7999 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008000 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008001 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008002 } else {
8003 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008004 }
8005 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008006 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07008007 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008008 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008009 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008010 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008011 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008012 timer.detach();
8013 } else {
8014 active = true;
8015 }
8016 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008017 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07008018 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008019 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07008020 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008021 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008022 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008023 timer.detach();
8024 } else {
8025 active = true;
8026 }
8027 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008028 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008029 mJobCompletions.clear();
Amith Yamasani977e11f2018-02-16 11:29:54 -08008030
8031 mJobsDeferredEventCount.reset(false);
8032 mJobsDeferredCount.reset(false);
8033 mJobsFreshnessTimeMs.reset(false);
8034 for (int ij = 0; ij < JOB_FRESHNESS_BUCKETS.length; ij++) {
8035 if (mJobsFreshnessBuckets[ij] != null) {
8036 mJobsFreshnessBuckets[ij].reset(false);
8037 }
8038 }
8039
Dianne Hackborn61659e52014-07-09 16:13:01 -07008040 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
8041 Sensor s = mSensorStats.valueAt(ise);
8042 if (s.reset()) {
8043 mSensorStats.removeAt(ise);
8044 } else {
8045 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008046 }
8047 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08008048
Dianne Hackborn61659e52014-07-09 16:13:01 -07008049 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
8050 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008051 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008052 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008053 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008054 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008055 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008056 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008057 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008058 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008059 } else {
8060 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008061 }
8062 }
8063 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008064 if (mPackageStats.size() > 0) {
8065 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
8066 while (it.hasNext()) {
8067 Map.Entry<String, Pkg> pkgEntry = it.next();
8068 Pkg p = pkgEntry.getValue();
8069 p.detach();
8070 if (p.mServiceStats.size() > 0) {
8071 Iterator<Map.Entry<String, Pkg.Serv>> it2
8072 = p.mServiceStats.entrySet().iterator();
8073 while (it2.hasNext()) {
8074 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
8075 servEntry.getValue().detach();
8076 }
8077 }
8078 }
8079 mPackageStats.clear();
8080 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008081
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008082 mLastStepUserTime = mLastStepSystemTime = 0;
8083 mCurStepUserTime = mCurStepSystemTime = 0;
8084
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008085 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008086 if (mWifiRunningTimer != null) {
8087 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008088 }
8089 if (mFullWifiLockTimer != null) {
8090 mFullWifiLockTimer.detach();
8091 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008092 if (mWifiScanTimer != null) {
8093 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008094 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008095 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8096 if (mWifiBatchedScanTimer[i] != null) {
8097 mWifiBatchedScanTimer[i].detach();
8098 }
8099 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008100 if (mWifiMulticastTimer != null) {
8101 mWifiMulticastTimer.detach();
8102 }
8103 if (mAudioTurnedOnTimer != null) {
8104 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008105 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008106 }
8107 if (mVideoTurnedOnTimer != null) {
8108 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008109 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008110 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008111 if (mFlashlightTurnedOnTimer != null) {
8112 mFlashlightTurnedOnTimer.detach();
8113 mFlashlightTurnedOnTimer = null;
8114 }
8115 if (mCameraTurnedOnTimer != null) {
8116 mCameraTurnedOnTimer.detach();
8117 mCameraTurnedOnTimer = null;
8118 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008119 if (mForegroundActivityTimer != null) {
8120 mForegroundActivityTimer.detach();
8121 mForegroundActivityTimer = null;
8122 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008123 if (mForegroundServiceTimer != null) {
8124 mForegroundServiceTimer.detach();
8125 mForegroundServiceTimer = null;
8126 }
Bookatzc8c44962017-05-11 12:12:54 -07008127 if (mAggregatedPartialWakelockTimer != null) {
8128 mAggregatedPartialWakelockTimer.detach();
8129 mAggregatedPartialWakelockTimer = null;
8130 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008131 if (mBluetoothScanTimer != null) {
8132 mBluetoothScanTimer.detach();
8133 mBluetoothScanTimer = null;
8134 }
Bookatzb1f04f32017-05-19 13:57:32 -07008135 if (mBluetoothUnoptimizedScanTimer != null) {
8136 mBluetoothUnoptimizedScanTimer.detach();
8137 mBluetoothUnoptimizedScanTimer = null;
8138 }
Bookatz956f36bf2017-04-28 09:48:17 -07008139 if (mBluetoothScanResultCounter != null) {
8140 mBluetoothScanResultCounter.detach();
8141 mBluetoothScanResultCounter = null;
8142 }
Bookatzb1f04f32017-05-19 13:57:32 -07008143 if (mBluetoothScanResultBgCounter != null) {
8144 mBluetoothScanResultBgCounter.detach();
8145 mBluetoothScanResultBgCounter = null;
8146 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008147 if (mUserActivityCounters != null) {
8148 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8149 mUserActivityCounters[i].detach();
8150 }
8151 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008152 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008153 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008154 mNetworkByteActivityCounters[i].detach();
8155 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008156 }
8157 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008158
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008159 if (mWifiControllerActivity != null) {
8160 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008161 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008162
8163 if (mBluetoothControllerActivity != null) {
8164 mBluetoothControllerActivity.detach();
8165 }
8166
8167 if (mModemControllerActivity != null) {
8168 mModemControllerActivity.detach();
8169 }
8170
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008171 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008172
8173 mUserCpuTime.detach();
8174 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008175
Sudheer Shankaaf857412017-07-21 00:14:24 -07008176 if (mCpuClusterSpeedTimesUs != null) {
8177 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008178 if (cpuSpeeds != null) {
8179 for (LongSamplingCounter c : cpuSpeeds) {
8180 if (c != null) {
8181 c.detach();
8182 }
8183 }
8184 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008185 }
8186 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008187
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008188 if (mCpuFreqTimeMs != null) {
8189 mCpuFreqTimeMs.detach();
8190 }
8191 if (mScreenOffCpuFreqTimeMs != null) {
8192 mScreenOffCpuFreqTimeMs.detach();
8193 }
Mike Ma3d422c32017-10-25 11:08:57 -07008194 mCpuActiveTimeMs.detach();
8195 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008196
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008197 if (mProcStateTimeMs != null) {
8198 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8199 if (counters != null) {
8200 counters.detach();
8201 }
8202 }
8203 }
8204 if (mProcStateScreenOffTimeMs != null) {
8205 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8206 if (counters != null) {
8207 counters.detach();
8208 }
8209 }
8210 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008211 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8212 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008213 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008214
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008215 return !active;
8216 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008217
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008218 void writeJobCompletionsToParcelLocked(Parcel out) {
8219 int NJC = mJobCompletions.size();
8220 out.writeInt(NJC);
8221 for (int ijc=0; ijc<NJC; ijc++) {
8222 out.writeString(mJobCompletions.keyAt(ijc));
8223 SparseIntArray types = mJobCompletions.valueAt(ijc);
8224 int NT = types.size();
8225 out.writeInt(NT);
8226 for (int it=0; it<NT; it++) {
8227 out.writeInt(types.keyAt(it));
8228 out.writeInt(types.valueAt(it));
8229 }
8230 }
8231 }
8232
Bookatz867c0d72017-03-07 18:23:42 -08008233 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8234 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008235 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008236
Dianne Hackbornd953c532014-08-16 18:17:38 -07008237 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8238 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008239 out.writeInt(NW);
8240 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008241 out.writeString(wakeStats.keyAt(iw));
8242 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008243 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008244 }
8245
Bookatz2bffb5b2017-04-13 11:59:33 -07008246 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008247 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008248 out.writeInt(NS);
8249 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008250 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008251 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008252 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8253 }
8254
Bookatzaa4594a2017-03-24 12:39:56 -07008255 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008256 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008257 out.writeInt(NJ);
8258 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008259 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008260 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008261 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8262 }
8263
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008264 writeJobCompletionsToParcelLocked(out);
8265
Amith Yamasani977e11f2018-02-16 11:29:54 -08008266 mJobsDeferredEventCount.writeToParcel(out);
8267 mJobsDeferredCount.writeToParcel(out);
8268 mJobsFreshnessTimeMs.writeToParcel(out);
8269 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8270 Counter.writeCounterToParcel(out, mJobsFreshnessBuckets[i]);
8271 }
8272
Dianne Hackborn61659e52014-07-09 16:13:01 -07008273 int NSE = mSensorStats.size();
8274 out.writeInt(NSE);
8275 for (int ise=0; ise<NSE; ise++) {
8276 out.writeInt(mSensorStats.keyAt(ise));
8277 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008278 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008279 }
8280
Dianne Hackborn61659e52014-07-09 16:13:01 -07008281 int NP = mProcessStats.size();
8282 out.writeInt(NP);
8283 for (int ip=0; ip<NP; ip++) {
8284 out.writeString(mProcessStats.keyAt(ip));
8285 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008286 proc.writeToParcelLocked(out);
8287 }
8288
8289 out.writeInt(mPackageStats.size());
8290 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8291 out.writeString(pkgEntry.getKey());
8292 Uid.Pkg pkg = pkgEntry.getValue();
8293 pkg.writeToParcelLocked(out);
8294 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008295
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008296 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008297 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008298 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008299 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008300 out.writeInt(0);
8301 }
8302 if (mFullWifiLockTimer != null) {
8303 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008304 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008305 } else {
8306 out.writeInt(0);
8307 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008308 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008309 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008310 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008311 } else {
8312 out.writeInt(0);
8313 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008314 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8315 if (mWifiBatchedScanTimer[i] != null) {
8316 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008317 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008318 } else {
8319 out.writeInt(0);
8320 }
8321 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008322 if (mWifiMulticastTimer != null) {
8323 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008324 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008325 } else {
8326 out.writeInt(0);
8327 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008328
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008329 if (mAudioTurnedOnTimer != null) {
8330 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008331 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008332 } else {
8333 out.writeInt(0);
8334 }
8335 if (mVideoTurnedOnTimer != null) {
8336 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008337 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008338 } else {
8339 out.writeInt(0);
8340 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008341 if (mFlashlightTurnedOnTimer != null) {
8342 out.writeInt(1);
8343 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8344 } else {
8345 out.writeInt(0);
8346 }
8347 if (mCameraTurnedOnTimer != null) {
8348 out.writeInt(1);
8349 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8350 } else {
8351 out.writeInt(0);
8352 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008353 if (mForegroundActivityTimer != null) {
8354 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008355 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008356 } else {
8357 out.writeInt(0);
8358 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008359 if (mForegroundServiceTimer != null) {
8360 out.writeInt(1);
8361 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8362 } else {
8363 out.writeInt(0);
8364 }
Bookatzc8c44962017-05-11 12:12:54 -07008365 if (mAggregatedPartialWakelockTimer != null) {
8366 out.writeInt(1);
8367 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8368 } else {
8369 out.writeInt(0);
8370 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008371 if (mBluetoothScanTimer != null) {
8372 out.writeInt(1);
8373 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8374 } else {
8375 out.writeInt(0);
8376 }
Bookatzb1f04f32017-05-19 13:57:32 -07008377 if (mBluetoothUnoptimizedScanTimer != null) {
8378 out.writeInt(1);
8379 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8380 } else {
8381 out.writeInt(0);
8382 }
Bookatz956f36bf2017-04-28 09:48:17 -07008383 if (mBluetoothScanResultCounter != null) {
8384 out.writeInt(1);
8385 mBluetoothScanResultCounter.writeToParcel(out);
8386 } else {
8387 out.writeInt(0);
8388 }
Bookatzb1f04f32017-05-19 13:57:32 -07008389 if (mBluetoothScanResultBgCounter != null) {
8390 out.writeInt(1);
8391 mBluetoothScanResultBgCounter.writeToParcel(out);
8392 } else {
8393 out.writeInt(0);
8394 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008395 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8396 if (mProcessStateTimer[i] != null) {
8397 out.writeInt(1);
8398 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8399 } else {
8400 out.writeInt(0);
8401 }
8402 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008403 if (mVibratorOnTimer != null) {
8404 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008405 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008406 } else {
8407 out.writeInt(0);
8408 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008409 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008410 out.writeInt(1);
8411 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8412 mUserActivityCounters[i].writeToParcel(out);
8413 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008414 } else {
8415 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008416 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008417 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008418 out.writeInt(1);
8419 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008420 mNetworkByteActivityCounters[i].writeToParcel(out);
8421 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008422 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008423 mMobileRadioActiveTime.writeToParcel(out);
8424 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008425 } else {
8426 out.writeInt(0);
8427 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008428
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008429 if (mWifiControllerActivity != null) {
8430 out.writeInt(1);
8431 mWifiControllerActivity.writeToParcel(out, 0);
8432 } else {
8433 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008434 }
8435
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008436 if (mBluetoothControllerActivity != null) {
8437 out.writeInt(1);
8438 mBluetoothControllerActivity.writeToParcel(out, 0);
8439 } else {
8440 out.writeInt(0);
8441 }
8442
8443 if (mModemControllerActivity != null) {
8444 out.writeInt(1);
8445 mModemControllerActivity.writeToParcel(out, 0);
8446 } else {
8447 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008448 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008449
8450 mUserCpuTime.writeToParcel(out);
8451 mSystemCpuTime.writeToParcel(out);
8452
Sudheer Shankaaf857412017-07-21 00:14:24 -07008453 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008454 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008455 out.writeInt(mCpuClusterSpeedTimesUs.length);
8456 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008457 if (cpuSpeeds != null) {
8458 out.writeInt(1);
8459 out.writeInt(cpuSpeeds.length);
8460 for (LongSamplingCounter c : cpuSpeeds) {
8461 if (c != null) {
8462 out.writeInt(1);
8463 c.writeToParcel(out);
8464 } else {
8465 out.writeInt(0);
8466 }
8467 }
8468 } else {
8469 out.writeInt(0);
8470 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008471 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008472 } else {
8473 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008474 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008475
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008476 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8477 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008478
8479 mCpuActiveTimeMs.writeToParcel(out);
8480 mCpuClusterTimesMs.writeToParcel(out);
8481
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008482 if (mProcStateTimeMs != null) {
8483 out.writeInt(mProcStateTimeMs.length);
8484 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8485 LongSamplingCounterArray.writeToParcel(out, counters);
8486 }
8487 } else {
8488 out.writeInt(0);
8489 }
8490 if (mProcStateScreenOffTimeMs != null) {
8491 out.writeInt(mProcStateScreenOffTimeMs.length);
8492 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8493 LongSamplingCounterArray.writeToParcel(out, counters);
8494 }
8495 } else {
8496 out.writeInt(0);
8497 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008498
Adam Lesinski5f056f62016-07-14 16:56:08 -07008499 if (mMobileRadioApWakeupCount != null) {
8500 out.writeInt(1);
8501 mMobileRadioApWakeupCount.writeToParcel(out);
8502 } else {
8503 out.writeInt(0);
8504 }
8505
8506 if (mWifiRadioApWakeupCount != null) {
8507 out.writeInt(1);
8508 mWifiRadioApWakeupCount.writeToParcel(out);
8509 } else {
8510 out.writeInt(0);
8511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008512 }
8513
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008514 void readJobCompletionsFromParcelLocked(Parcel in) {
8515 int numJobCompletions = in.readInt();
8516 mJobCompletions.clear();
8517 for (int j = 0; j < numJobCompletions; j++) {
8518 String jobName = in.readString();
8519 int numTypes = in.readInt();
8520 if (numTypes > 0) {
8521 SparseIntArray types = new SparseIntArray();
8522 for (int k = 0; k < numTypes; k++) {
8523 int type = in.readInt();
8524 int count = in.readInt();
8525 types.put(type, count);
8526 }
8527 mJobCompletions.put(jobName, types);
8528 }
8529 }
8530 }
8531
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008532 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008533 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008534 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008536 int numWakelocks = in.readInt();
8537 mWakelockStats.clear();
8538 for (int j = 0; j < numWakelocks; j++) {
8539 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008540 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008541 wakelock.readFromParcelLocked(
8542 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008543 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008544 }
8545
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008546 int numSyncs = in.readInt();
8547 mSyncStats.clear();
8548 for (int j = 0; j < numSyncs; j++) {
8549 String syncName = in.readString();
8550 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008551 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8552 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008553 }
8554 }
8555
8556 int numJobs = in.readInt();
8557 mJobStats.clear();
8558 for (int j = 0; j < numJobs; j++) {
8559 String jobName = in.readString();
8560 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008561 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8562 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008563 }
8564 }
8565
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008566 readJobCompletionsFromParcelLocked(in);
8567
Amith Yamasani977e11f2018-02-16 11:29:54 -08008568 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8569 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8570 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8571 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8572 mJobsFreshnessBuckets[i] = Counter.readCounterFromParcel(mBsi.mOnBatteryTimeBase,
8573 in);
8574 }
8575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008576 int numSensors = in.readInt();
8577 mSensorStats.clear();
8578 for (int k = 0; k < numSensors; k++) {
8579 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008580 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008581 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8582 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008583 mSensorStats.put(sensorNumber, sensor);
8584 }
8585
8586 int numProcs = in.readInt();
8587 mProcessStats.clear();
8588 for (int k = 0; k < numProcs; k++) {
8589 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008590 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 proc.readFromParcelLocked(in);
8592 mProcessStats.put(processName, proc);
8593 }
8594
8595 int numPkgs = in.readInt();
8596 mPackageStats.clear();
8597 for (int l = 0; l < numPkgs; l++) {
8598 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008599 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008600 pkg.readFromParcelLocked(in);
8601 mPackageStats.put(packageName, pkg);
8602 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008603
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008604 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008605 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008606 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8607 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008608 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008609 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008610 }
8611 mFullWifiLockOut = false;
8612 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008613 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8614 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008615 } else {
8616 mFullWifiLockTimer = null;
8617 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008618 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008619 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008620 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8621 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8622 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008623 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008624 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008625 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008626 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8627 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8628 if (in.readInt() != 0) {
8629 makeWifiBatchedScanBin(i, in);
8630 } else {
8631 mWifiBatchedScanTimer[i] = null;
8632 }
8633 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008634 mWifiMulticastEnabled = false;
8635 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008636 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8637 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008638 } else {
8639 mWifiMulticastTimer = null;
8640 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008641 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008642 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8643 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008644 } else {
8645 mAudioTurnedOnTimer = null;
8646 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008647 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008648 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8649 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008650 } else {
8651 mVideoTurnedOnTimer = null;
8652 }
8653 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008654 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8655 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008656 } else {
8657 mFlashlightTurnedOnTimer = null;
8658 }
8659 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008660 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8661 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008662 } else {
8663 mCameraTurnedOnTimer = null;
8664 }
8665 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008666 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8667 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008668 } else {
8669 mForegroundActivityTimer = null;
8670 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008671 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008672 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8673 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8674 } else {
8675 mForegroundServiceTimer = null;
8676 }
8677 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008678 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8679 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8680 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8681 in);
8682 } else {
8683 mAggregatedPartialWakelockTimer = null;
8684 }
8685 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008686 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8687 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8688 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008689 } else {
8690 mBluetoothScanTimer = null;
8691 }
Bookatz956f36bf2017-04-28 09:48:17 -07008692 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008693 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8694 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8695 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8696 } else {
8697 mBluetoothUnoptimizedScanTimer = null;
8698 }
8699 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008700 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8701 } else {
8702 mBluetoothScanResultCounter = null;
8703 }
Bookatzb1f04f32017-05-19 13:57:32 -07008704 if (in.readInt() != 0) {
8705 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8706 } else {
8707 mBluetoothScanResultBgCounter = null;
8708 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008709 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008710 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8711 if (in.readInt() != 0) {
8712 makeProcessState(i, in);
8713 } else {
8714 mProcessStateTimer[i] = null;
8715 }
8716 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008717 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008718 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8719 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008720 } else {
8721 mVibratorOnTimer = null;
8722 }
8723 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008724 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8725 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008726 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008727 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008728 } else {
8729 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008730 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008731 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008732 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8733 mNetworkPacketActivityCounters
8734 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008735 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008736 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008737 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008738 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008739 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008740 }
Joe Onoratoabded112016-02-08 16:49:39 -08008741 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8742 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008743 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008744 mNetworkByteActivityCounters = null;
8745 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008746 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008747
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008748 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008749 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008750 NUM_WIFI_TX_LEVELS, in);
8751 } else {
8752 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008753 }
8754
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008755 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008756 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008757 NUM_BT_TX_LEVELS, in);
8758 } else {
8759 mBluetoothControllerActivity = null;
8760 }
8761
8762 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008763 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008764 ModemActivityInfo.TX_POWER_LEVELS, in);
8765 } else {
8766 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008767 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008768
Joe Onoratoabded112016-02-08 16:49:39 -08008769 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8770 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008771
Adam Lesinski6832f392015-09-05 18:05:40 -07008772 if (in.readInt() != 0) {
8773 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008774 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008775 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008776 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008777
Sudheer Shankaaf857412017-07-21 00:14:24 -07008778 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008779 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8780 if (in.readInt() != 0) {
8781 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008782 if (mBsi.mPowerProfile != null &&
8783 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008784 throw new ParcelFormatException("Incompatible number of cpu speeds");
8785 }
8786
8787 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008788 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008789 for (int speed = 0; speed < numSpeeds; speed++) {
8790 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008791 cpuSpeeds[speed] = new LongSamplingCounter(
8792 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008793 }
8794 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008795 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008796 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008797 }
8798 }
8799 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008800 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008801 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008802
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008803 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8804 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8805 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008806
Mike Ma3d422c32017-10-25 11:08:57 -07008807 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8808 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8809
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008810 int length = in.readInt();
8811 if (length == NUM_PROCESS_STATE) {
8812 mProcStateTimeMs = new LongSamplingCounterArray[length];
8813 for (int procState = 0; procState < length; ++procState) {
8814 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8815 in, mBsi.mOnBatteryTimeBase);
8816 }
8817 } else {
8818 mProcStateTimeMs = null;
8819 }
8820 length = in.readInt();
8821 if (length == NUM_PROCESS_STATE) {
8822 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8823 for (int procState = 0; procState < length; ++procState) {
8824 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8825 in, mBsi.mOnBatteryScreenOffTimeBase);
8826 }
8827 } else {
8828 mProcStateScreenOffTimeMs = null;
8829 }
8830
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008831 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008832 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8833 } else {
8834 mMobileRadioApWakeupCount = null;
8835 }
8836
8837 if (in.readInt() != 0) {
8838 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8839 } else {
8840 mWifiRadioApWakeupCount = null;
8841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008842 }
8843
Amith Yamasani977e11f2018-02-16 11:29:54 -08008844 public void noteJobsDeferredLocked(int numDeferred, long sinceLast) {
8845 mJobsDeferredEventCount.addAtomic(1);
8846 mJobsDeferredCount.addAtomic(numDeferred);
8847 if (sinceLast != 0) {
8848 // Add the total time, which can be divided by the event count to get an average
8849 mJobsFreshnessTimeMs.addCountLocked(sinceLast);
8850 // Also keep track of how many times there were in these different buckets.
8851 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8852 if (sinceLast < JOB_FRESHNESS_BUCKETS[i]) {
8853 if (mJobsFreshnessBuckets[i] == null) {
8854 mJobsFreshnessBuckets[i] = new Counter(
8855 mBsi.mOnBatteryTimeBase);
8856 }
8857 mJobsFreshnessBuckets[i].addAtomic(1);
8858 break;
8859 }
8860 }
8861 }
8862 }
8863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 /**
8865 * The statistics associated with a particular wake lock.
8866 */
Joe Onoratoabded112016-02-08 16:49:39 -08008867 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8868 /**
8869 * BatteryStatsImpl that we are associated with.
8870 */
8871 protected BatteryStatsImpl mBsi;
8872
8873 /**
8874 * BatteryStatsImpl that we are associated with.
8875 */
8876 protected Uid mUid;
8877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008878 /**
8879 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008880 * 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 -08008881 */
Bookatz5b5ec322017-05-26 09:40:38 -07008882 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883
8884 /**
8885 * How long (in ms) this uid has been keeping the device fully awake.
8886 */
Evan Millarc64edde2009-04-18 12:26:32 -07008887 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008888
8889 /**
8890 * How long (in ms) this uid has had a window keeping the device awake.
8891 */
Evan Millarc64edde2009-04-18 12:26:32 -07008892 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008893
8894 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008895 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008896 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008897 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008898
Joe Onoratoabded112016-02-08 16:49:39 -08008899 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8900 mBsi = bsi;
8901 mUid = uid;
8902 }
8903
Adam Lesinski9425fe22015-06-19 12:02:13 -07008904 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008905 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8906 * proper timer pool from the given BatteryStatsImpl object.
8907 *
8908 * @param in the Parcel to be read from.
8909 * return a new Timer, or null.
8910 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008911 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8912 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008913 if (in.readInt() == 0) {
8914 return null;
8915 }
8916
Joe Onoratoabded112016-02-08 16:49:39 -08008917 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008918 }
8919
Joe Onorato92fd23f2016-07-25 11:18:42 -07008920 /**
8921 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8922 * proper timer pool from the given BatteryStatsImpl object.
8923 *
8924 * @param in the Parcel to be read from.
8925 * return a new Timer, or null.
8926 */
Bookatz5b5ec322017-05-26 09:40:38 -07008927 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8928 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008929 if (in.readInt() == 0) {
8930 return null;
8931 }
8932
Bookatz5b5ec322017-05-26 09:40:38 -07008933 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008934 }
8935
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008936 boolean reset() {
8937 boolean wlactive = false;
8938 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008939 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008940 }
8941 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008942 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008943 }
8944 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008945 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008946 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008947 if (mTimerDraw != null) {
8948 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008949 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008950 if (!wlactive) {
8951 if (mTimerFull != null) {
8952 mTimerFull.detach();
8953 mTimerFull = null;
8954 }
8955 if (mTimerPartial != null) {
8956 mTimerPartial.detach();
8957 mTimerPartial = null;
8958 }
8959 if (mTimerWindow != null) {
8960 mTimerWindow.detach();
8961 mTimerWindow = null;
8962 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008963 if (mTimerDraw != null) {
8964 mTimerDraw.detach();
8965 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008966 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008967 }
8968 return !wlactive;
8969 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008970
Bookatz5b5ec322017-05-26 09:40:38 -07008971 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
8972 TimeBase screenOffBgTimeBase, Parcel in) {
8973 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
8974 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008975 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
8976 mBsi.mFullTimers, timeBase, in);
8977 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
8978 mBsi.mWindowTimers, timeBase, in);
8979 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
8980 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008981 }
8982
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008983 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
8984 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
8985 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
8986 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008987 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008988 }
8989
8990 @Override
8991 public Timer getWakeTime(int type) {
8992 switch (type) {
8993 case WAKE_TYPE_FULL: return mTimerFull;
8994 case WAKE_TYPE_PARTIAL: return mTimerPartial;
8995 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008996 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008997 default: throw new IllegalArgumentException("type = " + type);
8998 }
8999 }
9000 }
9001
Joe Onoratoabded112016-02-08 16:49:39 -08009002 public static class Sensor extends BatteryStats.Uid.Sensor {
9003 /**
9004 * BatteryStatsImpl that we are associated with.
9005 */
9006 protected BatteryStatsImpl mBsi;
9007
9008 /**
Bookatz867c0d72017-03-07 18:23:42 -08009009 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08009010 */
9011 protected Uid mUid;
9012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009013 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08009014 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009015
Joe Onoratoabded112016-02-08 16:49:39 -08009016 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
9017 mBsi = bsi;
9018 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009019 mHandle = handle;
9020 }
9021
Bookatz867c0d72017-03-07 18:23:42 -08009022 private DualTimer readTimersFromParcel(
9023 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009024 if (in.readInt() == 0) {
9025 return null;
9026 }
9027
Joe Onoratoabded112016-02-08 16:49:39 -08009028 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009029 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009030 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009031 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009032 }
Bookatz867c0d72017-03-07 18:23:42 -08009033 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009034 }
9035
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009036 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009037 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009038 mTimer = null;
9039 return true;
9040 }
9041 return false;
9042 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009043
Bookatz867c0d72017-03-07 18:23:42 -08009044 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
9045 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009046 }
9047
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009048 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009049 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009050 }
9051
9052 @Override
9053 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07009054 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009055 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009056
9057 @Override
Bookatz867c0d72017-03-07 18:23:42 -08009058 public Timer getSensorBackgroundTime() {
9059 if (mTimer == null) {
9060 return null;
9061 }
9062 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009063 }
9064
9065 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009066 public int getHandle() {
9067 return mHandle;
9068 }
9069 }
9070
9071 /**
9072 * The statistics associated with a particular process.
9073 */
Joe Onoratoabded112016-02-08 16:49:39 -08009074 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
9075 /**
9076 * BatteryStatsImpl that we are associated with.
9077 */
9078 protected BatteryStatsImpl mBsi;
9079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009080 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009081 * The name of this process.
9082 */
9083 final String mName;
9084
9085 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08009086 * Remains true until removed from the stats.
9087 */
9088 boolean mActive = true;
9089
9090 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009091 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 */
9093 long mUserTime;
9094
9095 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009096 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009097 */
9098 long mSystemTime;
9099
9100 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009101 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009102 */
9103 long mForegroundTime;
9104
9105 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009106 * Number of times the process has been started.
9107 */
9108 int mStarts;
9109
9110 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009111 * Number of times the process has crashed.
9112 */
9113 int mNumCrashes;
9114
9115 /**
9116 * Number of times the process has had an ANR.
9117 */
9118 int mNumAnrs;
9119
9120 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009121 * The amount of user time loaded from a previous save.
9122 */
9123 long mLoadedUserTime;
9124
9125 /**
9126 * The amount of system time loaded from a previous save.
9127 */
9128 long mLoadedSystemTime;
9129
9130 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009131 * The amount of foreground time loaded from a previous save.
9132 */
9133 long mLoadedForegroundTime;
9134
9135 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009136 * The number of times the process has started from a previous save.
9137 */
9138 int mLoadedStarts;
9139
9140 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009141 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009142 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009143 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009144
9145 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009146 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009148 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009149
9150 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009151 * The amount of user time when last unplugged.
9152 */
9153 long mUnpluggedUserTime;
9154
9155 /**
9156 * The amount of system time when last unplugged.
9157 */
9158 long mUnpluggedSystemTime;
9159
9160 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009161 * The amount of foreground time since unplugged.
9162 */
9163 long mUnpluggedForegroundTime;
9164
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009165 /**
9166 * The number of times the process has started before unplugged.
9167 */
9168 int mUnpluggedStarts;
9169
Dianne Hackborn61659e52014-07-09 16:13:01 -07009170 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009171 * Number of times the process has crashed before unplugged.
9172 */
9173 int mUnpluggedNumCrashes;
9174
9175 /**
9176 * Number of times the process has had an ANR before unplugged.
9177 */
9178 int mUnpluggedNumAnrs;
9179
Dianne Hackborn287952c2010-09-22 22:34:31 -07009180 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009181
Joe Onoratoabded112016-02-08 16:49:39 -08009182 public Proc(BatteryStatsImpl bsi, String name) {
9183 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009184 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08009185 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009186 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009187
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009188 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009189 mUnpluggedUserTime = mUserTime;
9190 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009191 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009192 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009193 mUnpluggedNumCrashes = mNumCrashes;
9194 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009195 }
9196
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009197 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009198 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009199
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009200 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009201 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009202 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009203 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009204
Dianne Hackborn287952c2010-09-22 22:34:31 -07009205 public int countExcessivePowers() {
9206 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009207 }
9208
Dianne Hackborn287952c2010-09-22 22:34:31 -07009209 public ExcessivePower getExcessivePower(int i) {
9210 if (mExcessivePower != null) {
9211 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009212 }
9213 return null;
9214 }
9215
Dianne Hackborn287952c2010-09-22 22:34:31 -07009216 public void addExcessiveCpu(long overTime, long usedTime) {
9217 if (mExcessivePower == null) {
9218 mExcessivePower = new ArrayList<ExcessivePower>();
9219 }
9220 ExcessivePower ew = new ExcessivePower();
9221 ew.type = ExcessivePower.TYPE_CPU;
9222 ew.overTime = overTime;
9223 ew.usedTime = usedTime;
9224 mExcessivePower.add(ew);
9225 }
9226
9227 void writeExcessivePowerToParcelLocked(Parcel out) {
9228 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009229 out.writeInt(0);
9230 return;
9231 }
9232
Dianne Hackborn287952c2010-09-22 22:34:31 -07009233 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009234 out.writeInt(N);
9235 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009236 ExcessivePower ew = mExcessivePower.get(i);
9237 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009238 out.writeLong(ew.overTime);
9239 out.writeLong(ew.usedTime);
9240 }
9241 }
9242
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009243 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009244 final int N = in.readInt();
9245 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009246 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009247 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009248 }
9249
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009250 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009251 throw new ParcelFormatException(
9252 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009253 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009254
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009255 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009256 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009257 ExcessivePower ew = new ExcessivePower();
9258 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009259 ew.overTime = in.readLong();
9260 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009261 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009262 }
9263 }
9264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009265 void writeToParcelLocked(Parcel out) {
9266 out.writeLong(mUserTime);
9267 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009268 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009269 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009270 out.writeInt(mNumCrashes);
9271 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009272 out.writeLong(mLoadedUserTime);
9273 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009274 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009275 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009276 out.writeInt(mLoadedNumCrashes);
9277 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009278 out.writeLong(mUnpluggedUserTime);
9279 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009280 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009281 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009282 out.writeInt(mUnpluggedNumCrashes);
9283 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009284 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009285 }
9286
9287 void readFromParcelLocked(Parcel in) {
9288 mUserTime = in.readLong();
9289 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009290 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009291 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009292 mNumCrashes = in.readInt();
9293 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009294 mLoadedUserTime = in.readLong();
9295 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009296 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009298 mLoadedNumCrashes = in.readInt();
9299 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009300 mUnpluggedUserTime = in.readLong();
9301 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009302 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009304 mUnpluggedNumCrashes = in.readInt();
9305 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009306 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009307 }
9308
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009309 public void addCpuTimeLocked(int utime, int stime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08009310 addCpuTimeLocked(utime, stime, mBsi.mOnBatteryTimeBase.isRunning());
9311 }
9312
9313 public void addCpuTimeLocked(int utime, int stime, boolean isRunning) {
9314 if (isRunning) {
9315 mUserTime += utime;
9316 mSystemTime += stime;
9317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009318 }
9319
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009320 public void addForegroundTimeLocked(long ttime) {
9321 mForegroundTime += ttime;
9322 }
9323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009324 public void incStartsLocked() {
9325 mStarts++;
9326 }
9327
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009328 public void incNumCrashesLocked() {
9329 mNumCrashes++;
9330 }
9331
9332 public void incNumAnrsLocked() {
9333 mNumAnrs++;
9334 }
9335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009336 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009337 public boolean isActive() {
9338 return mActive;
9339 }
9340
9341 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009342 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009343 long val = mUserTime;
9344 if (which == STATS_CURRENT) {
9345 val -= mLoadedUserTime;
9346 } else if (which == STATS_SINCE_UNPLUGGED) {
9347 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009348 }
9349 return val;
9350 }
9351
9352 @Override
9353 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009354 long val = mSystemTime;
9355 if (which == STATS_CURRENT) {
9356 val -= mLoadedSystemTime;
9357 } else if (which == STATS_SINCE_UNPLUGGED) {
9358 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009359 }
9360 return val;
9361 }
9362
9363 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009364 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009365 long val = mForegroundTime;
9366 if (which == STATS_CURRENT) {
9367 val -= mLoadedForegroundTime;
9368 } else if (which == STATS_SINCE_UNPLUGGED) {
9369 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009370 }
9371 return val;
9372 }
9373
9374 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009375 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009376 int val = mStarts;
9377 if (which == STATS_CURRENT) {
9378 val -= mLoadedStarts;
9379 } else if (which == STATS_SINCE_UNPLUGGED) {
9380 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381 }
9382 return val;
9383 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009384
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009385 @Override
9386 public int getNumCrashes(int which) {
9387 int val = mNumCrashes;
9388 if (which == STATS_CURRENT) {
9389 val -= mLoadedNumCrashes;
9390 } else if (which == STATS_SINCE_UNPLUGGED) {
9391 val -= mUnpluggedNumCrashes;
9392 }
9393 return val;
9394 }
9395
9396 @Override
9397 public int getNumAnrs(int which) {
9398 int val = mNumAnrs;
9399 if (which == STATS_CURRENT) {
9400 val -= mLoadedNumAnrs;
9401 } else if (which == STATS_SINCE_UNPLUGGED) {
9402 val -= mUnpluggedNumAnrs;
9403 }
9404 return val;
9405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009406 }
9407
9408 /**
9409 * The statistics associated with a particular package.
9410 */
Joe Onoratoabded112016-02-08 16:49:39 -08009411 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9412 /**
9413 * BatteryStatsImpl that we are associated with.
9414 */
9415 protected BatteryStatsImpl mBsi;
9416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009417 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009418 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009419 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009420 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009421 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009422
9423 /**
9424 * The statics we have collected for this package's services.
9425 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009426 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009427
Joe Onoratoabded112016-02-08 16:49:39 -08009428 public Pkg(BatteryStatsImpl bsi) {
9429 mBsi = bsi;
9430 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009431 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009432
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009433 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 }
9435
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009436 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009437 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009438
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009439 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009440 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009441 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009443 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009444 int numWA = in.readInt();
9445 mWakeupAlarms.clear();
9446 for (int i=0; i<numWA; i++) {
9447 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009448 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009450
9451 int numServs = in.readInt();
9452 mServiceStats.clear();
9453 for (int m = 0; m < numServs; m++) {
9454 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009455 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009456 mServiceStats.put(serviceName, serv);
9457
9458 serv.readFromParcelLocked(in);
9459 }
9460 }
9461
9462 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009463 int numWA = mWakeupAlarms.size();
9464 out.writeInt(numWA);
9465 for (int i=0; i<numWA; i++) {
9466 out.writeString(mWakeupAlarms.keyAt(i));
9467 mWakeupAlarms.valueAt(i).writeToParcel(out);
9468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009469
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009470 final int NS = mServiceStats.size();
9471 out.writeInt(NS);
9472 for (int i=0; i<NS; i++) {
9473 out.writeString(mServiceStats.keyAt(i));
9474 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009475 serv.writeToParcelLocked(out);
9476 }
9477 }
9478
9479 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009480 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9481 return mWakeupAlarms;
9482 }
9483
9484 public void noteWakeupAlarmLocked(String tag) {
9485 Counter c = mWakeupAlarms.get(tag);
9486 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009487 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009488 mWakeupAlarms.put(tag, c);
9489 }
9490 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009491 }
9492
9493 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009494 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9495 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009496 }
9497
9498 /**
9499 * The statistics associated with a particular service.
9500 */
Joe Onoratoabded112016-02-08 16:49:39 -08009501 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9502 /**
9503 * BatteryStatsImpl that we are associated with.
9504 */
9505 protected BatteryStatsImpl mBsi;
9506
9507 /**
9508 * The android package in which this service resides.
9509 */
9510 protected Pkg mPkg;
9511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009512 /**
9513 * Total time (ms in battery uptime) the service has been left started.
9514 */
Joe Onoratoabded112016-02-08 16:49:39 -08009515 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009516
9517 /**
9518 * If service has been started and not yet stopped, this is
9519 * when it was started.
9520 */
Joe Onoratoabded112016-02-08 16:49:39 -08009521 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009522
9523 /**
9524 * True if we are currently running.
9525 */
Joe Onoratoabded112016-02-08 16:49:39 -08009526 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009527
9528 /**
9529 * Total number of times startService() has been called.
9530 */
Joe Onoratoabded112016-02-08 16:49:39 -08009531 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009532
9533 /**
9534 * Total time (ms in battery uptime) the service has been left launched.
9535 */
Joe Onoratoabded112016-02-08 16:49:39 -08009536 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009537
9538 /**
9539 * If service has been launched and not yet exited, this is
9540 * when it was launched (ms in battery uptime).
9541 */
Joe Onoratoabded112016-02-08 16:49:39 -08009542 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009543
9544 /**
9545 * True if we are currently launched.
9546 */
Joe Onoratoabded112016-02-08 16:49:39 -08009547 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009548
9549 /**
9550 * Total number times the service has been launched.
9551 */
Joe Onoratoabded112016-02-08 16:49:39 -08009552 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009553
9554 /**
9555 * The amount of time spent started loaded from a previous save
9556 * (ms in battery uptime).
9557 */
Joe Onoratoabded112016-02-08 16:49:39 -08009558 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009559
9560 /**
9561 * The number of starts loaded from a previous save.
9562 */
Joe Onoratoabded112016-02-08 16:49:39 -08009563 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009564
9565 /**
9566 * The number of launches loaded from a previous save.
9567 */
Joe Onoratoabded112016-02-08 16:49:39 -08009568 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569
9570 /**
9571 * The amount of time spent started as of the last run (ms
9572 * in battery uptime).
9573 */
Joe Onoratoabded112016-02-08 16:49:39 -08009574 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009575
9576 /**
9577 * The number of starts as of the last run.
9578 */
Joe Onoratoabded112016-02-08 16:49:39 -08009579 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009580
9581 /**
9582 * The number of launches as of the last run.
9583 */
Joe Onoratoabded112016-02-08 16:49:39 -08009584 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009585
9586 /**
9587 * The amount of time spent started when last unplugged (ms
9588 * in battery uptime).
9589 */
Joe Onoratoabded112016-02-08 16:49:39 -08009590 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009591
9592 /**
9593 * The number of starts when last unplugged.
9594 */
Joe Onoratoabded112016-02-08 16:49:39 -08009595 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009596
9597 /**
9598 * The number of launches when last unplugged.
9599 */
Joe Onoratoabded112016-02-08 16:49:39 -08009600 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009601
Joe Onoratoabded112016-02-08 16:49:39 -08009602 /**
9603 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9604 */
9605 public Serv(BatteryStatsImpl bsi) {
9606 mBsi = bsi;
9607 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009608 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009609
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009610 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9611 long baseRealtime) {
9612 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009613 mUnpluggedStarts = mStarts;
9614 mUnpluggedLaunches = mLaunches;
9615 }
9616
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009617 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9618 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009619 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009620
Joe Onoratoabded112016-02-08 16:49:39 -08009621 /**
9622 * Remove this Serv as a listener from the time base.
9623 */
9624 public void detach() {
9625 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009626 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009627
Joe Onoratoabded112016-02-08 16:49:39 -08009628 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009629 mStartTime = in.readLong();
9630 mRunningSince = in.readLong();
9631 mRunning = in.readInt() != 0;
9632 mStarts = in.readInt();
9633 mLaunchedTime = in.readLong();
9634 mLaunchedSince = in.readLong();
9635 mLaunched = in.readInt() != 0;
9636 mLaunches = in.readInt();
9637 mLoadedStartTime = in.readLong();
9638 mLoadedStarts = in.readInt();
9639 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009640 mLastStartTime = 0;
9641 mLastStarts = 0;
9642 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009643 mUnpluggedStartTime = in.readLong();
9644 mUnpluggedStarts = in.readInt();
9645 mUnpluggedLaunches = in.readInt();
9646 }
9647
Joe Onoratoabded112016-02-08 16:49:39 -08009648 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009649 out.writeLong(mStartTime);
9650 out.writeLong(mRunningSince);
9651 out.writeInt(mRunning ? 1 : 0);
9652 out.writeInt(mStarts);
9653 out.writeLong(mLaunchedTime);
9654 out.writeLong(mLaunchedSince);
9655 out.writeInt(mLaunched ? 1 : 0);
9656 out.writeInt(mLaunches);
9657 out.writeLong(mLoadedStartTime);
9658 out.writeInt(mLoadedStarts);
9659 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009660 out.writeLong(mUnpluggedStartTime);
9661 out.writeInt(mUnpluggedStarts);
9662 out.writeInt(mUnpluggedLaunches);
9663 }
9664
Joe Onoratoabded112016-02-08 16:49:39 -08009665 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009666 if (!mLaunched) return mLaunchedTime;
9667 return mLaunchedTime + batteryUptime - mLaunchedSince;
9668 }
9669
Joe Onoratoabded112016-02-08 16:49:39 -08009670 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009671 if (!mRunning) return mStartTime;
9672 return mStartTime + batteryUptime - mRunningSince;
9673 }
9674
9675 public void startLaunchedLocked() {
9676 if (!mLaunched) {
9677 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009678 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 mLaunched = true;
9680 }
9681 }
9682
9683 public void stopLaunchedLocked() {
9684 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009685 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009686 if (time > 0) {
9687 mLaunchedTime += time;
9688 } else {
9689 mLaunches--;
9690 }
9691 mLaunched = false;
9692 }
9693 }
9694
9695 public void startRunningLocked() {
9696 if (!mRunning) {
9697 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009698 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009699 mRunning = true;
9700 }
9701 }
9702
9703 public void stopRunningLocked() {
9704 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009705 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009706 if (time > 0) {
9707 mStartTime += time;
9708 } else {
9709 mStarts--;
9710 }
9711 mRunning = false;
9712 }
9713 }
9714
9715 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009716 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009717 }
9718
9719 @Override
9720 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009721 int val = mLaunches;
9722 if (which == STATS_CURRENT) {
9723 val -= mLoadedLaunches;
9724 } else if (which == STATS_SINCE_UNPLUGGED) {
9725 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009727 return val;
9728 }
9729
9730 @Override
9731 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009732 long val = getStartTimeToNowLocked(now);
9733 if (which == STATS_CURRENT) {
9734 val -= mLoadedStartTime;
9735 } else if (which == STATS_SINCE_UNPLUGGED) {
9736 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009738 return val;
9739 }
9740
9741 @Override
9742 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009743 int val = mStarts;
9744 if (which == STATS_CURRENT) {
9745 val -= mLoadedStarts;
9746 } else if (which == STATS_SINCE_UNPLUGGED) {
9747 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009748 }
9749
9750 return val;
9751 }
9752 }
9753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009754 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009755 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009756 }
9757 }
9758
9759 /**
9760 * Retrieve the statistics object for a particular process, creating
9761 * if needed.
9762 */
9763 public Proc getProcessStatsLocked(String name) {
9764 Proc ps = mProcessStats.get(name);
9765 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009766 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009767 mProcessStats.put(name, ps);
9768 }
9769
9770 return ps;
9771 }
9772
Andreas Gampe3f24e692018-02-05 13:24:28 -08009773 @GuardedBy("mBsi")
Dianne Hackborna8d10942015-11-19 17:55:19 -08009774 public void updateUidProcessStateLocked(int procState) {
9775 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009776 // Make special note of Foreground Services
9777 final boolean userAwareService =
9778 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009779 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009780
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009781 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9782 return;
9783 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009784
Bookatz867c0d72017-03-07 18:23:42 -08009785 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009786 if (mProcessState != uidRunningState) {
9787 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009788
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009789 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9790 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009791
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009792 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009793 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009794 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9795 mBsi.mOnBatteryTimeBase.isRunning(),
Sudheer Shankac20379e2018-02-15 00:06:21 -08009796 mBsi.mOnBatteryScreenOffTimeBase.isRunning(),
9797 mBsi.mConstants.PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma234d1822018-03-13 18:53:21 -07009798 mBsi.mNumSingleUidCpuTimeReads++;
Sudheer Shankac20379e2018-02-15 00:06:21 -08009799 } else {
Mike Ma234d1822018-03-13 18:53:21 -07009800 mBsi.mNumBatchedSingleUidCpuTimeReads++;
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009801 }
9802 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9803 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9804 mBsi.mPendingUids.put(mUid, mProcessState);
9805 }
9806 } else {
9807 mBsi.mPendingUids.clear();
9808 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009809 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009810 mProcessState = uidRunningState;
9811 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9812 if (mProcessStateTimer[uidRunningState] == null) {
9813 makeProcessState(uidRunningState, null);
9814 }
9815 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9816 }
9817
9818 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9819 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009820 }
Bookatz867c0d72017-03-07 18:23:42 -08009821
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009822 if (userAwareService != mInForegroundService) {
9823 if (userAwareService) {
9824 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9825 } else {
9826 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9827 }
9828 mInForegroundService = userAwareService;
9829 }
Bookatz867c0d72017-03-07 18:23:42 -08009830 }
9831
Bookatzc8c44962017-05-11 12:12:54 -07009832 /** Whether to consider Uid to be in the background for background timebase purposes. */
9833 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009834 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9835 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009836 return mProcessState >= PROCESS_STATE_BACKGROUND;
9837 }
9838
9839 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9840 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9841 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9842 }
9843
9844 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9845 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9846 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009847 }
9848
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009849 public SparseArray<? extends Pid> getPidStats() {
9850 return mPids;
9851 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009852
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009853 public Pid getPidStatsLocked(int pid) {
9854 Pid p = mPids.get(pid);
9855 if (p == null) {
9856 p = new Pid();
9857 mPids.put(pid, p);
9858 }
9859 return p;
9860 }
9861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009862 /**
9863 * Retrieve the statistics object for a particular service, creating
9864 * if needed.
9865 */
9866 public Pkg getPackageStatsLocked(String name) {
9867 Pkg ps = mPackageStats.get(name);
9868 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009869 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009870 mPackageStats.put(name, ps);
9871 }
9872
9873 return ps;
9874 }
9875
9876 /**
9877 * Retrieve the statistics object for a particular service, creating
9878 * if needed.
9879 */
9880 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9881 Pkg ps = getPackageStatsLocked(pkg);
9882 Pkg.Serv ss = ps.mServiceStats.get(serv);
9883 if (ss == null) {
9884 ss = ps.newServiceStatsLocked();
9885 ps.mServiceStats.put(serv, ss);
9886 }
9887
9888 return ss;
9889 }
9890
Dianne Hackbornd953c532014-08-16 18:17:38 -07009891 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009892 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009893 timer.readSummaryFromParcelLocked(in);
9894 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009895 }
9896
Dianne Hackbornd953c532014-08-16 18:17:38 -07009897 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009898 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009899 timer.readSummaryFromParcelLocked(in);
9900 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009901 }
9902
Dianne Hackbornd953c532014-08-16 18:17:38 -07009903 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009904 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009905 mWakelockStats.add(wlName, wl);
9906 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009907 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009908 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009909 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009910 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009911 }
9912 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009913 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009914 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009915 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009916 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009918 }
9919
Bookatz867c0d72017-03-07 18:23:42 -08009920 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009921 Sensor se = mSensorStats.get(sensor);
9922 if (se == null) {
9923 if (!create) {
9924 return null;
9925 }
Joe Onoratoabded112016-02-08 16:49:39 -08009926 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009927 mSensorStats.put(sensor, se);
9928 }
Bookatz867c0d72017-03-07 18:23:42 -08009929 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009930 if (t != null) {
9931 return t;
9932 }
Joe Onoratoabded112016-02-08 16:49:39 -08009933 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009934 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009935 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009936 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009937 }
Bookatz867c0d72017-03-07 18:23:42 -08009938 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9939 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009940 se.mTimer = t;
9941 return t;
9942 }
9943
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009944 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009945 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009946 if (t != null) {
9947 t.startRunningLocked(elapsedRealtimeMs);
9948 }
9949 }
9950
9951 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009952 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009953 if (t != null) {
9954 t.stopRunningLocked(elapsedRealtimeMs);
9955 }
9956 }
9957
9958 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009959 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009960 if (t != null) {
9961 t.startRunningLocked(elapsedRealtimeMs);
9962 }
9963 }
9964
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009965 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07009966 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009967 if (t != null) {
9968 t.stopRunningLocked(elapsedRealtimeMs);
9969 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009970 if (mBsi.mOnBatteryTimeBase.isRunning()) {
9971 SparseIntArray types = mJobCompletions.get(name);
9972 if (types == null) {
9973 types = new SparseIntArray();
9974 mJobCompletions.put(name, types);
9975 }
9976 int last = types.get(stopReason, 0);
9977 types.put(stopReason, last + 1);
9978 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009979 }
9980
Bookatz5b5ec322017-05-26 09:40:38 -07009981 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
9982 if (wl == null) {
9983 return null;
9984 }
9985 switch (type) {
9986 case WAKE_TYPE_PARTIAL: {
9987 DualTimer t = wl.mTimerPartial;
9988 if (t == null) {
9989 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
9990 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
9991 mOnBatteryScreenOffBackgroundTimeBase);
9992 wl.mTimerPartial = t;
9993 }
9994 return t;
9995 }
9996 case WAKE_TYPE_FULL: {
9997 StopwatchTimer t = wl.mTimerFull;
9998 if (t == null) {
9999 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
10000 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
10001 wl.mTimerFull = t;
10002 }
10003 return t;
10004 }
10005 case WAKE_TYPE_WINDOW: {
10006 StopwatchTimer t = wl.mTimerWindow;
10007 if (t == null) {
10008 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
10009 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
10010 wl.mTimerWindow = t;
10011 }
10012 return t;
10013 }
10014 case WAKE_TYPE_DRAW: {
10015 StopwatchTimer t = wl.mTimerDraw;
10016 if (t == null) {
10017 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
10018 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
10019 wl.mTimerDraw = t;
10020 }
10021 return t;
10022 }
10023 default:
10024 throw new IllegalArgumentException("type=" + type);
10025 }
10026 }
10027
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010028 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010029 Wakelock wl = mWakelockStats.startObject(name);
10030 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -070010031 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010032 }
Bookatzc8c44962017-05-11 12:12:54 -070010033 if (type == WAKE_TYPE_PARTIAL) {
10034 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
10035 if (pid >= 0) {
10036 Pid p = getPidStatsLocked(pid);
10037 if (p.mWakeNesting++ == 0) {
10038 p.mWakeStartMs = elapsedRealtimeMs;
10039 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -070010040 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010042 }
10043
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010044 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010045 Wakelock wl = mWakelockStats.stopObject(name);
10046 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -070010047 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
10048 wlt.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010049 }
Bookatzc8c44962017-05-11 12:12:54 -070010050 if (type == WAKE_TYPE_PARTIAL) {
10051 if (mAggregatedPartialWakelockTimer != null) {
10052 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
10053 }
10054 if (pid >= 0) {
10055 Pid p = mPids.get(pid);
10056 if (p != null && p.mWakeNesting > 0) {
10057 if (p.mWakeNesting-- == 1) {
10058 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
10059 p.mWakeStartMs = 0;
10060 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -080010061 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010062 }
10063 }
10064 }
10065
Dianne Hackborn287952c2010-09-22 22:34:31 -070010066 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
10067 Proc p = getProcessStatsLocked(proc);
10068 if (p != null) {
10069 p.addExcessiveCpu(overTime, usedTime);
10070 }
10071 }
10072
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010073 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010074 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -080010075 t.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010076 }
10077
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010078 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010079 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -080010080 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010081 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010082 t.stopRunningLocked(elapsedRealtimeMs);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010084 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010085
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010086 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010087 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010088 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010089
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010090 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010091 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010092 }
10093
10094 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -080010095 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010096 }
10097 }
10098
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010099 public long[] getCpuFreqs() {
10100 return mCpuFreqs;
10101 }
10102
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010103 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
10104 UserInfoProvider userInfoProvider) {
10105 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010106 }
10107
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010108 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
10109 PlatformIdleStateCallback cb,
10110 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -080010111 init(clocks);
10112
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010113 if (systemDir != null) {
10114 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
10115 new File(systemDir, "batterystats.bin.tmp"));
10116 } else {
10117 mFile = null;
10118 }
10119 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010120 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -080010121 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010122 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010123 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -080010124 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010125 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010126 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010127 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010128 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010129 }
Joe Onoratoabded112016-02-08 16:49:39 -080010130 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
10131 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
10132 mOnBatteryTimeBase);
10133 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
10134 mOnBatteryTimeBase);
10135 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
10136 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
10137 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
10138 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
10139 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10140 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
10141 mOnBatteryTimeBase);
10142 }
10143 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
10144 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010145 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010146 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010147 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010148 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010149 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010150 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
10151 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010152 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010153 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
10154 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10155 NUM_BT_TX_LEVELS);
10156 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10157 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -080010158 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
10159 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
10160 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010161 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010162 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
10163 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010164 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
10165 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -080010166 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
10167 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010168 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010169 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -070010170 mOnBatteryTimeBase);
10171 }
Joe Onoratoabded112016-02-08 16:49:39 -080010172 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10173 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
10174 mOnBatteryTimeBase);
10175 }
10176 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10177 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
10178 mOnBatteryTimeBase);
10179 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010180 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010181 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10182 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10183 mOnBatteryTimeBase);
10184 }
Joe Onoratoabded112016-02-08 16:49:39 -080010185 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10186 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10187 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10188 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10189 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010190 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010191 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010192 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10193 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010194 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010195 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010196 long uptime = mClocks.uptimeMillis() * 1000;
10197 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010198 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010199 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010200 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010201 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010202 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010203 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010204 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010205 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010206 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010207 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010208 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010209 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010210 }
10211
10212 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010213 this(new SystemClocks(), p);
10214 }
10215
10216 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10217 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010218 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010219 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010220 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010221 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010222 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010223 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010224 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010225 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010226 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010227 }
10228
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010229 public void setPowerProfileLocked(PowerProfile profile) {
10230 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010231
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010232 // We need to initialize the KernelCpuSpeedReaders to read from
10233 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10234 // information.
10235 final int numClusters = mPowerProfile.getNumCpuClusters();
10236 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10237 int firstCpuOfCluster = 0;
10238 for (int i = 0; i < numClusters; i++) {
10239 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10240 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10241 numSpeedSteps);
10242 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10243 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010244
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010245 if (mEstimatedBatteryCapacity == -1) {
10246 // Initialize the estimated battery capacity to a known preset one.
10247 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010248 }
10249 }
10250
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010251 public void setCallback(BatteryCallback cb) {
10252 mCallback = cb;
10253 }
10254
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010255 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010256 if (mPhoneSignalScanningTimer != null) {
10257 mPhoneSignalScanningTimer.setTimeout(timeout);
10258 }
10259 }
10260
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010261 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10262 mExternalSync = sync;
10263 }
10264
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010265 public void updateDailyDeadlineLocked() {
10266 // Get the current time.
10267 long currentTime = mDailyStartTime = System.currentTimeMillis();
10268 Calendar calDeadline = Calendar.getInstance();
10269 calDeadline.setTimeInMillis(currentTime);
10270
10271 // Move time up to the next day, ranging from 1am to 3pm.
10272 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10273 calDeadline.set(Calendar.MILLISECOND, 0);
10274 calDeadline.set(Calendar.SECOND, 0);
10275 calDeadline.set(Calendar.MINUTE, 0);
10276 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10277 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10278 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10279 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10280 }
10281
10282 public void recordDailyStatsIfNeededLocked(boolean settled) {
10283 long currentTime = System.currentTimeMillis();
10284 if (currentTime >= mNextMaxDailyDeadline) {
10285 recordDailyStatsLocked();
10286 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10287 recordDailyStatsLocked();
10288 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10289 recordDailyStatsLocked();
10290 }
10291 }
10292
10293 public void recordDailyStatsLocked() {
10294 DailyItem item = new DailyItem();
10295 item.mStartTime = mDailyStartTime;
10296 item.mEndTime = System.currentTimeMillis();
10297 boolean hasData = false;
10298 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10299 hasData = true;
10300 item.mDischargeSteps = new LevelStepTracker(
10301 mDailyDischargeStepTracker.mNumStepDurations,
10302 mDailyDischargeStepTracker.mStepDurations);
10303 }
10304 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10305 hasData = true;
10306 item.mChargeSteps = new LevelStepTracker(
10307 mDailyChargeStepTracker.mNumStepDurations,
10308 mDailyChargeStepTracker.mStepDurations);
10309 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010310 if (mDailyPackageChanges != null) {
10311 hasData = true;
10312 item.mPackageChanges = mDailyPackageChanges;
10313 mDailyPackageChanges = null;
10314 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010315 mDailyDischargeStepTracker.init();
10316 mDailyChargeStepTracker.init();
10317 updateDailyDeadlineLocked();
10318
10319 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010320 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010321 mDailyItems.add(item);
10322 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10323 mDailyItems.remove(0);
10324 }
10325 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10326 try {
10327 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010328 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010329 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010330 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010331 BackgroundThread.getHandler().post(new Runnable() {
10332 @Override
10333 public void run() {
10334 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010335 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010336 FileOutputStream stream = null;
10337 try {
10338 stream = mDailyFile.startWrite();
10339 memStream.writeTo(stream);
10340 stream.flush();
10341 FileUtils.sync(stream);
10342 stream.close();
10343 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010344 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
10345 "batterystats-daily",
10346 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010347 } catch (IOException e) {
10348 Slog.w("BatteryStats",
10349 "Error writing battery daily items", e);
10350 mDailyFile.failWrite(stream);
10351 }
10352 }
10353 }
10354 });
10355 } catch (IOException e) {
10356 }
10357 }
10358 }
10359
10360 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10361 StringBuilder sb = new StringBuilder(64);
10362 out.startDocument(null, true);
10363 out.startTag(null, "daily-items");
10364 for (int i=0; i<mDailyItems.size(); i++) {
10365 final DailyItem dit = mDailyItems.get(i);
10366 out.startTag(null, "item");
10367 out.attribute(null, "start", Long.toString(dit.mStartTime));
10368 out.attribute(null, "end", Long.toString(dit.mEndTime));
10369 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10370 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010371 if (dit.mPackageChanges != null) {
10372 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10373 PackageChange pc = dit.mPackageChanges.get(j);
10374 if (pc.mUpdate) {
10375 out.startTag(null, "upd");
10376 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010377 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010378 out.endTag(null, "upd");
10379 } else {
10380 out.startTag(null, "rem");
10381 out.attribute(null, "pkg", pc.mPackageName);
10382 out.endTag(null, "rem");
10383 }
10384 }
10385 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010386 out.endTag(null, "item");
10387 }
10388 out.endTag(null, "daily-items");
10389 out.endDocument();
10390 }
10391
10392 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10393 StringBuilder tmpBuilder) throws IOException {
10394 if (steps != null) {
10395 out.startTag(null, tag);
10396 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10397 for (int i=0; i<steps.mNumStepDurations; i++) {
10398 out.startTag(null, "s");
10399 tmpBuilder.setLength(0);
10400 steps.encodeEntryAt(i, tmpBuilder);
10401 out.attribute(null, "v", tmpBuilder.toString());
10402 out.endTag(null, "s");
10403 }
10404 out.endTag(null, tag);
10405 }
10406 }
10407
10408 public void readDailyStatsLocked() {
10409 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10410 mDailyItems.clear();
10411 FileInputStream stream;
10412 try {
10413 stream = mDailyFile.openRead();
10414 } catch (FileNotFoundException e) {
10415 return;
10416 }
10417 try {
10418 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010419 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010420 readDailyItemsLocked(parser);
10421 } catch (XmlPullParserException e) {
10422 } finally {
10423 try {
10424 stream.close();
10425 } catch (IOException e) {
10426 }
10427 }
10428 }
10429
10430 private void readDailyItemsLocked(XmlPullParser parser) {
10431 try {
10432 int type;
10433 while ((type = parser.next()) != XmlPullParser.START_TAG
10434 && type != XmlPullParser.END_DOCUMENT) {
10435 ;
10436 }
10437
10438 if (type != XmlPullParser.START_TAG) {
10439 throw new IllegalStateException("no start tag found");
10440 }
10441
10442 int outerDepth = parser.getDepth();
10443 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10444 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10445 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10446 continue;
10447 }
10448
10449 String tagName = parser.getName();
10450 if (tagName.equals("item")) {
10451 readDailyItemTagLocked(parser);
10452 } else {
10453 Slog.w(TAG, "Unknown element under <daily-items>: "
10454 + parser.getName());
10455 XmlUtils.skipCurrentTag(parser);
10456 }
10457 }
10458
10459 } catch (IllegalStateException e) {
10460 Slog.w(TAG, "Failed parsing daily " + e);
10461 } catch (NullPointerException e) {
10462 Slog.w(TAG, "Failed parsing daily " + e);
10463 } catch (NumberFormatException e) {
10464 Slog.w(TAG, "Failed parsing daily " + e);
10465 } catch (XmlPullParserException e) {
10466 Slog.w(TAG, "Failed parsing daily " + e);
10467 } catch (IOException e) {
10468 Slog.w(TAG, "Failed parsing daily " + e);
10469 } catch (IndexOutOfBoundsException e) {
10470 Slog.w(TAG, "Failed parsing daily " + e);
10471 }
10472 }
10473
10474 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10475 XmlPullParserException, IOException {
10476 DailyItem dit = new DailyItem();
10477 String attr = parser.getAttributeValue(null, "start");
10478 if (attr != null) {
10479 dit.mStartTime = Long.parseLong(attr);
10480 }
10481 attr = parser.getAttributeValue(null, "end");
10482 if (attr != null) {
10483 dit.mEndTime = Long.parseLong(attr);
10484 }
10485 int outerDepth = parser.getDepth();
10486 int type;
10487 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10488 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10489 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10490 continue;
10491 }
10492
10493 String tagName = parser.getName();
10494 if (tagName.equals("dis")) {
10495 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10496 } else if (tagName.equals("chg")) {
10497 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010498 } else if (tagName.equals("upd")) {
10499 if (dit.mPackageChanges == null) {
10500 dit.mPackageChanges = new ArrayList<>();
10501 }
10502 PackageChange pc = new PackageChange();
10503 pc.mUpdate = true;
10504 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10505 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010506 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010507 dit.mPackageChanges.add(pc);
10508 XmlUtils.skipCurrentTag(parser);
10509 } else if (tagName.equals("rem")) {
10510 if (dit.mPackageChanges == null) {
10511 dit.mPackageChanges = new ArrayList<>();
10512 }
10513 PackageChange pc = new PackageChange();
10514 pc.mUpdate = false;
10515 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10516 dit.mPackageChanges.add(pc);
10517 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010518 } else {
10519 Slog.w(TAG, "Unknown element under <item>: "
10520 + parser.getName());
10521 XmlUtils.skipCurrentTag(parser);
10522 }
10523 }
10524 mDailyItems.add(dit);
10525 }
10526
10527 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10528 String tag)
10529 throws NumberFormatException, XmlPullParserException, IOException {
10530 final String numAttr = parser.getAttributeValue(null, "n");
10531 if (numAttr == null) {
10532 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10533 XmlUtils.skipCurrentTag(parser);
10534 return;
10535 }
10536 final int num = Integer.parseInt(numAttr);
10537 LevelStepTracker steps = new LevelStepTracker(num);
10538 if (isCharge) {
10539 dit.mChargeSteps = steps;
10540 } else {
10541 dit.mDischargeSteps = steps;
10542 }
10543 int i = 0;
10544 int outerDepth = parser.getDepth();
10545 int type;
10546 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10547 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10548 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10549 continue;
10550 }
10551
10552 String tagName = parser.getName();
10553 if ("s".equals(tagName)) {
10554 if (i < num) {
10555 String valueAttr = parser.getAttributeValue(null, "v");
10556 if (valueAttr != null) {
10557 steps.decodeEntryAt(i, valueAttr);
10558 i++;
10559 }
10560 }
10561 } else {
10562 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10563 + parser.getName());
10564 XmlUtils.skipCurrentTag(parser);
10565 }
10566 }
10567 steps.mNumStepDurations = i;
10568 }
10569
10570 @Override
10571 public DailyItem getDailyItemLocked(int daysAgo) {
10572 int index = mDailyItems.size()-1-daysAgo;
10573 return index >= 0 ? mDailyItems.get(index) : null;
10574 }
10575
10576 @Override
10577 public long getCurrentDailyStartTime() {
10578 return mDailyStartTime;
10579 }
10580
10581 @Override
10582 public long getNextMinDailyDeadline() {
10583 return mNextMinDailyDeadline;
10584 }
10585
10586 @Override
10587 public long getNextMaxDailyDeadline() {
10588 return mNextMaxDailyDeadline;
10589 }
10590
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010591 @Override
10592 public boolean startIteratingOldHistoryLocked() {
10593 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10594 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010595 if ((mHistoryIterator = mHistory) == null) {
10596 return false;
10597 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010598 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010599 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010600 mReadOverflow = false;
10601 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010602 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010603 }
10604
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010605 @Override
10606 public boolean getNextOldHistoryLocked(HistoryItem out) {
10607 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10608 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010609 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010610 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010611 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010612 HistoryItem cur = mHistoryIterator;
10613 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010614 if (!mReadOverflow && !end) {
10615 Slog.w(TAG, "Old history ends before new history!");
10616 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010617 return false;
10618 }
10619 out.setTo(cur);
10620 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010621 if (!mReadOverflow) {
10622 if (end) {
10623 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010624 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010625 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010626 pw.println("Histories differ!");
10627 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010628 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010629 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010630 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10631 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010632 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010633 }
10634 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010635 return true;
10636 }
10637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010638 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010639 public void finishIteratingOldHistoryLocked() {
10640 mIteratingHistory = false;
10641 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010642 mHistoryIterator = null;
10643 }
10644
10645 public int getHistoryTotalSize() {
10646 return MAX_HISTORY_BUFFER;
10647 }
10648
10649 public int getHistoryUsedSize() {
10650 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010651 }
10652
10653 @Override
10654 public boolean startIteratingHistoryLocked() {
10655 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10656 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010657 if (mHistoryBuffer.dataSize() <= 0) {
10658 return false;
10659 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010660 mHistoryBuffer.setDataPosition(0);
10661 mReadOverflow = false;
10662 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010663 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10664 mReadHistoryUids = new int[mHistoryTagPool.size()];
10665 mReadHistoryChars = 0;
10666 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10667 final HistoryTag tag = ent.getKey();
10668 final int idx = ent.getValue();
10669 mReadHistoryStrings[idx] = tag.string;
10670 mReadHistoryUids[idx] = tag.uid;
10671 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010672 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010673 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010674 }
10675
10676 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010677 public int getHistoryStringPoolSize() {
10678 return mReadHistoryStrings.length;
10679 }
10680
10681 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010682 public int getHistoryStringPoolBytes() {
10683 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10684 // Each string character is 2 bytes.
10685 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10686 }
10687
10688 @Override
10689 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010690 return mReadHistoryStrings[index];
10691 }
10692
10693 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010694 public int getHistoryTagPoolUid(int index) {
10695 return mReadHistoryUids[index];
10696 }
10697
10698 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010699 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010700 final int pos = mHistoryBuffer.dataPosition();
10701 if (pos == 0) {
10702 out.clear();
10703 }
10704 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010705 if (end) {
10706 return false;
10707 }
10708
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010709 final long lastRealtime = out.time;
10710 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010711 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010712 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10713 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010714 out.currentTime = lastWalltime + (out.time - lastRealtime);
10715 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010716 return true;
10717 }
10718
10719 @Override
10720 public void finishIteratingHistoryLocked() {
10721 mIteratingHistory = false;
10722 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010723 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010724 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010725
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010726 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010727 public long getHistoryBaseTime() {
10728 return mHistoryBaseTime;
10729 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010730
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010731 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010732 public int getStartCount() {
10733 return mStartCount;
10734 }
10735
10736 public boolean isOnBattery() {
10737 return mOnBattery;
10738 }
10739
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010740 public boolean isCharging() {
10741 return mCharging;
10742 }
10743
Mike Mac2f518a2017-09-19 16:06:03 -070010744 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010745 return state == Display.STATE_ON || state == Display.STATE_VR
10746 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010747 }
10748
10749 public boolean isScreenOff(int state) {
10750 return state == Display.STATE_OFF;
10751 }
10752
10753 public boolean isScreenDoze(int state) {
10754 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010755 }
10756
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010757 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010758 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010759 mOnBatteryTimeBase.init(uptime, realtime);
10760 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010761 mRealtime = 0;
10762 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010763 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010764 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010765 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010766
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010767 void initDischarge() {
10768 mLowDischargeAmountSinceCharge = 0;
10769 mHighDischargeAmountSinceCharge = 0;
10770 mDischargeAmountScreenOn = 0;
10771 mDischargeAmountScreenOnSinceCharge = 0;
10772 mDischargeAmountScreenOff = 0;
10773 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010774 mDischargeAmountScreenDoze = 0;
10775 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010776 mDischargeStepTracker.init();
10777 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010778 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010779 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010780 mDischargeLightDozeCounter.reset(false);
10781 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010782 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010783 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010784
10785 public void resetAllStatsCmdLocked() {
10786 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010787 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010788 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010789 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010790 long realtime = mSecRealtime * 1000;
10791 mDischargeStartLevel = mHistoryCur.batteryLevel;
10792 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010793 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010794 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10795 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010796 mOnBatteryTimeBase.reset(uptime, realtime);
10797 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10798 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010799 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010800 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010801 mDischargeScreenDozeUnplugLevel = 0;
10802 mDischargeScreenOffUnplugLevel = 0;
10803 } else if (isScreenDoze(mScreenState)) {
10804 mDischargeScreenOnUnplugLevel = 0;
10805 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010806 mDischargeScreenOffUnplugLevel = 0;
10807 } else {
10808 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010809 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010810 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10811 }
10812 mDischargeAmountScreenOn = 0;
10813 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010814 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010815 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010816 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010817 }
10818
10819 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010820 final long uptimeMillis = mClocks.uptimeMillis();
10821 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010822 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010823 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010824 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010825 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010826 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010827 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010828 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010829
10830 if (mPowerProfile != null) {
10831 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10832 } else {
10833 mEstimatedBatteryCapacity = -1;
10834 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010835 mMinLearnedBatteryCapacity = -1;
10836 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010837 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010838 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010839 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010840 mLongestLightIdleTime = 0;
10841 mLongestFullIdleTime = 0;
10842 mDeviceIdleModeLightTimer.reset(false);
10843 mDeviceIdleModeFullTimer.reset(false);
10844 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010845 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010846 mPhoneOnTimer.reset(false);
10847 mAudioOnTimer.reset(false);
10848 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010849 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010850 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010851 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010852 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010853 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010854 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010855 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010856 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010857 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010858 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010859 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010860 mNetworkByteActivityCounters[i].reset(false);
10861 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010862 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010863 mMobileRadioActiveTimer.reset(false);
10864 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010865 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010866 mMobileRadioActiveUnknownTime.reset(false);
10867 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010868 mWifiOnTimer.reset(false);
10869 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010870 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010871 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010872 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010873 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10874 mWifiSupplStateTimer[i].reset(false);
10875 }
10876 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10877 mWifiSignalStrengthsTimer[i].reset(false);
10878 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010879 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010880 mWifiActiveTimer.reset(false);
10881 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010882 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10883 mGpsSignalQualityTimer[i].reset(false);
10884 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010885 mBluetoothActivity.reset(false);
10886 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010887 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010888
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010889 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010890 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010891 mUidStats.remove(mUidStats.keyAt(i));
10892 i--;
10893 }
10894 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010895
Bookatz50df7112017-08-04 14:53:26 -070010896 if (mRpmStats.size() > 0) {
10897 for (SamplingTimer timer : mRpmStats.values()) {
10898 mOnBatteryTimeBase.remove(timer);
10899 }
10900 mRpmStats.clear();
10901 }
10902 if (mScreenOffRpmStats.size() > 0) {
10903 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10904 mOnBatteryScreenOffTimeBase.remove(timer);
10905 }
10906 mScreenOffRpmStats.clear();
10907 }
10908
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010909 if (mKernelWakelockStats.size() > 0) {
10910 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010911 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010912 }
10913 mKernelWakelockStats.clear();
10914 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010915
James Carr3a226052016-07-01 14:49:52 -070010916 if (mKernelMemoryStats.size() > 0) {
10917 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10918 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10919 }
10920 mKernelMemoryStats.clear();
10921 }
10922
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010923 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010924 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10925 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010926 }
10927 mWakeupReasonStats.clear();
10928 }
10929
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010930 mLastHistoryStepDetails = null;
10931 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10932 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10933 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10934 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10935 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10936 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10937 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
10938 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
10939 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
10940 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
10941
Mike Ma234d1822018-03-13 18:53:21 -070010942 mNumAllUidCpuTimeReads = 0;
10943 mNumUidsRemoved = 0;
10944
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010945 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010946
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010947 clearHistoryLocked();
Fyodor Kupolov8aa51242018-04-23 12:44:51 -070010948 mHandler.sendEmptyMessage(MSG_REPORT_RESET_STATS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010949 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010950
Dianne Hackborn40c87252014-03-19 16:55:40 -070010951 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010952 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010953 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
10954 // Not recording process starts/stops.
10955 continue;
10956 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010957 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010958 if (active == null) {
10959 continue;
10960 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010961 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
10962 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010963 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070010964 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
10965 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010966 }
10967 }
10968 }
10969 }
10970
Mike Mac2f518a2017-09-19 16:06:03 -070010971 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
10972 updateOldDischargeScreenLevelLocked(oldState);
10973 updateNewDischargeScreenLevelLocked(newState);
10974 }
10975
10976 private void updateOldDischargeScreenLevelLocked(int state) {
10977 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010978 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
10979 if (diff > 0) {
10980 mDischargeAmountScreenOn += diff;
10981 mDischargeAmountScreenOnSinceCharge += diff;
10982 }
Mike Mac2f518a2017-09-19 16:06:03 -070010983 } else if (isScreenDoze(state)) {
10984 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
10985 if (diff > 0) {
10986 mDischargeAmountScreenDoze += diff;
10987 mDischargeAmountScreenDozeSinceCharge += diff;
10988 }
10989 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010990 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
10991 if (diff > 0) {
10992 mDischargeAmountScreenOff += diff;
10993 mDischargeAmountScreenOffSinceCharge += diff;
10994 }
10995 }
Mike Mac2f518a2017-09-19 16:06:03 -070010996 }
10997
10998 private void updateNewDischargeScreenLevelLocked(int state) {
10999 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011000 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
11001 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011002 mDischargeScreenDozeUnplugLevel = 0;
11003 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011004 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011005 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
11006 mDischargeScreenOffUnplugLevel = 0;
11007 } else if (isScreenOff(state)) {
11008 mDischargeScreenOnUnplugLevel = 0;
11009 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011010 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
11011 }
11012 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011013
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011014 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011015 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070011016 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011017 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011018 }
11019
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011020 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
11021 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
11022
11023 private final Object mWifiNetworkLock = new Object();
11024
11025 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011026 private String[] mWifiIfaces = EmptyArray.STRING;
11027
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011028 @GuardedBy("mWifiNetworkLock")
11029 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011030
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011031 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011032
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011033 @GuardedBy("mModemNetworkLock")
11034 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011035
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011036 @GuardedBy("mModemNetworkLock")
11037 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
11038
11039 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
11040 try {
11041 if (!ArrayUtils.isEmpty(ifaces)) {
11042 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
11043 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
11044 }
11045 } catch (IOException e) {
11046 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011047 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011048 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011049 }
11050
Chenjie Yu89083392018-01-11 14:53:31 -080011051 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011052 * Distribute WiFi energy info and network traffic to apps.
11053 * @param info The energy information from the WiFi controller.
11054 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011055 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011056 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011057 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011058 }
11059
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011060 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011061 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011062 synchronized (mWifiNetworkLock) {
11063 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
11064 if (latestStats != null) {
11065 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
11066 mNetworkStatsPool.acquire());
11067 mNetworkStatsPool.release(mLastWifiNetworkStats);
11068 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011069 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011070 }
11071
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011072 synchronized (this) {
11073 if (!mOnBatteryInternal) {
11074 if (delta != null) {
11075 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011076 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011077 return;
11078 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011079
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011080 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
11081 SparseLongArray rxPackets = new SparseLongArray();
11082 SparseLongArray txPackets = new SparseLongArray();
11083 long totalTxPackets = 0;
11084 long totalRxPackets = 0;
11085 if (delta != null) {
11086 NetworkStats.Entry entry = new NetworkStats.Entry();
11087 final int size = delta.size();
11088 for (int i = 0; i < size; i++) {
11089 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011090
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011091 if (DEBUG_ENERGY) {
11092 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
11093 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11094 + " txPackets=" + entry.txPackets);
11095 }
11096
11097 if (entry.rxBytes == 0 && entry.txBytes == 0) {
11098 // Skip the lookup below since there is no work to do.
11099 continue;
11100 }
11101
11102 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11103 if (entry.rxBytes != 0) {
11104 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011105 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011106 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11107 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
11108 entry.rxPackets);
11109 }
11110 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11111 entry.rxBytes);
11112 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11113 entry.rxPackets);
11114
11115 rxPackets.put(u.getUid(), entry.rxPackets);
11116
11117 // Sum the total number of packets so that the Rx Power can
11118 // be evenly distributed amongst the apps.
11119 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011120 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011121
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011122 if (entry.txBytes != 0) {
11123 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011124 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011125 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11126 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
11127 entry.txPackets);
11128 }
11129 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11130 entry.txBytes);
11131 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11132 entry.txPackets);
11133
11134 txPackets.put(u.getUid(), entry.txPackets);
11135
11136 // Sum the total number of packets so that the Tx Power can
11137 // be evenly distributed amongst the apps.
11138 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011139 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080011140 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011141 mNetworkStatsPool.release(delta);
11142 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070011143 }
11144
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011145 if (info != null) {
11146 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070011147
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011148 // Measured in mAms
11149 final long txTimeMs = info.getControllerTxTimeMillis();
11150 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080011151 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011152 final long idleTimeMs = info.getControllerIdleTimeMillis();
11153 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011154
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011155 long leftOverRxTimeMs = rxTimeMs;
11156 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011157
Adam Lesinskie08af192015-03-25 16:42:59 -070011158 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011159 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
11160 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11161 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11162 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
11163 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080011164 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011165 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011166
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011167 long totalWifiLockTimeMs = 0;
11168 long totalScanTimeMs = 0;
11169
11170 // On the first pass, collect some totals so that we can normalize power
11171 // calculations if we need to.
11172 final int uidStatsSize = mUidStats.size();
11173 for (int i = 0; i < uidStatsSize; i++) {
11174 final Uid uid = mUidStats.valueAt(i);
11175
11176 // Sum the total scan power for all apps.
11177 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
11178 elapsedRealtimeMs * 1000) / 1000;
11179
11180 // Sum the total time holding wifi lock for all apps.
11181 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11182 elapsedRealtimeMs * 1000) / 1000;
11183 }
11184
11185 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
11186 Slog.d(TAG,
11187 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
11188 + rxTimeMs + " ms). Normalizing scan time.");
11189 }
11190 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11191 Slog.d(TAG,
11192 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11193 + txTimeMs + " ms). Normalizing scan time.");
11194 }
11195
11196 // Actually assign and distribute power usage to apps.
11197 for (int i = 0; i < uidStatsSize; i++) {
11198 final Uid uid = mUidStats.valueAt(i);
11199
11200 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11201 elapsedRealtimeMs * 1000) / 1000;
11202 if (scanTimeSinceMarkMs > 0) {
11203 // Set the new mark so that next time we get new data since this point.
11204 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11205
11206 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11207 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11208
11209 // Our total scan time is more than the reported Tx/Rx time.
11210 // This is possible because the cost of a scan is approximate.
11211 // Let's normalize the result so that we evenly blame each app
11212 // scanning.
11213 //
11214 // This means that we may have apps that transmitted/received packets not be
11215 // blamed for this, but this is fine as scans are relatively more expensive.
11216 if (totalScanTimeMs > rxTimeMs) {
11217 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11218 totalScanTimeMs;
11219 }
11220 if (totalScanTimeMs > txTimeMs) {
11221 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11222 totalScanTimeMs;
11223 }
11224
11225 if (DEBUG_ENERGY) {
11226 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11227 + scanRxTimeSinceMarkMs + " ms Tx:"
11228 + scanTxTimeSinceMarkMs + " ms)");
11229 }
11230
11231 ControllerActivityCounterImpl activityCounter =
11232 uid.getOrCreateWifiControllerActivityLocked();
11233 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11234 activityCounter.getTxTimeCounters()[0].addCountLocked(
11235 scanTxTimeSinceMarkMs);
11236 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11237 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11238 }
11239
11240 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11241 // lock.
11242 final long wifiLockTimeSinceMarkMs =
11243 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11244 elapsedRealtimeMs * 1000) / 1000;
11245 if (wifiLockTimeSinceMarkMs > 0) {
11246 // Set the new mark so that next time we get new data since this point.
11247 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11248
11249 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11250 / totalWifiLockTimeMs;
11251 if (DEBUG_ENERGY) {
11252 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11253 + myIdleTimeMs + " ms");
11254 }
11255 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11256 .addCountLocked(myIdleTimeMs);
11257 }
11258 }
11259
Adam Lesinskie08af192015-03-25 16:42:59 -070011260 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011261 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11262 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011263 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011264
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011265 // Distribute the remaining Tx power appropriately between all apps that transmitted
11266 // packets.
11267 for (int i = 0; i < txPackets.size(); i++) {
11268 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11269 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11270 / totalTxPackets;
11271 if (DEBUG_ENERGY) {
11272 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11273 }
11274 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11275 .addCountLocked(myTxTimeMs);
11276 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011277
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011278 // Distribute the remaining Rx power appropriately between all apps that received
11279 // packets.
11280 for (int i = 0; i < rxPackets.size(); i++) {
11281 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11282 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11283 / totalRxPackets;
11284 if (DEBUG_ENERGY) {
11285 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11286 }
11287 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11288 .addCountLocked(myRxTimeMs);
11289 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011290
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011291 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11292
11293
11294 // Update WiFi controller stats.
11295 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11296 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11297 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011298 mWifiActivity.getScanTimeCounter().addCountLocked(
11299 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011300 mWifiActivity.getIdleTimeCounter().addCountLocked(
11301 info.getControllerIdleTimeMillis());
11302
11303 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11304 final double opVolt = mPowerProfile.getAveragePower(
11305 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11306 if (opVolt != 0) {
11307 // We store the power drain as mAms.
11308 mWifiActivity.getPowerCounter().addCountLocked(
11309 (long) (info.getControllerEnergyUsed() / opVolt));
11310 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011311 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011312 }
11313 }
11314
Chenjie Yu89083392018-01-11 14:53:31 -080011315 private ModemActivityInfo mLastModemActivityInfo =
11316 new ModemActivityInfo(0, 0, 0, new int[0], 0, 0);
11317
Chenjie Yua54e54d2018-02-14 20:12:52 -080011318 private ModemActivityInfo getDeltaModemActivityInfo(ModemActivityInfo activityInfo) {
11319 if (activityInfo == null) {
11320 return null;
11321 }
11322 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
11323 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
11324 txTimeMs[i] = activityInfo.getTxTimeMillis()[i]
11325 - mLastModemActivityInfo.getTxTimeMillis()[i];
11326 }
11327 ModemActivityInfo deltaInfo = new ModemActivityInfo(activityInfo.getTimestamp(),
11328 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis(),
11329 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis(),
11330 txTimeMs,
11331 activityInfo.getRxTimeMillis() - mLastModemActivityInfo.getRxTimeMillis(),
11332 activityInfo.getEnergyUsed() - mLastModemActivityInfo.getEnergyUsed());
11333 mLastModemActivityInfo = activityInfo;
11334 return deltaInfo;
11335 }
11336
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011337 /**
11338 * Distribute Cell radio energy info and network traffic to apps.
11339 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011340 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011341 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011342 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011343 }
Chenjie Yua54e54d2018-02-14 20:12:52 -080011344 ModemActivityInfo deltaInfo = getDeltaModemActivityInfo(activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011345
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011346 // Add modem tx power to history.
Chenjie Yua54e54d2018-02-14 20:12:52 -080011347 addModemTxPowerToHistory(deltaInfo);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011348
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011349 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011350 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011351 synchronized (mModemNetworkLock) {
11352 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11353 if (latestStats != null) {
11354 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11355 mNetworkStatsPool.acquire());
11356 mNetworkStatsPool.release(mLastModemNetworkStats);
11357 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011358 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011359 }
11360
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011361 synchronized (this) {
11362 if (!mOnBatteryInternal) {
11363 if (delta != null) {
11364 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011365 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011366 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011367 }
11368
Chenjie Yua54e54d2018-02-14 20:12:52 -080011369 if (deltaInfo != null) {
Siddharth Ray2038af82018-01-17 17:40:26 -080011370 mHasModemReporting = true;
11371 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011372 deltaInfo.getIdleTimeMillis());
Siddharth Rayed754702018-02-15 12:44:37 -080011373 mModemActivity.getSleepTimeCounter().addCountLocked(
11374 deltaInfo.getSleepTimeMillis());
Chenjie Yua54e54d2018-02-14 20:12:52 -080011375 mModemActivity.getRxTimeCounter().addCountLocked(deltaInfo.getRxTimeMillis());
Siddharth Ray2038af82018-01-17 17:40:26 -080011376 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11377 mModemActivity.getTxTimeCounters()[lvl]
Chenjie Yua54e54d2018-02-14 20:12:52 -080011378 .addCountLocked(deltaInfo.getTxTimeMillis()[lvl]);
Siddharth Ray2038af82018-01-17 17:40:26 -080011379 }
11380
11381 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11382 final double opVolt = mPowerProfile.getAveragePower(
11383 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11384 if (opVolt != 0) {
11385 double energyUsed =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011386 deltaInfo.getSleepTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011387 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011388 + deltaInfo.getIdleTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011389 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011390 + deltaInfo.getRxTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011391 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chenjie Yua54e54d2018-02-14 20:12:52 -080011392 int[] txTimeMs = deltaInfo.getTxTimeMillis();
Chenjie Yu89083392018-01-11 14:53:31 -080011393 for (int i = 0; i < Math.min(txTimeMs.length,
Chenjie Yua54e54d2018-02-14 20:12:52 -080011394 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chenjie Yu89083392018-01-11 14:53:31 -080011395 energyUsed += txTimeMs[i] * mPowerProfile.getAveragePower(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011396 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
Siddharth Ray2038af82018-01-17 17:40:26 -080011397 }
11398
11399 // We store the power drain as mAms.
11400 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11401 }
11402 }
11403
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011404 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011405 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11406 elapsedRealtimeMs * 1000);
11407 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11408
11409 long totalRxPackets = 0;
11410 long totalTxPackets = 0;
11411 if (delta != null) {
11412 NetworkStats.Entry entry = new NetworkStats.Entry();
11413 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011414 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011415 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011416 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11417 continue;
11418 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011419
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011420 if (DEBUG_ENERGY) {
11421 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11422 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11423 + " txPackets=" + entry.txPackets);
11424 }
11425
11426 totalRxPackets += entry.rxPackets;
11427 totalTxPackets += entry.txPackets;
11428
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011429 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011430 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11431 entry.rxPackets);
11432 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11433 entry.txPackets);
11434 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11435 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11436 entry.rxBytes, entry.rxPackets);
11437 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11438 entry.txBytes, entry.txPackets);
11439 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011440
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011441 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11442 entry.rxBytes);
11443 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11444 entry.txBytes);
11445 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11446 entry.rxPackets);
11447 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11448 entry.txPackets);
11449 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011450
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011451 // Now distribute proportional blame to the apps that did networking.
11452 long totalPackets = totalRxPackets + totalTxPackets;
11453 if (totalPackets > 0) {
11454 for (int i = 0; i < size; i++) {
11455 entry = delta.getValues(i, entry);
11456 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11457 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011458 }
11459
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011460 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11461
11462 // Distribute total radio active time in to this app.
11463 final long appPackets = entry.rxPackets + entry.txPackets;
11464 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11465 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11466
11467 // Remove this app from the totals, so that we don't lose any time
11468 // due to rounding.
11469 radioTime -= appRadioTime;
11470 totalPackets -= appPackets;
11471
Chenjie Yua54e54d2018-02-14 20:12:52 -080011472 if (deltaInfo != null) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011473 ControllerActivityCounterImpl activityCounter =
11474 u.getOrCreateModemControllerActivityLocked();
11475 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chenjie Yua54e54d2018-02-14 20:12:52 -080011476 final long rxMs = (entry.rxPackets * deltaInfo.getRxTimeMillis())
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011477 / totalRxPackets;
11478 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11479 }
11480
11481 if (totalTxPackets > 0 && entry.txPackets > 0) {
11482 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11483 long txMs =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011484 entry.txPackets * deltaInfo.getTxTimeMillis()[lvl];
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011485 txMs /= totalTxPackets;
11486 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11487 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011488 }
11489 }
11490 }
11491 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011492
11493 if (radioTime > 0) {
11494 // Whoops, there is some radio time we can't blame on an app!
11495 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11496 mMobileRadioActiveUnknownCount.addCountLocked(1);
11497 }
11498
11499 mNetworkStatsPool.release(delta);
11500 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011501 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011502 }
11503 }
11504
11505 /**
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011506 * Add modem tx power to history
11507 * Device is said to be in high cellular transmit power when it has spent most of the transmit
11508 * time at the highest power level.
11509 * @param activityInfo
11510 */
Siddharth Raya67fb562018-02-28 13:46:16 -080011511 private synchronized void addModemTxPowerToHistory(final ModemActivityInfo activityInfo) {
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011512 if (activityInfo == null) {
11513 return;
11514 }
11515 int[] txTimeMs = activityInfo.getTxTimeMillis();
11516 if (txTimeMs == null || txTimeMs.length != ModemActivityInfo.TX_POWER_LEVELS) {
11517 return;
11518 }
11519 final long elapsedRealtime = mClocks.elapsedRealtime();
11520 final long uptime = mClocks.uptimeMillis();
11521 int levelMaxTimeSpent = 0;
11522 for (int i = 1; i < txTimeMs.length; i++) {
11523 if (txTimeMs[i] > txTimeMs[levelMaxTimeSpent]) {
11524 levelMaxTimeSpent = i;
11525 }
11526 }
11527 if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
11528 if (!mIsCellularTxPowerHigh) {
11529 mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11530 addHistoryRecordLocked(elapsedRealtime, uptime);
11531 mIsCellularTxPowerHigh = true;
11532 }
11533 return;
11534 }
11535 if (mIsCellularTxPowerHigh) {
11536 mHistoryCur.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11537 addHistoryRecordLocked(elapsedRealtime, uptime);
11538 mIsCellularTxPowerHigh = false;
11539 }
11540 return;
11541 }
11542
Mike Ma561a8d92018-03-20 18:24:05 -070011543 private final class BluetoothActivityInfoCache {
11544 long idleTimeMs;
11545 long rxTimeMs;
11546 long txTimeMs;
11547 long energy;
11548
11549 SparseLongArray uidRxBytes = new SparseLongArray();
11550 SparseLongArray uidTxBytes = new SparseLongArray();
11551
11552 void set(BluetoothActivityEnergyInfo info) {
11553 idleTimeMs = info.getControllerIdleTimeMillis();
11554 rxTimeMs = info.getControllerRxTimeMillis();
11555 txTimeMs = info.getControllerTxTimeMillis();
11556 energy = info.getControllerEnergyUsed();
11557 if (info.getUidTraffic() != null) {
11558 for (UidTraffic traffic : info.getUidTraffic()) {
11559 uidRxBytes.put(traffic.getUid(), traffic.getRxBytes());
11560 uidTxBytes.put(traffic.getUid(), traffic.getTxBytes());
11561 }
11562 }
11563 }
11564 }
11565
11566 private final BluetoothActivityInfoCache mLastBluetoothActivityInfo
11567 = new BluetoothActivityInfoCache();
11568
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011569 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011570 * Distribute Bluetooth energy info and network traffic to apps.
Mike Ma561a8d92018-03-20 18:24:05 -070011571 *
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011572 * @param info The energy information from the bluetooth controller.
11573 */
11574 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011575 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011576 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011577 }
11578
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011579 if (info == null || !mOnBatteryInternal) {
11580 return;
11581 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011582
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011583 mHasBluetoothReporting = true;
11584
Bookatz867c0d72017-03-07 18:23:42 -080011585 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Mike Ma561a8d92018-03-20 18:24:05 -070011586 final long rxTimeMs =
11587 info.getControllerRxTimeMillis() - mLastBluetoothActivityInfo.rxTimeMs;
11588 final long txTimeMs =
11589 info.getControllerTxTimeMillis() - mLastBluetoothActivityInfo.txTimeMs;
11590 final long idleTimeMs =
11591 info.getControllerIdleTimeMillis() - mLastBluetoothActivityInfo.idleTimeMs;
11592
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011593 if (DEBUG_ENERGY) {
11594 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11595 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11596 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011597 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011598 }
11599
11600 long totalScanTimeMs = 0;
11601
11602 final int uidCount = mUidStats.size();
11603 for (int i = 0; i < uidCount; i++) {
11604 final Uid u = mUidStats.valueAt(i);
11605 if (u.mBluetoothScanTimer == null) {
11606 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011607 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011608
Bookatzaa4594a2017-03-24 12:39:56 -070011609 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011610 elapsedRealtimeMs * 1000) / 1000;
11611 }
11612
11613 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11614 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11615
11616 if (DEBUG_ENERGY) {
11617 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11618 + " TX=" + normalizeScanTxTime);
11619 }
11620
11621 long leftOverRxTimeMs = rxTimeMs;
11622 long leftOverTxTimeMs = txTimeMs;
11623
11624 for (int i = 0; i < uidCount; i++) {
11625 final Uid u = mUidStats.valueAt(i);
11626 if (u.mBluetoothScanTimer == null) {
11627 continue;
11628 }
11629
Bookatzaa4594a2017-03-24 12:39:56 -070011630 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011631 elapsedRealtimeMs * 1000) / 1000;
11632 if (scanTimeSinceMarkMs > 0) {
11633 // Set the new mark so that next time we get new data since this point.
11634 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11635
11636 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11637 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11638
11639 if (normalizeScanRxTime) {
11640 // Scan time is longer than the total rx time in the controller,
11641 // so distribute the scan time proportionately. This means regular traffic
11642 // will not blamed, but scans are more expensive anyways.
11643 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11644 }
11645
11646 if (normalizeScanTxTime) {
11647 // Scan time is longer than the total tx time in the controller,
11648 // so distribute the scan time proportionately. This means regular traffic
11649 // will not blamed, but scans are more expensive anyways.
11650 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11651 }
11652
11653 final ControllerActivityCounterImpl counter =
11654 u.getOrCreateBluetoothControllerActivityLocked();
11655 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11656 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11657
11658 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11659 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11660 }
11661 }
11662
11663 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011664 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs + " TX="
11665 + leftOverTxTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011666 }
11667
11668 //
11669 // Now distribute blame to apps that did bluetooth traffic.
11670 //
11671
11672 long totalTxBytes = 0;
11673 long totalRxBytes = 0;
11674
11675 final UidTraffic[] uidTraffic = info.getUidTraffic();
Mike Ma561a8d92018-03-20 18:24:05 -070011676 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11677 for (int i = 0; i < numUids; i++) {
11678 final UidTraffic traffic = uidTraffic[i];
11679 final long rxBytes = traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(
11680 traffic.getUid());
11681 final long txBytes = traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(
11682 traffic.getUid());
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011683
11684 // Add to the global counters.
Mike Ma561a8d92018-03-20 18:24:05 -070011685 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(rxBytes);
11686 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(txBytes);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011687
11688 // Add to the UID counters.
11689 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Mike Ma561a8d92018-03-20 18:24:05 -070011690 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, rxBytes, 0);
11691 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, txBytes, 0);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011692
11693 // Calculate the total traffic.
Mike Ma561a8d92018-03-20 18:24:05 -070011694 totalRxBytes += rxBytes;
11695 totalTxBytes += txBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011696 }
11697
Mike Ma561a8d92018-03-20 18:24:05 -070011698 if ((totalTxBytes != 0 || totalRxBytes != 0) && (leftOverRxTimeMs != 0
11699 || leftOverTxTimeMs != 0)) {
11700 for (int i = 0; i < numUids; i++) {
11701 final UidTraffic traffic = uidTraffic[i];
11702 final int uid = traffic.getUid();
11703 final long rxBytes =
11704 traffic.getRxBytes() - mLastBluetoothActivityInfo.uidRxBytes.get(uid);
11705 final long txBytes =
11706 traffic.getTxBytes() - mLastBluetoothActivityInfo.uidTxBytes.get(uid);
Adam Lesinski50e47602015-12-04 17:04:54 -080011707
Mike Ma561a8d92018-03-20 18:24:05 -070011708 final Uid u = getUidStatsLocked(mapUid(uid));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011709 final ControllerActivityCounterImpl counter =
11710 u.getOrCreateBluetoothControllerActivityLocked();
11711
Mike Ma561a8d92018-03-20 18:24:05 -070011712 if (totalRxBytes > 0 && rxBytes > 0) {
11713 final long timeRxMs = (leftOverRxTimeMs * rxBytes) / totalRxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011714 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011715 Slog.d(TAG, "UID=" + uid + " rx_bytes=" + rxBytes + " rx_time=" + timeRxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011716 }
11717 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11718 leftOverRxTimeMs -= timeRxMs;
11719 }
11720
Mike Ma561a8d92018-03-20 18:24:05 -070011721 if (totalTxBytes > 0 && txBytes > 0) {
11722 final long timeTxMs = (leftOverTxTimeMs * txBytes) / totalTxBytes;
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011723 if (DEBUG_ENERGY) {
Mike Ma561a8d92018-03-20 18:24:05 -070011724 Slog.d(TAG, "UID=" + uid + " tx_bytes=" + txBytes + " tx_time=" + timeTxMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011725 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011726 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11727 leftOverTxTimeMs -= timeTxMs;
11728 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011729 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011730 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011731
Chenjie Yu89083392018-01-11 14:53:31 -080011732 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11733 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11734 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011735
11736 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11737 final double opVolt = mPowerProfile.getAveragePower(
11738 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11739 if (opVolt != 0) {
11740 // We store the power drain as mAms.
11741 mBluetoothActivity.getPowerCounter().addCountLocked(
Mike Ma561a8d92018-03-20 18:24:05 -070011742 (long) ((info.getControllerEnergyUsed() - mLastBluetoothActivityInfo.energy)
11743 / opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011744 }
Mike Ma561a8d92018-03-20 18:24:05 -070011745 mLastBluetoothActivityInfo.set(info);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011746 }
11747
11748 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011749 * Read and record Resource Power Manager (RPM) state and voter times.
11750 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11751 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011752 */
11753 public void updateRpmStatsLocked() {
11754 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011755 long now = SystemClock.elapsedRealtime();
11756 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11757 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11758 mLastRpmStatsUpdateTimeMs = now;
11759 }
Bookatz50df7112017-08-04 14:53:26 -070011760
11761 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11762 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11763
11764 // Update values for this platform state.
11765 final String pName = pstate.getKey();
11766 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11767 final int pCount = pstate.getValue().mCount;
11768 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011769 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11770 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11771 }
Bookatz50df7112017-08-04 14:53:26 -070011772
11773 // Update values for each voter of this platform state.
11774 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11775 : pstate.getValue().mVoters.entrySet()) {
11776 final String vName = pName + "." + voter.getKey();
11777 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11778 final int vCount = voter.getValue().mCount;
11779 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011780 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11781 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11782 }
Bookatz50df7112017-08-04 14:53:26 -070011783 }
11784 }
11785
11786 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11787 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11788
11789 final String subsysName = subsys.getKey();
11790 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11791 : subsys.getValue().mStates.entrySet()) {
11792 final String name = subsysName + "." + sstate.getKey();
11793 final long timeUs = sstate.getValue().mTimeMs * 1000;
11794 final int count = sstate.getValue().mCount;
11795 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011796 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11797 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11798 }
Bookatz50df7112017-08-04 14:53:26 -070011799 }
11800 }
11801 }
11802
11803 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011804 * Read and distribute kernel wake lock use across apps.
11805 */
11806 public void updateKernelWakelocksLocked() {
11807 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11808 mTmpWakelockStats);
11809 if (wakelockStats == null) {
11810 // Not crashing might make board bringup easier.
11811 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11812 return;
11813 }
11814
11815 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11816 String name = ent.getKey();
11817 KernelWakelockStats.Entry kws = ent.getValue();
11818
11819 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11820 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011821 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011822 mKernelWakelockStats.put(name, kwlt);
11823 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011824
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011825 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011826 kwlt.setUpdateVersion(kws.mVersion);
11827 }
11828
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011829 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011830 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11831 // this time.
11832 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11833 SamplingTimer st = ent.getValue();
11834 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11835 st.endSample();
11836 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011837 }
11838 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011839
Adam Lesinskid84ad302016-05-17 18:31:02 -070011840 // Record whether we've seen a non-zero time (for debugging b/22716723).
11841 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011842 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11843 }
11844
11845 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11846 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11847 wakelockStats.kernelWakelockVersion);
11848 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011849 }
11850
Adam Lesinski72478f02015-06-17 15:39:43 -070011851 // We use an anonymous class to access these variables,
11852 // so they can't live on the stack or they'd have to be
11853 // final MutableLong objects (more allocations).
11854 // Used in updateCpuTimeLocked().
11855 long mTempTotalCpuUserTimeUs;
11856 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011857 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011858
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011859 /**
James Carr3a226052016-07-01 14:49:52 -070011860 * Reads the newest memory stats from the kernel.
11861 */
11862 public void updateKernelMemoryBandwidthLocked() {
11863 mKernelMemoryBandwidthStats.updateStats();
11864 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11865 final int bandwidthEntryCount = bandwidthEntries.size();
11866 int index;
11867 for (int i = 0; i < bandwidthEntryCount; i++) {
11868 SamplingTimer timer;
11869 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11870 timer = mKernelMemoryStats.valueAt(index);
11871 } else {
11872 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11873 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11874 }
11875 timer.update(bandwidthEntries.valueAt(i), 1);
11876 if (DEBUG_MEMORY) {
11877 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11878 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11879 mKernelMemoryStats.get(
11880 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11881 mKernelMemoryStats.size()));
11882 }
11883 }
11884 }
11885
Sudheer Shankac57729a2018-02-09 15:44:42 -080011886 public boolean isOnBatteryLocked() {
11887 return mOnBatteryTimeBase.isRunning();
11888 }
11889
11890 public boolean isOnBatteryScreenOffLocked() {
11891 return mOnBatteryScreenOffTimeBase.isRunning();
11892 }
11893
James Carr3a226052016-07-01 14:49:52 -070011894 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011895 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11896 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11897 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011898 * It's possible this will be invoked after the internal battery/screen states are updated, so
11899 * passing the appropriate battery/screen states to try attribute the cpu times to correct
11900 * buckets.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011901 */
Andreas Gampe3f24e692018-02-05 13:24:28 -080011902 @GuardedBy("this")
Sudheer Shankac57729a2018-02-09 15:44:42 -080011903 public void updateCpuTimeLocked(boolean onBattery, boolean onBatteryScreenOff) {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011904 if (mPowerProfile == null) {
11905 return;
11906 }
11907
Adam Lesinski72478f02015-06-17 15:39:43 -070011908 if (DEBUG_ENERGY_CPU) {
11909 Slog.d(TAG, "!Cpu updating!");
11910 }
11911
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011912 if (mCpuFreqs == null) {
11913 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11914 }
11915
Sudheer Shanka38383232017-07-25 09:55:03 -070011916 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11917 // usually holding the wakelock on behalf of an app.
11918 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11919 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Sudheer Shankac57729a2018-02-09 15:44:42 -080011920 if (onBatteryScreenOff) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011921 partialTimersToConsider = new ArrayList<>();
11922 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011923 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011924 // Since the collection and blaming of wakelocks can be scheduled to run after
11925 // some delay, the mPartialTimers list may have new entries. We can't blame
11926 // the newly added timer for past cpu time, so we only consider timers that
11927 // were present for one round of collection. Once a timer has gone through
11928 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011929 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011930 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011931 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011932 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011933 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011934 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011935
Sudheer Shanka38383232017-07-25 09:55:03 -070011936 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11937 // need to take the snapshots.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011938 if (!onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011939 mKernelUidCpuTimeReader.readDelta(null);
11940 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070011941 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011942 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11943 mKernelUidCpuActiveTimeReader.readDelta(null);
11944 mKernelUidCpuClusterTimeReader.readDelta(null);
Mike Ma234d1822018-03-13 18:53:21 -070011945 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011946 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011947 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
11948 mKernelCpuSpeedReaders[cluster].readDelta();
11949 }
11950 return;
11951 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011952
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011953 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011954 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
11955 ? null : new SparseLongArray();
Sudheer Shankac57729a2018-02-09 15:44:42 -080011956 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011957 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
11958 // freqs, so no need to approximate these values.
11959 if (updatedUids != null) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080011960 updateClusterSpeedTimes(updatedUids, onBattery);
Sudheer Shanka671985f2017-05-19 11:33:42 -070011961 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080011962 readKernelUidCpuFreqTimesLocked(partialTimersToConsider, onBattery, onBatteryScreenOff);
Mike Ma234d1822018-03-13 18:53:21 -070011963 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011964 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080011965 readKernelUidCpuActiveTimesLocked(onBattery);
11966 readKernelUidCpuClusterTimesLocked(onBattery);
Mike Ma234d1822018-03-13 18:53:21 -070011967 mNumAllUidCpuTimeReads += 2;
Mike Mafae87da2018-01-19 20:07:20 -080011968 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011969 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011970
Sudheer Shanka38383232017-07-25 09:55:03 -070011971 /**
11972 * Mark the current partial timers as gone through a collection so that they will be
11973 * considered in the next cpu times distribution to wakelock holders.
11974 */
11975 @VisibleForTesting
11976 public void markPartialTimersAsEligible() {
11977 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
11978 // No difference, so each timer is now considered for the next collection.
11979 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
11980 mPartialTimers.get(i).mInList = true;
11981 }
11982 } else {
11983 // The lists are different, meaning we added (or removed a timer) since the last
11984 // collection.
11985 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
11986 mLastPartialTimers.get(i).mInList = false;
11987 }
11988 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070011989
Sudheer Shanka38383232017-07-25 09:55:03 -070011990 // Mark the current timers as gone through a collection.
11991 final int numPartialTimers = mPartialTimers.size();
11992 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011993 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011994 timer.mInList = true;
11995 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070011996 }
11997 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011998 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011999
Sudheer Shanka38383232017-07-25 09:55:03 -070012000 /**
12001 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
12002 * calculate cpu times spent by each uid at different frequencies.
12003 *
12004 * @param updatedUids The uids for which times spent at different frequencies are calculated.
12005 */
12006 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012007 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012008 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012009 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070012010 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012011 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012012 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
12013 if (clusterSpeedTimesMs[cluster] != null) {
12014 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
12015 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012016 }
12017 }
12018 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012019 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012020 // We have cpu times per freq aggregated over all uids but we need the times per uid.
12021 // So, we distribute total time spent by an uid to different cpu freqs based on the
12022 // amount of time cpu was running at that freq.
12023 final int updatedUidsCount = updatedUids.size();
12024 for (int i = 0; i < updatedUidsCount; ++i) {
12025 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070012026 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012027 // Add the cpu speeds to this UID.
12028 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070012029 if (u.mCpuClusterSpeedTimesUs == null ||
12030 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012031 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012032 }
12033
Sudheer Shankaaf857412017-07-21 00:14:24 -070012034 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
12035 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
12036 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
12037 u.mCpuClusterSpeedTimesUs[cluster].length) {
12038 u.mCpuClusterSpeedTimesUs[cluster]
12039 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012040 }
12041
Sudheer Shankaaf857412017-07-21 00:14:24 -070012042 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012043 for (int speed = 0; speed < speedsInCluster; speed++) {
12044 if (cpuSpeeds[speed] == null) {
12045 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12046 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012047 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
12048 * clusterSpeedTimesMs[cluster][speed]
Sudheer Shankac57729a2018-02-09 15:44:42 -080012049 / totalCpuClustersTimeMs, onBattery);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012050 }
12051 }
12052 }
12053 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012054 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012055
Sudheer Shanka38383232017-07-25 09:55:03 -070012056 /**
12057 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
12058 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
12059 * wakelock holders.
12060 *
12061 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
12062 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
12063 */
12064 @VisibleForTesting
12065 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
Sudheer Shankac57729a2018-02-09 15:44:42 -080012066 @Nullable SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012067 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
12068 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12069 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070012070
Sudheer Shanka38383232017-07-25 09:55:03 -070012071 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
12072 uid = mapUid(uid);
12073 if (Process.isIsolated(uid)) {
12074 // This could happen if the isolated uid mapping was removed before that process
12075 // was actually killed.
12076 mKernelUidCpuTimeReader.removeUid(uid);
12077 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
12078 return;
12079 }
12080 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12081 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
12082 mKernelUidCpuTimeReader.removeUid(uid);
12083 return;
12084 }
12085 final Uid u = getUidStatsLocked(uid);
12086
12087 // Accumulate the total system and user time.
12088 mTempTotalCpuUserTimeUs += userTimeUs;
12089 mTempTotalCpuSystemTimeUs += systemTimeUs;
12090
12091 StringBuilder sb = null;
12092 if (DEBUG_ENERGY_CPU) {
12093 sb = new StringBuilder();
12094 sb.append(" got time for uid=").append(u.mUid).append(": u=");
12095 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12096 sb.append(" s=");
12097 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12098 sb.append("\n");
12099 }
12100
12101 if (numWakelocks > 0) {
12102 // We have wakelocks being held, so only give a portion of the
12103 // time to the process. The rest will be distributed among wakelock
12104 // holders.
12105 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
12106 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
12107 }
12108
12109 if (sb != null) {
12110 sb.append(" adding to uid=").append(u.mUid).append(": u=");
12111 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12112 sb.append(" s=");
12113 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12114 Slog.d(TAG, sb.toString());
12115 }
12116
Sudheer Shankac57729a2018-02-09 15:44:42 -080012117 u.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12118 u.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012119 if (updatedUids != null) {
12120 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
12121 }
12122 });
12123
12124 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12125 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12126 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
12127 }
12128
12129 if (numWakelocks > 0) {
12130 // Distribute a portion of the total cpu time to wakelock holders.
12131 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12132 mTempTotalCpuSystemTimeUs =
12133 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12134
12135 for (int i = 0; i < numWakelocks; ++i) {
12136 final StopwatchTimer timer = partialTimers.get(i);
12137 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
12138 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
12139
12140 if (DEBUG_ENERGY_CPU) {
12141 final StringBuilder sb = new StringBuilder();
12142 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
12143 .append(": u=");
12144 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12145 sb.append(" s=");
12146 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12147 Slog.d(TAG, sb.toString());
12148 }
12149
Sudheer Shankac57729a2018-02-09 15:44:42 -080012150 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12151 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012152 if (updatedUids != null) {
12153 final int uid = timer.mUid.getUid();
12154 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
12155 }
12156
12157 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
Sudheer Shankac57729a2018-02-09 15:44:42 -080012158 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012159
12160 mTempTotalCpuUserTimeUs -= userTimeUs;
12161 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070012162 }
12163 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012164 }
12165
Sudheer Shanka38383232017-07-25 09:55:03 -070012166 /**
12167 * Take a snapshot of the cpu times spent by each uid in each freq and update the
12168 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012169 *
12170 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070012171 */
12172 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012173 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
12174 boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012175 final boolean perClusterTimesAvailable =
12176 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
12177 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12178 final int numClusters = mPowerProfile.getNumCpuClusters();
12179 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012180 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012181 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
12182 uid = mapUid(uid);
12183 if (Process.isIsolated(uid)) {
12184 mKernelUidCpuFreqTimeReader.removeUid(uid);
12185 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
12186 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070012187 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012188 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12189 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
12190 mKernelUidCpuFreqTimeReader.removeUid(uid);
12191 return;
12192 }
12193 final Uid u = getUidStatsLocked(uid);
12194 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12195 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
12196 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012197 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012198 if (u.mScreenOffCpuFreqTimeMs == null ||
12199 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12200 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
12201 mOnBatteryScreenOffTimeBase);
12202 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012203 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012204
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012205 if (perClusterTimesAvailable) {
12206 if (u.mCpuClusterSpeedTimesUs == null ||
12207 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12208 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012209 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012210 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
12211 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012212 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012213
12214 int freqIndex = 0;
12215 for (int cluster = 0; cluster < numClusters; ++cluster) {
12216 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12217 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12218 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12219 u.mCpuClusterSpeedTimesUs[cluster]
12220 = new LongSamplingCounter[speedsInCluster];
12221 }
12222 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
12223 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
12224 }
12225 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
12226 for (int speed = 0; speed < speedsInCluster; ++speed) {
12227 if (cpuTimesUs[speed] == null) {
12228 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12229 }
12230 final long appAllocationUs;
12231 if (mWakeLockAllocationsUs != null) {
12232 appAllocationUs =
12233 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
12234 mWakeLockAllocationsUs[cluster][speed] +=
12235 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
12236 } else {
12237 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
12238 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012239 cpuTimesUs[speed].addCountLocked(appAllocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012240 freqIndex++;
12241 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012242 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012243 }
12244 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012245
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012246 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12247 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12248 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
12249 }
12250
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012251 if (mWakeLockAllocationsUs != null) {
12252 for (int i = 0; i < numWakelocks; ++i) {
12253 final Uid u = partialTimers.get(i).mUid;
12254 if (u.mCpuClusterSpeedTimesUs == null ||
12255 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12256 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
12257 }
12258
12259 for (int cluster = 0; cluster < numClusters; ++cluster) {
12260 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12261 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12262 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12263 u.mCpuClusterSpeedTimesUs[cluster]
12264 = new LongSamplingCounter[speedsInCluster];
12265 }
12266 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
12267 for (int speed = 0; speed < speedsInCluster; ++speed) {
12268 if (cpuTimeUs[speed] == null) {
12269 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12270 }
12271 final long allocationUs =
12272 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
Sudheer Shankac57729a2018-02-09 15:44:42 -080012273 cpuTimeUs[speed].addCountLocked(allocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012274 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
12275 }
12276 }
12277 }
12278 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012279 }
12280
Mike Ma3d422c32017-10-25 11:08:57 -070012281 /**
12282 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
12283 * counters.
12284 */
12285 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012286 public void readKernelUidCpuActiveTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012287 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012288 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012289 uid = mapUid(uid);
12290 if (Process.isIsolated(uid)) {
12291 mKernelUidCpuActiveTimeReader.removeUid(uid);
12292 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
12293 return;
12294 }
12295 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12296 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
12297 mKernelUidCpuActiveTimeReader.removeUid(uid);
12298 return;
12299 }
12300 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012301 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012302 });
12303
12304 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12305 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12306 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12307 }
12308 }
12309
12310 /**
12311 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12312 * counters.
12313 */
12314 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012315 public void readKernelUidCpuClusterTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012316 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012317 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012318 uid = mapUid(uid);
12319 if (Process.isIsolated(uid)) {
12320 mKernelUidCpuClusterTimeReader.removeUid(uid);
12321 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12322 return;
12323 }
12324 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12325 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12326 mKernelUidCpuClusterTimeReader.removeUid(uid);
12327 return;
12328 }
12329 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012330 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012331 });
12332
12333 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12334 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12335 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12336 }
12337 }
12338
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012339 boolean setChargingLocked(boolean charging) {
12340 if (mCharging != charging) {
12341 mCharging = charging;
12342 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012343 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012344 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012345 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012346 }
12347 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12348 return true;
12349 }
12350 return false;
12351 }
12352
Andreas Gampe3f24e692018-02-05 13:24:28 -080012353 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -070012354 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12355 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012356 boolean doWrite = false;
12357 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12358 m.arg1 = onBattery ? 1 : 0;
12359 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012360
Dianne Hackborn40c87252014-03-19 16:55:40 -070012361 final long uptime = mSecUptime * 1000;
12362 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012363 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012364 if (onBattery) {
12365 // We will reset our status if we are unplugging after the
12366 // battery was last full, or the level is at 100, or
12367 // we have gone through a significant charge (from a very low
12368 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012369 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012370 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012371 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012372 || (mDischargeCurrentLevel < 20 && level >= 80)
12373 || (getHighDischargeAmountSinceCharge() >= 200
12374 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012375 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012376 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012377 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12378 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012379 // Before we write, collect a snapshot of the final aggregated
12380 // stats to be reported in the next checkin. Only do this if we have
12381 // a sufficient amount of data to make it interesting.
12382 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012383 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012384 final Parcel parcel = Parcel.obtain();
12385 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012386 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012387 BackgroundThread.getHandler().post(new Runnable() {
12388 @Override public void run() {
12389 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012390 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012391 FileOutputStream stream = null;
12392 try {
12393 stream = mCheckinFile.startWrite();
12394 stream.write(parcel.marshall());
12395 stream.flush();
12396 FileUtils.sync(stream);
12397 stream.close();
12398 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012399 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12400 "batterystats-checkin",
12401 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012402 } catch (IOException e) {
12403 Slog.w("BatteryStats",
12404 "Error writing checkin battery statistics", e);
12405 mCheckinFile.failWrite(stream);
12406 } finally {
12407 parcel.recycle();
12408 }
12409 }
12410 }
12411 });
12412 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012413 doWrite = true;
12414 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012415 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012416 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012417 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012418 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012419 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012420 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012421 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012422 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012423 if (mCharging) {
12424 setChargingLocked(false);
12425 }
12426 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012427 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012428 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012429 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012430 mDischargeStepTracker.clearTime();
12431 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012432 mInitStepMode = mCurStepMode;
12433 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012434 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012435 mHistoryCur.batteryLevel = (byte)level;
12436 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12437 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12438 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012439 if (reset) {
12440 mRecordingHistory = true;
12441 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12442 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012443 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012444 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012445 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012446 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012447 mDischargeScreenDozeUnplugLevel = 0;
12448 mDischargeScreenOffUnplugLevel = 0;
12449 } else if (isScreenDoze(screenState)) {
12450 mDischargeScreenOnUnplugLevel = 0;
12451 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012452 mDischargeScreenOffUnplugLevel = 0;
12453 } else {
12454 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012455 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012456 mDischargeScreenOffUnplugLevel = level;
12457 }
12458 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012459 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012460 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012461 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012462 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012463 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012464 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012465 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012466 mHistoryCur.batteryLevel = (byte)level;
12467 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12468 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12469 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012470 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012471 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012472 if (level < mDischargeUnplugLevel) {
12473 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12474 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12475 }
Mike Mac2f518a2017-09-19 16:06:03 -070012476 updateDischargeScreenLevelsLocked(screenState, screenState);
12477 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012478 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012479 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012480 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012481 mInitStepMode = mCurStepMode;
12482 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012483 }
12484 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12485 if (mFile != null) {
12486 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012487 }
12488 }
12489 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012490
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012491 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12492 boolean reset) {
12493 mRecordingHistory = true;
12494 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012495 addHistoryBufferLocked(elapsedRealtimeMs,
Dianne Hackborn37de0982014-05-09 09:32:18 -070012496 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012497 mHistoryCur);
12498 mHistoryCur.currentTime = 0;
12499 if (reset) {
12500 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12501 }
12502 }
12503
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012504 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12505 final long uptimeMs) {
12506 if (mRecordingHistory) {
12507 mHistoryCur.currentTime = currentTime;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012508 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_CURRENT_TIME, mHistoryCur);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012509 mHistoryCur.currentTime = 0;
12510 }
12511 }
12512
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012513 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12514 if (mRecordingHistory) {
12515 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012516 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_SHUTDOWN, mHistoryCur);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012517 mHistoryCur.currentTime = 0;
12518 }
12519 }
12520
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012521 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012522 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012523 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012524 }
12525 }
12526
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012527 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012528 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012529
Andreas Gampe3f24e692018-02-05 13:24:28 -080012530 @GuardedBy("this")
Bookatz8c6571b2017-10-24 15:04:41 -070012531 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12532 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12533 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012534 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12535 temp = Math.max(0, temp);
12536
Bookatz8c6571b2017-10-24 15:04:41 -070012537 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
Tej Singh40298312018-02-16 00:15:09 -080012538 status, plugType, level);
Bookatz8c6571b2017-10-24 15:04:41 -070012539
Sudheer Shankac57729a2018-02-09 15:44:42 -080012540 final boolean onBattery = isOnBattery(plugType, status);
Joe Onoratoabded112016-02-08 16:49:39 -080012541 final long uptime = mClocks.uptimeMillis();
12542 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012543 if (!mHaveBatteryLevel) {
12544 mHaveBatteryLevel = true;
12545 // We start out assuming that the device is plugged in (not
12546 // on battery). If our first report is now that we are indeed
12547 // plugged in, then twiddle our state to correctly reflect that
12548 // since we won't be going through the full setOnBattery().
12549 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012550 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012551 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012552 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012553 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012554 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012555 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012556 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012557 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012558 mHistoryCur.batteryStatus = (byte)status;
12559 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012560 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012561 mMaxChargeStepLevel = mMinDischargeStepLevel =
12562 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012563 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012564 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12565 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12566 }
12567 int oldStatus = mHistoryCur.batteryStatus;
12568 if (onBattery) {
12569 mDischargeCurrentLevel = level;
12570 if (!mRecordingHistory) {
12571 mRecordingHistory = true;
12572 startRecordingHistory(elapsedRealtime, uptime, true);
12573 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012574 } else if (level < 96 &&
12575 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012576 if (!mRecordingHistory) {
12577 mRecordingHistory = true;
12578 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012579 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012580 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012581 mCurrentBatteryLevel = level;
12582 if (mDischargePlugLevel < 0) {
12583 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012584 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012585
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012586 if (onBattery != mOnBattery) {
12587 mHistoryCur.batteryLevel = (byte)level;
12588 mHistoryCur.batteryStatus = (byte)status;
12589 mHistoryCur.batteryHealth = (byte)health;
12590 mHistoryCur.batteryPlugType = (byte)plugType;
12591 mHistoryCur.batteryTemperature = (short)temp;
12592 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012593 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12594 // Only record discharges
12595 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12596 mDischargeCounter.addCountLocked(chargeDiff);
12597 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012598 if (isScreenDoze(mScreenState)) {
12599 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12600 }
Mike Ma15313c92017-11-15 17:58:21 -080012601 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12602 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12603 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12604 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12605 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012606 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012607 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012608 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012609 } else {
12610 boolean changed = false;
12611 if (mHistoryCur.batteryLevel != level) {
12612 mHistoryCur.batteryLevel = (byte)level;
12613 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012614
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012615 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12616 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012617 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070012618 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012619 if (mHistoryCur.batteryStatus != status) {
12620 mHistoryCur.batteryStatus = (byte)status;
12621 changed = true;
12622 }
12623 if (mHistoryCur.batteryHealth != health) {
12624 mHistoryCur.batteryHealth = (byte)health;
12625 changed = true;
12626 }
12627 if (mHistoryCur.batteryPlugType != plugType) {
12628 mHistoryCur.batteryPlugType = (byte)plugType;
12629 changed = true;
12630 }
12631 if (temp >= (mHistoryCur.batteryTemperature+10)
12632 || temp <= (mHistoryCur.batteryTemperature-10)) {
12633 mHistoryCur.batteryTemperature = (short)temp;
12634 changed = true;
12635 }
12636 if (volt > (mHistoryCur.batteryVoltage+20)
12637 || volt < (mHistoryCur.batteryVoltage-20)) {
12638 mHistoryCur.batteryVoltage = (char)volt;
12639 changed = true;
12640 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012641 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12642 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012643 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12644 // Only record discharges
12645 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12646 mDischargeCounter.addCountLocked(chargeDiff);
12647 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012648 if (isScreenDoze(mScreenState)) {
12649 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12650 }
Mike Ma15313c92017-11-15 17:58:21 -080012651 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12652 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12653 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12654 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12655 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012656 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012657 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012658 changed = true;
12659 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012660 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12661 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12662 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12663 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012664 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012665 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12666 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12667 modeBits, elapsedRealtime);
12668 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12669 modeBits, elapsedRealtime);
12670 mLastDischargeStepLevel = level;
12671 mMinDischargeStepLevel = level;
12672 mInitStepMode = mCurStepMode;
12673 mModStepMode = 0;
12674 }
12675 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012676 if (level >= 90) {
12677 // If the battery level is at least 90%, always consider the device to be
12678 // charging even if it happens to go down a level.
12679 changed |= setChargingLocked(true);
12680 mLastChargeStepLevel = level;
12681 } if (!mCharging) {
12682 if (mLastChargeStepLevel < level) {
12683 // We have not reporting that we are charging, but the level has now
12684 // gone up, so consider the state to be charging.
12685 changed |= setChargingLocked(true);
12686 mLastChargeStepLevel = level;
12687 }
12688 } else {
12689 if (mLastChargeStepLevel > level) {
12690 // We had reported that the device was charging, but here we are with
12691 // power connected and the level going down. Looks like the current
12692 // power supplied isn't enough, so consider the device to now be
12693 // discharging.
12694 changed |= setChargingLocked(false);
12695 mLastChargeStepLevel = level;
12696 }
12697 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012698 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12699 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12700 modeBits, elapsedRealtime);
12701 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12702 modeBits, elapsedRealtime);
12703 mLastChargeStepLevel = level;
12704 mMaxChargeStepLevel = level;
12705 mInitStepMode = mCurStepMode;
12706 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012707 }
12708 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012709 if (changed) {
12710 addHistoryRecordLocked(elapsedRealtime, uptime);
12711 }
Evan Millarc64edde2009-04-18 12:26:32 -070012712 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012713 if (!onBattery &&
12714 (status == BatteryManager.BATTERY_STATUS_FULL ||
12715 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12716 // We don't record history while we are plugged in and fully charged
12717 // (or when battery is not present). The next time we are
12718 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012719 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012720 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012721
Jocelyn Dangc627d102017-04-14 13:15:14 -070012722 if (mMinLearnedBatteryCapacity == -1) {
12723 mMinLearnedBatteryCapacity = chargeFullUAh;
12724 } else {
12725 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012726 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012727 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012728 }
12729
Sudheer Shankac57729a2018-02-09 15:44:42 -080012730 public static boolean isOnBattery(int plugType, int status) {
12731 return plugType == BATTERY_PLUGGED_NONE && status != BatteryManager.BATTERY_STATUS_UNKNOWN;
12732 }
12733
Bookatz8c6571b2017-10-24 15:04:41 -070012734 // Inform StatsLog of setBatteryState changes.
12735 // If this is the first reporting, pass in recentPast == null.
12736 private void reportChangesToStatsLog(HistoryItem recentPast,
Tej Singh40298312018-02-16 00:15:09 -080012737 final int status, final int plugType, final int level) {
Bookatz8c6571b2017-10-24 15:04:41 -070012738
12739 if (recentPast == null || recentPast.batteryStatus != status) {
12740 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12741 }
12742 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12743 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12744 }
12745 if (recentPast == null || recentPast.batteryLevel != level) {
12746 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12747 }
Bookatz8c6571b2017-10-24 15:04:41 -070012748 }
12749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012750 public long getAwakeTimeBattery() {
12751 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12752 }
12753
12754 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012755 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012756 }
12757
12758 @Override
12759 public long computeUptime(long curTime, int which) {
12760 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012761 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012762 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012763 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012764 }
12765 return 0;
12766 }
12767
12768 @Override
12769 public long computeRealtime(long curTime, int which) {
12770 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012771 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012772 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012773 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012774 }
12775 return 0;
12776 }
12777
12778 @Override
12779 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012780 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012781 }
12782
12783 @Override
12784 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012785 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012786 }
12787
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012788 @Override
12789 public long computeBatteryScreenOffUptime(long curTime, int which) {
12790 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12791 }
12792
12793 @Override
12794 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12795 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012796 }
12797
Dianne Hackborn260c5022014-04-29 11:23:16 -070012798 private long computeTimePerLevel(long[] steps, int numSteps) {
12799 // For now we'll do a simple average across all steps.
12800 if (numSteps <= 0) {
12801 return -1;
12802 }
12803 long total = 0;
12804 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012805 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012806 }
12807 return total / numSteps;
12808 /*
12809 long[] buckets = new long[numSteps];
12810 int numBuckets = 0;
12811 int numToAverage = 4;
12812 int i = 0;
12813 while (i < numSteps) {
12814 long totalTime = 0;
12815 int num = 0;
12816 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012817 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012818 num++;
12819 }
12820 buckets[numBuckets] = totalTime / num;
12821 numBuckets++;
12822 numToAverage *= 2;
12823 i += num;
12824 }
12825 if (numBuckets < 1) {
12826 return -1;
12827 }
12828 long averageTime = buckets[numBuckets-1];
12829 for (i=numBuckets-2; i>=0; i--) {
12830 averageTime = (averageTime + buckets[i]) / 2;
12831 }
12832 return averageTime;
12833 */
12834 }
12835
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012836 @Override
12837 public long computeBatteryTimeRemaining(long curTime) {
12838 if (!mOnBattery) {
12839 return -1;
12840 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012841 /* Simple implementation just looks at the average discharge per level across the
12842 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012843 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12844 if (discharge < 2) {
12845 return -1;
12846 }
12847 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12848 if (duration < 1000*1000) {
12849 return -1;
12850 }
12851 long usPerLevel = duration/discharge;
12852 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012853 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012854 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012855 return -1;
12856 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012857 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012858 if (msPerLevel <= 0) {
12859 return -1;
12860 }
12861 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012862 }
12863
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012864 @Override
12865 public LevelStepTracker getDischargeLevelStepTracker() {
12866 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012867 }
12868
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012869 @Override
12870 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12871 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012872 }
12873
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012874 @Override
12875 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012876 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012877 // Not yet working.
12878 return -1;
12879 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012880 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012881 int curLevel = mCurrentBatteryLevel;
12882 int plugLevel = mDischargePlugLevel;
12883 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12884 return -1;
12885 }
12886 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12887 if (duration < 1000*1000) {
12888 return -1;
12889 }
12890 long usPerLevel = duration/(curLevel-plugLevel);
12891 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012892 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012893 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012894 return -1;
12895 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012896 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012897 if (msPerLevel <= 0) {
12898 return -1;
12899 }
12900 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012901 }
12902
Siddharth Raya1fd0572017-11-13 14:20:47 -080012903 /*@hide */
12904 public CellularBatteryStats getCellularBatteryStats() {
12905 CellularBatteryStats s = new CellularBatteryStats();
12906 final int which = STATS_SINCE_CHARGED;
12907 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12908 final ControllerActivityCounter counter = getModemControllerActivity();
Siddharth Rayed754702018-02-15 12:44:37 -080012909 final long sleepTimeMs = counter.getSleepTimeCounter().getCountLocked(which);
Siddharth Raya1fd0572017-11-13 14:20:47 -080012910 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12911 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12912 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12913 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12914 for (int i = 0; i < timeInRatMs.length; i++) {
12915 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12916 }
12917 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12918 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12919 timeInRxSignalStrengthLevelMs[i]
12920 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12921 }
12922 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12923 counter.getTxTimeCounters().length)];
12924 long totalTxTimeMs = 0;
12925 for (int i = 0; i < txTimeMs.length; i++) {
12926 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12927 totalTxTimeMs += txTimeMs[i];
12928 }
Siddharth Raya1fd0572017-11-13 14:20:47 -080012929 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12930 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12931 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12932 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12933 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12934 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
12935 s.setSleepTimeMs(sleepTimeMs);
12936 s.setIdleTimeMs(idleTimeMs);
12937 s.setRxTimeMs(rxTimeMs);
12938 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12939 s.setTimeInRatMs(timeInRatMs);
12940 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
12941 s.setTxTimeMs(txTimeMs);
12942 return s;
12943 }
12944
Siddharth Rayb50a6842017-12-14 15:15:28 -080012945 /*@hide */
12946 public WifiBatteryStats getWifiBatteryStats() {
12947 WifiBatteryStats s = new WifiBatteryStats();
12948 final int which = STATS_SINCE_CHARGED;
12949 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12950 final ControllerActivityCounter counter = getWifiControllerActivity();
12951 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12952 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
12953 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12954 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
12955 final long totalControllerActivityTimeMs
12956 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12957 final long sleepTimeMs
12958 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
12959 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12960 long numAppScanRequest = 0;
12961 for (int i = 0; i < mUidStats.size(); i++) {
12962 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
12963 }
12964 long[] timeInStateMs = new long[NUM_WIFI_STATES];
12965 for (int i=0; i<NUM_WIFI_STATES; i++) {
12966 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
12967 }
12968 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
12969 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12970 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
12971 }
12972 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
12973 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12974 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
12975 }
12976 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12977 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
12978 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
12979 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
12980 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
12981 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
12982 s.setSleepTimeMs(sleepTimeMs);
12983 s.setIdleTimeMs(idleTimeMs);
12984 s.setRxTimeMs(rxTimeMs);
12985 s.setTxTimeMs(txTimeMs);
12986 s.setScanTimeMs(scanTimeMs);
12987 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12988 s.setNumAppScanRequest(numAppScanRequest);
12989 s.setTimeInStateMs(timeInStateMs);
12990 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
12991 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
12992 return s;
12993 }
12994
Siddharth Ray78ccaf52017-12-23 16:16:21 -080012995 /*@hide */
12996 public GpsBatteryStats getGpsBatteryStats() {
12997 GpsBatteryStats s = new GpsBatteryStats();
12998 final int which = STATS_SINCE_CHARGED;
12999 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13000 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13001 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
13002 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
13003 for (int i=0; i<time.length; i++) {
13004 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
13005 }
13006 s.setTimeInGpsSignalQualityLevel(time);
13007 return s;
13008 }
13009
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013010 @Override
13011 public LevelStepTracker getChargeLevelStepTracker() {
13012 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013013 }
13014
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013015 @Override
13016 public LevelStepTracker getDailyChargeLevelStepTracker() {
13017 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013018 }
13019
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013020 @Override
13021 public ArrayList<PackageChange> getDailyPackageChanges() {
13022 return mDailyPackageChanges;
13023 }
13024
Joe Onoratoe1acd632016-02-23 13:25:10 -080013025 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013026 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013027 }
13028
13029 @Override
13030 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013031 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013032 }
13033
13034 @Override
13035 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013036 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013037 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070013038
The Android Open Source Project10592532009-03-18 17:39:46 -070013039 @Override
Evan Millar633a1742009-04-02 16:36:33 -070013040 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013041 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013042 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013043 }
13044 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013045
Evan Millar633a1742009-04-02 16:36:33 -070013046 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013047 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013048 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013049
The Android Open Source Project10592532009-03-18 17:39:46 -070013050 @Override
Evan Millar633a1742009-04-02 16:36:33 -070013051 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013052 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013053 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013054 }
13055 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013056
Evan Millar633a1742009-04-02 16:36:33 -070013057 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013058 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013060
Amith Yamasanie43530a2009-08-21 13:11:37 -070013061 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013062 public int getLowDischargeAmountSinceCharge() {
13063 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013064 int val = mLowDischargeAmountSinceCharge;
13065 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13066 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
13067 }
13068 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013069 }
13070 }
13071
13072 @Override
13073 public int getHighDischargeAmountSinceCharge() {
13074 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013075 int val = mHighDischargeAmountSinceCharge;
13076 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13077 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
13078 }
13079 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013080 }
13081 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013082
13083 @Override
13084 public int getDischargeAmount(int which) {
13085 int dischargeAmount = which == STATS_SINCE_CHARGED
13086 ? getHighDischargeAmountSinceCharge()
13087 : (getDischargeStartLevel() - getDischargeCurrentLevel());
13088 if (dischargeAmount < 0) {
13089 dischargeAmount = 0;
13090 }
13091 return dischargeAmount;
13092 }
13093
Mike Mac2f518a2017-09-19 16:06:03 -070013094 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013095 public int getDischargeAmountScreenOn() {
13096 synchronized(this) {
13097 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070013098 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013099 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13100 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13101 }
13102 return val;
13103 }
13104 }
13105
Mike Mac2f518a2017-09-19 16:06:03 -070013106 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013107 public int getDischargeAmountScreenOnSinceCharge() {
13108 synchronized(this) {
13109 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070013110 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013111 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13112 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13113 }
13114 return val;
13115 }
13116 }
13117
Mike Mac2f518a2017-09-19 16:06:03 -070013118 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013119 public int getDischargeAmountScreenOff() {
13120 synchronized(this) {
13121 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070013122 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013123 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13124 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13125 }
Mike Mac2f518a2017-09-19 16:06:03 -070013126 // For backward compatibility, doze discharge is counted into screen off.
13127 return val + getDischargeAmountScreenDoze();
13128 }
13129 }
13130
13131 @Override
13132 public int getDischargeAmountScreenOffSinceCharge() {
13133 synchronized(this) {
13134 int val = mDischargeAmountScreenOffSinceCharge;
13135 if (mOnBattery && isScreenOff(mScreenState)
13136 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13137 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13138 }
13139 // For backward compatibility, doze discharge is counted into screen off.
13140 return val + getDischargeAmountScreenDozeSinceCharge();
13141 }
13142 }
13143
13144 @Override
13145 public int getDischargeAmountScreenDoze() {
13146 synchronized(this) {
13147 int val = mDischargeAmountScreenDoze;
13148 if (mOnBattery && isScreenDoze(mScreenState)
13149 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13150 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
13151 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013152 return val;
13153 }
13154 }
13155
Mike Mac2f518a2017-09-19 16:06:03 -070013156 @Override
13157 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013158 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070013159 int val = mDischargeAmountScreenDozeSinceCharge;
13160 if (mOnBattery && isScreenDoze(mScreenState)
13161 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13162 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013163 }
13164 return val;
13165 }
13166 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013168 /**
13169 * Retrieve the statistics object for a particular uid, creating if needed.
13170 */
13171 public Uid getUidStatsLocked(int uid) {
13172 Uid u = mUidStats.get(uid);
13173 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080013174 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013175 mUidStats.put(uid, u);
13176 }
13177 return u;
13178 }
13179
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013180 /**
13181 * Retrieve the statistics object for a particular uid. Returns null if the object is not
13182 * available.
13183 */
13184 public Uid getAvailableUidStatsLocked(int uid) {
13185 Uid u = mUidStats.get(uid);
13186 return u;
13187 }
13188
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013189 public void onCleanupUserLocked(int userId) {
13190 final int firstUidForUser = UserHandle.getUid(userId, 0);
13191 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
Mike Ma234d1822018-03-13 18:53:21 -070013192 mPendingRemovedUids.add(
13193 new UidToRemove(firstUidForUser, lastUidForUser, mClocks.elapsedRealtime()));
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013194 }
13195
13196 public void onUserRemovedLocked(int userId) {
13197 final int firstUidForUser = UserHandle.getUid(userId, 0);
13198 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13199 mUidStats.put(firstUidForUser, null);
13200 mUidStats.put(lastUidForUser, null);
13201 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
13202 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
13203 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
13204 }
13205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013206 /**
13207 * Remove the statistics object for a particular uid.
13208 */
13209 public void removeUidStatsLocked(int uid) {
13210 mUidStats.remove(uid);
Mike Ma234d1822018-03-13 18:53:21 -070013211 mPendingRemovedUids.add(new UidToRemove(uid, mClocks.elapsedRealtime()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013212 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070013213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013214 /**
13215 * Retrieve the statistics object for a particular process, creating
13216 * if needed.
13217 */
13218 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013219 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013220 Uid u = getUidStatsLocked(uid);
13221 return u.getProcessStatsLocked(name);
13222 }
13223
13224 /**
13225 * Retrieve the statistics object for a particular process, creating
13226 * if needed.
13227 */
13228 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013229 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013230 Uid u = getUidStatsLocked(uid);
13231 return u.getPackageStatsLocked(pkg);
13232 }
13233
13234 /**
13235 * Retrieve the statistics object for a particular service, creating
13236 * if needed.
13237 */
13238 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013239 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013240 Uid u = getUidStatsLocked(uid);
13241 return u.getServiceStatsLocked(pkg, name);
13242 }
13243
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013244 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013245 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013246 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013247 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013248 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013249
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013250 public boolean trackPerProcStateCpuTimes() {
13251 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
13252 }
13253
13254 public void systemServicesReady(Context context) {
13255 mConstants.startObserving(context.getContentResolver());
Mike Mafbc01fc2018-04-02 10:28:28 -070013256 registerUsbStateReceiver(context);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013257 }
13258
13259 @VisibleForTesting
13260 public final class Constants extends ContentObserver {
13261 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
13262 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080013263 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
13264 = "track_cpu_active_cluster_time";
Sudheer Shankac20379e2018-02-15 00:06:21 -080013265 public static final String KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS
13266 = "proc_state_cpu_times_read_delay_ms";
Mike Ma2ab01442018-02-13 14:22:47 -080013267 public static final String KEY_KERNEL_UID_READERS_THROTTLE_TIME
13268 = "kernel_uid_readers_throttle_time";
Mike Ma234d1822018-03-13 18:53:21 -070013269 public static final String KEY_UID_REMOVE_DELAY_MS
13270 = "uid_remove_delay_ms";
Sudheer Shankae56013a2018-04-23 11:22:15 -070013271 public static final String KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13272 = "external_stats_collection_rate_limit_ms";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013273
13274 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080013275 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013276 private static final long DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS = 5_000;
Mike Ma2ab01442018-02-13 14:22:47 -080013277 private static final long DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME = 10_000;
Mike Ma234d1822018-03-13 18:53:21 -070013278 private static final long DEFAULT_UID_REMOVE_DELAY_MS = 5L * 60L * 1000L;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013279 private static final long DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = 600_000;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013280
13281 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013282 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013283 public long PROC_STATE_CPU_TIMES_READ_DELAY_MS = DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS;
Mike Ma2ab01442018-02-13 14:22:47 -080013284 public long KERNEL_UID_READERS_THROTTLE_TIME = DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME;
Mike Ma234d1822018-03-13 18:53:21 -070013285 public long UID_REMOVE_DELAY_MS = DEFAULT_UID_REMOVE_DELAY_MS;
Sudheer Shankae56013a2018-04-23 11:22:15 -070013286 public long EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS
13287 = DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013288
13289 private ContentResolver mResolver;
13290 private final KeyValueListParser mParser = new KeyValueListParser(',');
13291
13292 public Constants(Handler handler) {
13293 super(handler);
13294 }
13295
13296 public void startObserving(ContentResolver resolver) {
13297 mResolver = resolver;
13298 mResolver.registerContentObserver(
13299 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13300 false /* notifyForDescendants */, this);
13301 updateConstants();
13302 }
13303
13304 @Override
13305 public void onChange(boolean selfChange, Uri uri) {
13306 updateConstants();
13307 }
13308
13309 private void updateConstants() {
13310 synchronized (BatteryStatsImpl.this) {
13311 try {
13312 mParser.setString(Settings.Global.getString(mResolver,
13313 Settings.Global.BATTERY_STATS_CONSTANTS));
13314 } catch (IllegalArgumentException e) {
13315 // Failed to parse the settings string, log this and move on
13316 // with defaults.
13317 Slog.e(TAG, "Bad batterystats settings", e);
13318 }
13319
13320 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13321 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13322 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013323 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13324 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013325 updateProcStateCpuTimesReadDelayMs(PROC_STATE_CPU_TIMES_READ_DELAY_MS,
13326 mParser.getLong(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS,
Mike Ma2ab01442018-02-13 14:22:47 -080013327 DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS));
13328 updateKernelUidReadersThrottleTime(KERNEL_UID_READERS_THROTTLE_TIME,
13329 mParser.getLong(KEY_KERNEL_UID_READERS_THROTTLE_TIME,
13330 DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME));
Mike Ma234d1822018-03-13 18:53:21 -070013331 updateUidRemoveDelay(
13332 mParser.getLong(KEY_UID_REMOVE_DELAY_MS, DEFAULT_UID_REMOVE_DELAY_MS));
Sudheer Shankae56013a2018-04-23 11:22:15 -070013333 EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS = mParser.getLong(
13334 KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS,
13335 DEFAULT_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013336 }
13337 }
13338
13339 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13340 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13341 if (isEnabled && !wasEnabled) {
13342 mKernelSingleUidTimeReader.markDataAsStale(true);
13343 mExternalSync.scheduleCpuSyncDueToSettingChange();
Sudheer Shankac20379e2018-02-15 00:06:21 -080013344
Mike Ma234d1822018-03-13 18:53:21 -070013345 mNumSingleUidCpuTimeReads = 0;
13346 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013347 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
13348 }
13349 }
13350
13351 private void updateProcStateCpuTimesReadDelayMs(long oldDelayMillis, long newDelayMillis) {
13352 PROC_STATE_CPU_TIMES_READ_DELAY_MS = newDelayMillis;
13353 if (oldDelayMillis != newDelayMillis) {
Mike Ma234d1822018-03-13 18:53:21 -070013354 mNumSingleUidCpuTimeReads = 0;
13355 mNumBatchedSingleUidCpuTimeReads = 0;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013356 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013357 }
13358 }
13359
Mike Ma2ab01442018-02-13 14:22:47 -080013360 private void updateKernelUidReadersThrottleTime(long oldTimeMs, long newTimeMs) {
13361 KERNEL_UID_READERS_THROTTLE_TIME = newTimeMs;
13362 if (oldTimeMs != newTimeMs) {
Mike Ma69d8b3e2018-02-23 14:51:26 -080013363 mKernelUidCpuTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
Mike Ma2ab01442018-02-13 14:22:47 -080013364 mKernelUidCpuFreqTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13365 mKernelUidCpuActiveTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13366 mKernelUidCpuClusterTimeReader
13367 .setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13368 }
13369 }
13370
Mike Ma234d1822018-03-13 18:53:21 -070013371 private void updateUidRemoveDelay(long newTimeMs) {
13372 UID_REMOVE_DELAY_MS = newTimeMs;
13373 clearPendingRemovedUids();
13374 }
13375
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013376 public void dumpLocked(PrintWriter pw) {
13377 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13378 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013379 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13380 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013381 pw.print(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS); pw.print("=");
13382 pw.println(PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma2ab01442018-02-13 14:22:47 -080013383 pw.print(KEY_KERNEL_UID_READERS_THROTTLE_TIME); pw.print("=");
13384 pw.println(KERNEL_UID_READERS_THROTTLE_TIME);
Sudheer Shankae56013a2018-04-23 11:22:15 -070013385 pw.print(KEY_EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS); pw.print("=");
13386 pw.println(EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS);
13387 }
13388 }
13389
13390 public long getExternalStatsCollectionRateLimitMs() {
13391 synchronized (this) {
13392 return mConstants.EXTERNAL_STATS_COLLECTION_RATE_LIMIT_MS;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013393 }
13394 }
13395
Andreas Gampe3f24e692018-02-05 13:24:28 -080013396 @GuardedBy("this")
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013397 public void dumpConstantsLocked(PrintWriter pw) {
13398 mConstants.dumpLocked(pw);
13399 }
13400
Mike Ma234d1822018-03-13 18:53:21 -070013401 @GuardedBy("this")
13402 public void dumpCpuStatsLocked(PrintWriter pw) {
13403 int size = mUidStats.size();
13404 pw.println("Per UID CPU user & system time in ms:");
13405 for (int i = 0; i < size; i++) {
13406 int u = mUidStats.keyAt(i);
13407 Uid uid = mUidStats.get(u);
13408 pw.print(" "); pw.print(u); pw.print(": ");
13409 pw.print(uid.getUserCpuTimeUs(STATS_SINCE_CHARGED) / 1000); pw.print(" ");
13410 pw.println(uid.getSystemCpuTimeUs(STATS_SINCE_CHARGED) / 1000);
13411 }
13412 pw.println("Per UID CPU active time in ms:");
13413 for (int i = 0; i < size; i++) {
13414 int u = mUidStats.keyAt(i);
13415 Uid uid = mUidStats.get(u);
13416 if (uid.getCpuActiveTime() > 0) {
13417 pw.print(" "); pw.print(u); pw.print(": "); pw.println(uid.getCpuActiveTime());
13418 }
13419 }
13420 pw.println("Per UID CPU cluster time in ms:");
13421 for (int i = 0; i < size; i++) {
13422 int u = mUidStats.keyAt(i);
13423 long[] times = mUidStats.get(u).getCpuClusterTimes();
13424 if (times != null) {
13425 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13426 }
13427 }
13428 pw.println("Per UID CPU frequency time in ms:");
13429 for (int i = 0; i < size; i++) {
13430 int u = mUidStats.keyAt(i);
13431 long[] times = mUidStats.get(u).getCpuFreqTimes(STATS_SINCE_CHARGED);
13432 if (times != null) {
13433 pw.print(" "); pw.print(u); pw.print(": "); pw.println(Arrays.toString(times));
13434 }
13435 }
13436 }
13437
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013438 Parcel mPendingWrite = null;
13439 final ReentrantLock mWriteLock = new ReentrantLock();
13440
13441 public void writeAsyncLocked() {
13442 writeLocked(false);
13443 }
13444
13445 public void writeSyncLocked() {
13446 writeLocked(true);
13447 }
13448
13449 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013450 if (mFile == null) {
13451 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013452 return;
13453 }
13454
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013455 if (mShuttingDown) {
13456 return;
13457 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013458
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013459 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013460 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013461 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013462
13463 if (mPendingWrite != null) {
13464 mPendingWrite.recycle();
13465 }
13466 mPendingWrite = out;
13467
13468 if (sync) {
13469 commitPendingDataToDisk();
13470 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013471 BackgroundThread.getHandler().post(new Runnable() {
13472 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013473 commitPendingDataToDisk();
13474 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013475 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013476 }
13477 }
13478
13479 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013480 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013481 synchronized (this) {
13482 next = mPendingWrite;
13483 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013484 if (next == null) {
13485 return;
13486 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013487 }
13488
Amith Yamasanid2450862017-02-07 15:58:24 -080013489 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013490 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013491 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013492 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013493 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013494 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013495 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013496 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013497 mFile.commit();
Dianne Hackborne17b4452018-01-10 13:15:40 -080013498 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13499 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013500 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013501 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013502 mFile.rollback();
13503 } finally {
13504 next.recycle();
13505 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013507 }
13508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013509 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013510 if (mDailyFile != null) {
13511 readDailyStatsLocked();
13512 }
13513
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013514 if (mFile == null) {
13515 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013516 return;
13517 }
13518
13519 mUidStats.clear();
13520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013521 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013522 File file = mFile.chooseForRead();
13523 if (!file.exists()) {
13524 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013525 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013526 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013527
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013528 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013529 Parcel in = Parcel.obtain();
13530 in.unmarshall(raw, 0, raw.length);
13531 in.setDataPosition(0);
13532 stream.close();
13533
13534 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013535 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013536 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013537 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013538 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013539
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013540 mEndPlatformVersion = Build.ID;
13541
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013542 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013543 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013544 final long elapsedRealtime = mClocks.elapsedRealtime();
13545 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013546 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013547 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013548 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000013549 addHistoryBufferLocked(elapsedRealtime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013550 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013551 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013552
13553 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013554 }
13555
13556 public int describeContents() {
13557 return 0;
13558 }
13559
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013560 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013561 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013562
13563 mHistoryBuffer.setDataSize(0);
13564 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013565 mHistoryTagPool.clear();
13566 mNextHistoryTagIdx = 0;
13567 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013568
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013569 int numTags = in.readInt();
13570 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013571 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013572 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013573 if (str == null) {
13574 throw new ParcelFormatException("null history tag string");
13575 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013576 int uid = in.readInt();
13577 HistoryTag tag = new HistoryTag();
13578 tag.string = str;
13579 tag.uid = uid;
13580 tag.poolIdx = idx;
13581 mHistoryTagPool.put(tag, idx);
13582 if (idx >= mNextHistoryTagIdx) {
13583 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013584 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013585 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013586 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013587
13588 int bufSize = in.readInt();
13589 int curPos = in.dataPosition();
13590 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013591 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13592 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013593 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013594 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13595 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013596 } else {
13597 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13598 + " bytes at " + curPos);
13599 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13600 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013601 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013602
Dianne Hackbornae384452011-06-28 12:33:48 -070013603 if (andOldHistory) {
13604 readOldHistory(in);
13605 }
13606
13607 if (DEBUG_HISTORY) {
13608 StringBuilder sb = new StringBuilder(128);
13609 sb.append("****************** OLD mHistoryBaseTime: ");
13610 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13611 Slog.i(TAG, sb.toString());
13612 }
13613 mHistoryBaseTime = historyBaseTime;
13614 if (DEBUG_HISTORY) {
13615 StringBuilder sb = new StringBuilder(128);
13616 sb.append("****************** NEW mHistoryBaseTime: ");
13617 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13618 Slog.i(TAG, sb.toString());
13619 }
13620
13621 // We are just arbitrarily going to insert 1 minute from the sample of
13622 // the last run until samples in this run.
13623 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013624 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013625 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013626 if (DEBUG_HISTORY) {
13627 StringBuilder sb = new StringBuilder(128);
13628 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13629 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13630 Slog.i(TAG, sb.toString());
13631 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013632 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013633 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013634
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013635 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013636 if (!USE_OLD_HISTORY) {
13637 return;
13638 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013639 mHistory = mHistoryEnd = mHistoryCache = null;
13640 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013641 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013642 HistoryItem rec = new HistoryItem(time, in);
13643 addHistoryRecordLocked(rec);
13644 }
13645 }
13646
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013647 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013648 if (DEBUG_HISTORY) {
13649 StringBuilder sb = new StringBuilder(128);
13650 sb.append("****************** WRITING mHistoryBaseTime: ");
13651 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013652 sb.append(" mLastHistoryElapsedRealtime: ");
13653 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013654 Slog.i(TAG, sb.toString());
13655 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013656 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013657 if (!inclData) {
13658 out.writeInt(0);
13659 out.writeInt(0);
13660 return;
13661 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013662 out.writeInt(mHistoryTagPool.size());
13663 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13664 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013665 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013666 out.writeString(tag.string);
13667 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013668 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013669 out.writeInt(mHistoryBuffer.dataSize());
13670 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13671 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13672 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013673
13674 if (andOldHistory) {
13675 writeOldHistory(out);
13676 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013677 }
13678
13679 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013680 if (!USE_OLD_HISTORY) {
13681 return;
13682 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013683 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013684 while (rec != null) {
13685 if (rec.time >= 0) rec.writeToParcel(out, 0);
13686 rec = rec.next;
13687 }
13688 out.writeLong(-1);
13689 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013690
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013691 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013692 final int version = in.readInt();
13693 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013694 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013695 + ", expected " + VERSION + "; erasing old stats");
13696 return;
13697 }
13698
Dianne Hackbornae384452011-06-28 12:33:48 -070013699 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013701 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013702 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013703 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013704 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013705 mStartPlatformVersion = in.readString();
13706 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013707 mOnBatteryTimeBase.readSummaryFromParcel(in);
13708 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013709 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013710 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013711 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013712 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013713 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013714 mMinLearnedBatteryCapacity = in.readInt();
13715 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013716 mLowDischargeAmountSinceCharge = in.readInt();
13717 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013718 mDischargeAmountScreenOnSinceCharge = in.readInt();
13719 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013720 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013721 mDischargeStepTracker.readFromParcel(in);
13722 mChargeStepTracker.readFromParcel(in);
13723 mDailyDischargeStepTracker.readFromParcel(in);
13724 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013725 mDischargeCounter.readSummaryFromParcelLocked(in);
13726 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013727 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013728 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13729 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013730 int NPKG = in.readInt();
13731 if (NPKG > 0) {
13732 mDailyPackageChanges = new ArrayList<>(NPKG);
13733 while (NPKG > 0) {
13734 NPKG--;
13735 PackageChange pc = new PackageChange();
13736 pc.mPackageName = in.readString();
13737 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013738 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013739 mDailyPackageChanges.add(pc);
13740 }
13741 } else {
13742 mDailyPackageChanges = null;
13743 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013744 mDailyStartTime = in.readLong();
13745 mNextMinDailyDeadline = in.readLong();
13746 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013748 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013749
Jeff Browne95c3cd2014-05-02 16:59:26 -070013750 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013751 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013752 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013753 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13754 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13755 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013756 mInteractive = false;
13757 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013758 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013759 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013760 mLongestLightIdleTime = in.readLong();
13761 mLongestFullIdleTime = in.readLong();
13762 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13763 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13764 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013765 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013766 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013767 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013768 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13769 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013770 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013771 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13772 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13773 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013774 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013775 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13776 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013777 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013778 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013779 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013780 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013781 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013782 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13783 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013784 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013785 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013786 mWifiOn = false;
13787 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013788 mGlobalWifiRunning = false;
13789 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013790 for (int i=0; i<NUM_WIFI_STATES; i++) {
13791 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13792 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013793 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13794 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13795 }
13796 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13797 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13798 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013799 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13800 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013801 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13802 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13803 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013804 mBluetoothActivity.readSummaryFromParcel(in);
13805 mModemActivity.readSummaryFromParcel(in);
13806 mHasWifiReporting = in.readInt() != 0;
13807 mHasBluetoothReporting = in.readInt() != 0;
13808 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013809
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013810 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013811 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013812 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013813 mCameraOnNesting = 0;
13814 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013815 mBluetoothScanNesting = 0;
13816 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080013817 mIsCellularTxPowerHigh = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013818
Bookatz50df7112017-08-04 14:53:26 -070013819 int NRPMS = in.readInt();
13820 if (NRPMS > 10000) {
13821 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13822 }
13823 for (int irpm = 0; irpm < NRPMS; irpm++) {
13824 if (in.readInt() != 0) {
13825 String rpmName = in.readString();
13826 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13827 }
13828 }
13829 int NSORPMS = in.readInt();
13830 if (NSORPMS > 10000) {
13831 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13832 }
13833 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13834 if (in.readInt() != 0) {
13835 String rpmName = in.readString();
13836 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13837 }
13838 }
13839
Evan Millarc64edde2009-04-18 12:26:32 -070013840 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013841 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013842 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013843 }
Evan Millarc64edde2009-04-18 12:26:32 -070013844 for (int ikw = 0; ikw < NKW; ikw++) {
13845 if (in.readInt() != 0) {
13846 String kwltName = in.readString();
13847 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13848 }
13849 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013850
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013851 int NWR = in.readInt();
13852 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013853 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013854 }
13855 for (int iwr = 0; iwr < NWR; iwr++) {
13856 if (in.readInt() != 0) {
13857 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013858 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013859 }
13860 }
13861
James Carr3a226052016-07-01 14:49:52 -070013862 int NMS = in.readInt();
13863 for (int ims = 0; ims < NMS; ims++) {
13864 if (in.readInt() != 0) {
13865 long kmstName = in.readLong();
13866 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13867 }
13868 }
13869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013870 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013871 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013872 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013874 for (int iu = 0; iu < NU; iu++) {
13875 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013876 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013877 mUidStats.put(uid, u);
13878
Bookatz867c0d72017-03-07 18:23:42 -080013879 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013880 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013881
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013882 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013883 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013884 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013885 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013886 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013887 if (in.readInt() != 0) {
13888 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13889 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013890 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013891 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013892 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013893 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013894 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13895 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13896 if (in.readInt() != 0) {
13897 u.makeWifiBatchedScanBin(i, null);
13898 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13899 }
13900 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013901 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013902 if (in.readInt() != 0) {
13903 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13904 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013905 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013906 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013907 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013908 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013909 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13910 }
13911 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013912 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13913 }
13914 if (in.readInt() != 0) {
13915 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13916 }
13917 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013918 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13919 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013920 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013921 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13922 }
13923 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013924 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13925 }
13926 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013927 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13928 }
Bookatz956f36bf2017-04-28 09:48:17 -070013929 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013930 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13931 }
13932 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013933 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13934 }
Bookatzb1f04f32017-05-19 13:57:32 -070013935 if (in.readInt() != 0) {
13936 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13937 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013938 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013939 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13940 if (in.readInt() != 0) {
13941 u.makeProcessState(i, null);
13942 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13943 }
13944 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013945 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013946 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013947 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013948
Dianne Hackborn617f8772009-03-31 15:04:46 -070013949 if (in.readInt() != 0) {
13950 if (u.mUserActivityCounters == null) {
13951 u.initUserActivityLocked();
13952 }
13953 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13954 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13955 }
13956 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013957
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013958 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013959 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013960 u.initNetworkActivityLocked();
13961 }
13962 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013963 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13964 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013965 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013966 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13967 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013968 }
13969
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013970 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13971 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13972
Adam Lesinski6832f392015-09-05 18:05:40 -070013973 if (in.readInt() != 0) {
13974 final int numClusters = in.readInt();
13975 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13976 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013977 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013978
Sudheer Shankaaf857412017-07-21 00:14:24 -070013979 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013980 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013981 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013982 final int NSB = in.readInt();
13983 if (mPowerProfile != null &&
13984 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13985 throw new ParcelFormatException("File corrupt: too many speed bins " +
13986 NSB);
13987 }
13988
Sudheer Shankaaf857412017-07-21 00:14:24 -070013989 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070013990 for (int speed = 0; speed < NSB; speed++) {
13991 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013992 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070013993 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013994 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070013995 }
13996 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070013997 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013998 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070013999 }
14000 }
14001 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014002 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014003 }
14004
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014005 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14006 in, mOnBatteryTimeBase);
14007 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14008 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070014009
14010 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
14011 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
14012
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014013 int length = in.readInt();
14014 if (length == Uid.NUM_PROCESS_STATE) {
14015 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
14016 for (int procState = 0; procState < length; ++procState) {
14017 u.mProcStateTimeMs[procState]
14018 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14019 in, mOnBatteryTimeBase);
14020 }
14021 } else {
14022 u.mProcStateTimeMs = null;
14023 }
14024 length = in.readInt();
14025 if (length == Uid.NUM_PROCESS_STATE) {
14026 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
14027 for (int procState = 0; procState < length; ++procState) {
14028 u.mProcStateScreenOffTimeMs[procState]
14029 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14030 in, mOnBatteryScreenOffTimeBase);
14031 }
14032 } else {
14033 u.mProcStateScreenOffTimeMs = null;
14034 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014035
14036 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070014037 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14038 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
14039 } else {
14040 u.mMobileRadioApWakeupCount = null;
14041 }
14042
14043 if (in.readInt() != 0) {
14044 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14045 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
14046 } else {
14047 u.mWifiRadioApWakeupCount = null;
14048 }
14049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014050 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014051 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014052 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014054 for (int iw = 0; iw < NW; iw++) {
14055 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014056 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014057 }
14058
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014059 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014060 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014061 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014062 }
14063 for (int is = 0; is < NS; is++) {
14064 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014065 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014066 }
14067
14068 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014069 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014070 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014071 }
14072 for (int ij = 0; ij < NJ; ij++) {
14073 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014074 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014075 }
14076
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014077 u.readJobCompletionsFromParcelLocked(in);
14078
Amith Yamasani977e11f2018-02-16 11:29:54 -080014079 u.mJobsDeferredEventCount.readSummaryFromParcelLocked(in);
14080 u.mJobsDeferredCount.readSummaryFromParcelLocked(in);
14081 u.mJobsFreshnessTimeMs.readSummaryFromParcelLocked(in);
14082 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14083 if (in.readInt() != 0) {
14084 u.mJobsFreshnessBuckets[i] = new Counter(u.mBsi.mOnBatteryTimeBase);
14085 u.mJobsFreshnessBuckets[i].readSummaryFromParcelLocked(in);
14086 }
14087 }
14088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014089 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014090 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014091 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014093 for (int is = 0; is < NP; is++) {
14094 int seNumber = in.readInt();
14095 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080014096 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014097 }
14098 }
14099
14100 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014101 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014102 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014103 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014104 for (int ip = 0; ip < NP; ip++) {
14105 String procName = in.readString();
14106 Uid.Proc p = u.getProcessStatsLocked(procName);
14107 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014108 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014109 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014110 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014111 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
14112 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014113 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014114 }
14115
14116 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014117 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014118 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014120 for (int ip = 0; ip < NP; ip++) {
14121 String pkgName = in.readString();
14122 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014123 final int NWA = in.readInt();
14124 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014125 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014126 }
14127 p.mWakeupAlarms.clear();
14128 for (int iwa=0; iwa<NWA; iwa++) {
14129 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070014130 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014131 c.readSummaryFromParcelLocked(in);
14132 p.mWakeupAlarms.put(tag, c);
14133 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014134 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014135 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014136 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014138 for (int is = 0; is < NS; is++) {
14139 String servName = in.readString();
14140 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
14141 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014142 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014143 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014144 }
14145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014146 }
14147 }
14148
14149 /**
14150 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
14151 * disk. This format does not allow a lossless round-trip.
14152 *
14153 * @param out the Parcel to be written to.
14154 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014155 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014156 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014157
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014158 // Pull the clock time. This may update the time and make a new history entry
14159 // if we had originally pulled a time before the RTC was set.
14160 long startClockTime = getStartClockTime();
14161
Joe Onoratoabded112016-02-08 16:49:39 -080014162 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
14163 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014164
14165 out.writeInt(VERSION);
14166
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014167 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014169 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014170 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014171 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014172 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014173 out.writeString(mStartPlatformVersion);
14174 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014175 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
14176 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014177 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014178 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014179 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014180 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014181 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014182 out.writeInt(mMinLearnedBatteryCapacity);
14183 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080014184 out.writeInt(getLowDischargeAmountSinceCharge());
14185 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014186 out.writeInt(getDischargeAmountScreenOnSinceCharge());
14187 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070014188 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014189 mDischargeStepTracker.writeToParcel(out);
14190 mChargeStepTracker.writeToParcel(out);
14191 mDailyDischargeStepTracker.writeToParcel(out);
14192 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070014193 mDischargeCounter.writeSummaryFromParcelLocked(out);
14194 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014195 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080014196 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
14197 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014198 if (mDailyPackageChanges != null) {
14199 final int NPKG = mDailyPackageChanges.size();
14200 out.writeInt(NPKG);
14201 for (int i=0; i<NPKG; i++) {
14202 PackageChange pc = mDailyPackageChanges.get(i);
14203 out.writeString(pc.mPackageName);
14204 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070014205 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014206 }
14207 } else {
14208 out.writeInt(0);
14209 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014210 out.writeLong(mDailyStartTime);
14211 out.writeLong(mNextMinDailyDeadline);
14212 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014213
14214 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070014215 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014216 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014217 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014218 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014219 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014220 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014221 out.writeLong(mLongestLightIdleTime);
14222 out.writeLong(mLongestFullIdleTime);
14223 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14224 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14225 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014226 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014227 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080014228 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014229 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014230 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014231 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014232 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014233 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014234 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014235 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014236 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14237 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014238 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014239 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14240 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014241 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014242 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
14243 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014244 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014245 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14246 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014247 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014248 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014249 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014250 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14251 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14252 }
14253 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14254 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14255 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014256 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14257 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014258 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14259 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14260 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014261 mBluetoothActivity.writeSummaryToParcel(out);
14262 mModemActivity.writeSummaryToParcel(out);
14263 out.writeInt(mHasWifiReporting ? 1 : 0);
14264 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14265 out.writeInt(mHasModemReporting ? 1 : 0);
14266
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014267 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014268 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014269 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014270 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014271
Bookatz50df7112017-08-04 14:53:26 -070014272 out.writeInt(mRpmStats.size());
14273 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14274 Timer rpmt = ent.getValue();
14275 if (rpmt != null) {
14276 out.writeInt(1);
14277 out.writeString(ent.getKey());
14278 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14279 } else {
14280 out.writeInt(0);
14281 }
14282 }
14283 out.writeInt(mScreenOffRpmStats.size());
14284 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14285 Timer rpmt = ent.getValue();
14286 if (rpmt != null) {
14287 out.writeInt(1);
14288 out.writeString(ent.getKey());
14289 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14290 } else {
14291 out.writeInt(0);
14292 }
14293 }
14294
Evan Millarc64edde2009-04-18 12:26:32 -070014295 out.writeInt(mKernelWakelockStats.size());
14296 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14297 Timer kwlt = ent.getValue();
14298 if (kwlt != null) {
14299 out.writeInt(1);
14300 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014301 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14302 } else {
14303 out.writeInt(0);
14304 }
14305 }
14306
14307 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014308 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14309 SamplingTimer timer = ent.getValue();
14310 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014311 out.writeInt(1);
14312 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014313 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014314 } else {
14315 out.writeInt(0);
14316 }
14317 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014318
James Carr3a226052016-07-01 14:49:52 -070014319 out.writeInt(mKernelMemoryStats.size());
14320 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14321 Timer kmt = mKernelMemoryStats.valueAt(i);
14322 if (kmt != null) {
14323 out.writeInt(1);
14324 out.writeLong(mKernelMemoryStats.keyAt(i));
14325 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14326 } else {
14327 out.writeInt(0);
14328 }
14329 }
14330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014331 final int NU = mUidStats.size();
14332 out.writeInt(NU);
14333 for (int iu = 0; iu < NU; iu++) {
14334 out.writeInt(mUidStats.keyAt(iu));
14335 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014336
Bookatz867c0d72017-03-07 18:23:42 -080014337 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014338 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014339
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014340 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014341 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014342 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014343 } else {
14344 out.writeInt(0);
14345 }
14346 if (u.mFullWifiLockTimer != null) {
14347 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014348 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014349 } else {
14350 out.writeInt(0);
14351 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014352 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014353 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014354 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014355 } else {
14356 out.writeInt(0);
14357 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014358 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14359 if (u.mWifiBatchedScanTimer[i] != null) {
14360 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014361 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014362 } else {
14363 out.writeInt(0);
14364 }
14365 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014366 if (u.mWifiMulticastTimer != null) {
14367 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014368 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014369 } else {
14370 out.writeInt(0);
14371 }
14372 if (u.mAudioTurnedOnTimer != null) {
14373 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014374 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014375 } else {
14376 out.writeInt(0);
14377 }
14378 if (u.mVideoTurnedOnTimer != null) {
14379 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014380 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014381 } else {
14382 out.writeInt(0);
14383 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014384 if (u.mFlashlightTurnedOnTimer != null) {
14385 out.writeInt(1);
14386 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14387 } else {
14388 out.writeInt(0);
14389 }
14390 if (u.mCameraTurnedOnTimer != null) {
14391 out.writeInt(1);
14392 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14393 } else {
14394 out.writeInt(0);
14395 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014396 if (u.mForegroundActivityTimer != null) {
14397 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014398 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014399 } else {
14400 out.writeInt(0);
14401 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014402 if (u.mForegroundServiceTimer != null) {
14403 out.writeInt(1);
14404 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14405 } else {
14406 out.writeInt(0);
14407 }
Bookatzc8c44962017-05-11 12:12:54 -070014408 if (u.mAggregatedPartialWakelockTimer != null) {
14409 out.writeInt(1);
14410 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14411 } else {
14412 out.writeInt(0);
14413 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014414 if (u.mBluetoothScanTimer != null) {
14415 out.writeInt(1);
14416 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14417 } else {
14418 out.writeInt(0);
14419 }
Bookatzb1f04f32017-05-19 13:57:32 -070014420 if (u.mBluetoothUnoptimizedScanTimer != null) {
14421 out.writeInt(1);
14422 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14423 } else {
14424 out.writeInt(0);
14425 }
Bookatz956f36bf2017-04-28 09:48:17 -070014426 if (u.mBluetoothScanResultCounter != null) {
14427 out.writeInt(1);
14428 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14429 } else {
14430 out.writeInt(0);
14431 }
Bookatzb1f04f32017-05-19 13:57:32 -070014432 if (u.mBluetoothScanResultBgCounter != null) {
14433 out.writeInt(1);
14434 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14435 } else {
14436 out.writeInt(0);
14437 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014438 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14439 if (u.mProcessStateTimer[i] != null) {
14440 out.writeInt(1);
14441 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14442 } else {
14443 out.writeInt(0);
14444 }
14445 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014446 if (u.mVibratorOnTimer != null) {
14447 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014448 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014449 } else {
14450 out.writeInt(0);
14451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014452
Dianne Hackborn617f8772009-03-31 15:04:46 -070014453 if (u.mUserActivityCounters == null) {
14454 out.writeInt(0);
14455 } else {
14456 out.writeInt(1);
14457 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14458 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14459 }
14460 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014461
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014462 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014463 out.writeInt(0);
14464 } else {
14465 out.writeInt(1);
14466 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014467 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14468 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014469 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014470 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14471 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014472 }
14473
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014474 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14475 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14476
Sudheer Shankaaf857412017-07-21 00:14:24 -070014477 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014478 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014479 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14480 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014481 if (cpuSpeeds != null) {
14482 out.writeInt(1);
14483 out.writeInt(cpuSpeeds.length);
14484 for (LongSamplingCounter c : cpuSpeeds) {
14485 if (c != null) {
14486 out.writeInt(1);
14487 c.writeSummaryFromParcelLocked(out);
14488 } else {
14489 out.writeInt(0);
14490 }
14491 }
14492 } else {
14493 out.writeInt(0);
14494 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014495 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014496 } else {
14497 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014498 }
14499
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014500 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14501 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014502
Mike Ma3d422c32017-10-25 11:08:57 -070014503 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14504 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14505
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014506 if (u.mProcStateTimeMs != null) {
14507 out.writeInt(u.mProcStateTimeMs.length);
14508 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14509 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14510 }
14511 } else {
14512 out.writeInt(0);
14513 }
14514 if (u.mProcStateScreenOffTimeMs != null) {
14515 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14516 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14517 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14518 }
14519 } else {
14520 out.writeInt(0);
14521 }
14522
Adam Lesinski5f056f62016-07-14 16:56:08 -070014523 if (u.mMobileRadioApWakeupCount != null) {
14524 out.writeInt(1);
14525 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14526 } else {
14527 out.writeInt(0);
14528 }
14529
14530 if (u.mWifiRadioApWakeupCount != null) {
14531 out.writeInt(1);
14532 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14533 } else {
14534 out.writeInt(0);
14535 }
14536
Dianne Hackbornd953c532014-08-16 18:17:38 -070014537 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14538 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014539 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014540 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014541 out.writeString(wakeStats.keyAt(iw));
14542 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014543 if (wl.mTimerFull != null) {
14544 out.writeInt(1);
14545 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14546 } else {
14547 out.writeInt(0);
14548 }
14549 if (wl.mTimerPartial != null) {
14550 out.writeInt(1);
14551 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14552 } else {
14553 out.writeInt(0);
14554 }
14555 if (wl.mTimerWindow != null) {
14556 out.writeInt(1);
14557 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14558 } else {
14559 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014560 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014561 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014562 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014563 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014564 } else {
14565 out.writeInt(0);
14566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014567 }
14568
Bookatz2bffb5b2017-04-13 11:59:33 -070014569 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014570 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014571 out.writeInt(NS);
14572 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014573 out.writeString(syncStats.keyAt(is));
14574 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014575 }
14576
Bookatzaa4594a2017-03-24 12:39:56 -070014577 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014578 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014579 out.writeInt(NJ);
14580 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014581 out.writeString(jobStats.keyAt(ij));
14582 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014583 }
14584
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014585 u.writeJobCompletionsToParcelLocked(out);
14586
Amith Yamasani977e11f2018-02-16 11:29:54 -080014587 u.mJobsDeferredEventCount.writeSummaryFromParcelLocked(out);
14588 u.mJobsDeferredCount.writeSummaryFromParcelLocked(out);
14589 u.mJobsFreshnessTimeMs.writeSummaryFromParcelLocked(out);
14590 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14591 if (u.mJobsFreshnessBuckets[i] != null) {
Adam Lesinski14082082018-02-23 12:35:55 -080014592 out.writeInt(1);
Amith Yamasani977e11f2018-02-16 11:29:54 -080014593 u.mJobsFreshnessBuckets[i].writeSummaryFromParcelLocked(out);
14594 } else {
14595 out.writeInt(0);
14596 }
14597 }
14598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014599 int NSE = u.mSensorStats.size();
14600 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014601 for (int ise=0; ise<NSE; ise++) {
14602 out.writeInt(u.mSensorStats.keyAt(ise));
14603 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14604 if (se.mTimer != null) {
14605 out.writeInt(1);
14606 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14607 } else {
14608 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014609 }
14610 }
14611
14612 int NP = u.mProcessStats.size();
14613 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014614 for (int ip=0; ip<NP; ip++) {
14615 out.writeString(u.mProcessStats.keyAt(ip));
14616 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14617 out.writeLong(ps.mUserTime);
14618 out.writeLong(ps.mSystemTime);
14619 out.writeLong(ps.mForegroundTime);
14620 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014621 out.writeInt(ps.mNumCrashes);
14622 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014623 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014624 }
14625
14626 NP = u.mPackageStats.size();
14627 out.writeInt(NP);
14628 if (NP > 0) {
14629 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14630 : u.mPackageStats.entrySet()) {
14631 out.writeString(ent.getKey());
14632 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014633 final int NWA = ps.mWakeupAlarms.size();
14634 out.writeInt(NWA);
14635 for (int iwa=0; iwa<NWA; iwa++) {
14636 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14637 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14638 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014639 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014640 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014641 for (int is=0; is<NS; is++) {
14642 out.writeString(ps.mServiceStats.keyAt(is));
14643 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14644 long time = ss.getStartTimeToNowLocked(
14645 mOnBatteryTimeBase.getUptime(NOW_SYS));
14646 out.writeLong(time);
14647 out.writeInt(ss.mStarts);
14648 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014649 }
14650 }
14651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014652 }
14653 }
14654
14655 public void readFromParcel(Parcel in) {
14656 readFromParcelLocked(in);
14657 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014659 void readFromParcelLocked(Parcel in) {
14660 int magic = in.readInt();
14661 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014662 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014663 }
14664
Dianne Hackbornae384452011-06-28 12:33:48 -070014665 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014667 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014668 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014669 mStartPlatformVersion = in.readString();
14670 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014671 mUptime = in.readLong();
14672 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014673 mRealtime = in.readLong();
14674 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014675 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014676 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014677 mMinLearnedBatteryCapacity = in.readInt();
14678 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014679 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014680 mOnBatteryTimeBase.readFromParcel(in);
14681 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14682
Jeff Browne95c3cd2014-05-02 16:59:26 -070014683 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014684 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014685 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014686 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014687 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14688 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014689 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014690 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014691 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014692 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014693 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14694 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014695 mLongestLightIdleTime = in.readLong();
14696 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014697 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14698 mOnBatteryTimeBase, in);
14699 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14700 mOnBatteryTimeBase, in);
14701 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14702 mOnBatteryTimeBase, in);
14703 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14704 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014705 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014706 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014707 null, mOnBatteryTimeBase, in);
14708 }
Joe Onoratoabded112016-02-08 16:49:39 -080014709 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14710 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014711 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014712 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014713 null, mOnBatteryTimeBase, in);
14714 }
14715 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14716 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14717 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14718 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014719 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014720 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14721 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014722 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014723 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014724 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014725 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14726 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014727 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14728 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014729 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014730 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014731 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014732 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014733 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14734 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014735 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014736 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014737 null, mOnBatteryTimeBase, in);
14738 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014739 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014740 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014741 null, mOnBatteryTimeBase, in);
14742 }
14743 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014744 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014745 null, mOnBatteryTimeBase, in);
14746 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014747 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14748 mOnBatteryTimeBase, in);
14749 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14750 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014751 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14752 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14753 null, mOnBatteryTimeBase, in);
14754 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014755 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14756 NUM_BT_TX_LEVELS, in);
14757 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14758 ModemActivityInfo.TX_POWER_LEVELS, in);
14759 mHasWifiReporting = in.readInt() != 0;
14760 mHasBluetoothReporting = in.readInt() != 0;
14761 mHasModemReporting = in.readInt() != 0;
14762
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014763 mNumConnectivityChange = in.readInt();
14764 mLoadedNumConnectivityChange = in.readInt();
14765 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014766 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014767 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014768 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014769 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014770 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014771 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014772 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014773 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014774 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014775 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080014776 mIsCellularTxPowerHigh = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014777 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014778 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014779 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014780 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014781 mLowDischargeAmountSinceCharge = in.readInt();
14782 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014783 mDischargeAmountScreenOn = in.readInt();
14784 mDischargeAmountScreenOnSinceCharge = in.readInt();
14785 mDischargeAmountScreenOff = in.readInt();
14786 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014787 mDischargeAmountScreenDoze = in.readInt();
14788 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014789 mDischargeStepTracker.readFromParcel(in);
14790 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014791 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014792 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14793 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014794 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14795 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014796 mLastWriteTime = in.readLong();
14797
Bookatz50df7112017-08-04 14:53:26 -070014798 mRpmStats.clear();
14799 int NRPMS = in.readInt();
14800 for (int irpm = 0; irpm < NRPMS; irpm++) {
14801 if (in.readInt() != 0) {
14802 String rpmName = in.readString();
14803 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14804 mRpmStats.put(rpmName, rpmt);
14805 }
14806 }
14807 mScreenOffRpmStats.clear();
14808 int NSORPMS = in.readInt();
14809 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14810 if (in.readInt() != 0) {
14811 String rpmName = in.readString();
14812 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14813 mScreenOffRpmStats.put(rpmName, rpmt);
14814 }
14815 }
14816
Evan Millarc64edde2009-04-18 12:26:32 -070014817 mKernelWakelockStats.clear();
14818 int NKW = in.readInt();
14819 for (int ikw = 0; ikw < NKW; ikw++) {
14820 if (in.readInt() != 0) {
14821 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014822 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014823 mKernelWakelockStats.put(wakelockName, kwlt);
14824 }
14825 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014826
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014827 mWakeupReasonStats.clear();
14828 int NWR = in.readInt();
14829 for (int iwr = 0; iwr < NWR; iwr++) {
14830 if (in.readInt() != 0) {
14831 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014832 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014833 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014834 }
14835 }
14836
James Carr3a226052016-07-01 14:49:52 -070014837 mKernelMemoryStats.clear();
14838 int nmt = in.readInt();
14839 for (int imt = 0; imt < nmt; imt++) {
14840 if (in.readInt() != 0) {
14841 Long bucket = in.readLong();
14842 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14843 mKernelMemoryStats.put(bucket, kmt);
14844 }
14845 }
14846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014847 mPartialTimers.clear();
14848 mFullTimers.clear();
14849 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014850 mWifiRunningTimers.clear();
14851 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014852 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014853 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014854 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014855 mAudioTurnedOnTimers.clear();
14856 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014857 mFlashlightTurnedOnTimers.clear();
14858 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014859
14860 int numUids = in.readInt();
14861 mUidStats.clear();
14862 for (int i = 0; i < numUids; i++) {
14863 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014864 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014865 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014866 mUidStats.append(uid, u);
14867 }
14868 }
14869
14870 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014871 writeToParcelLocked(out, true, flags);
14872 }
14873
14874 public void writeToParcelWithoutUids(Parcel out, int flags) {
14875 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014876 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014877
14878 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014879 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014880 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014881 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014882
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014883 // Pull the clock time. This may update the time and make a new history entry
14884 // if we had originally pulled a time before the RTC was set.
14885 long startClockTime = getStartClockTime();
14886
Joe Onoratoabded112016-02-08 16:49:39 -080014887 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14888 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014889 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14890 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014892 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014893
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014894 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014896 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014897 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014898 out.writeString(mStartPlatformVersion);
14899 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014900 out.writeLong(mUptime);
14901 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014902 out.writeLong(mRealtime);
14903 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014904 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014905 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014906 out.writeInt(mMinLearnedBatteryCapacity);
14907 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014908 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14909 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14910
14911 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014912 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014913 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14914 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14915 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014916 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014917 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014918 out.writeLong(mLongestLightIdleTime);
14919 out.writeLong(mLongestFullIdleTime);
14920 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14921 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14922 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014923 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014924 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14925 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14926 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14927 }
14928 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14929 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14930 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14931 }
14932 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14933 mNetworkByteActivityCounters[i].writeToParcel(out);
14934 mNetworkPacketActivityCounters[i].writeToParcel(out);
14935 }
14936 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14937 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014938 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014939 mMobileRadioActiveUnknownTime.writeToParcel(out);
14940 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014941 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014942 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14943 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14944 for (int i=0; i<NUM_WIFI_STATES; i++) {
14945 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14946 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014947 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14948 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14949 }
14950 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14951 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14952 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014953 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
14954 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014955 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14956 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
14957 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014958 mBluetoothActivity.writeToParcel(out, 0);
14959 mModemActivity.writeToParcel(out, 0);
14960 out.writeInt(mHasWifiReporting ? 1 : 0);
14961 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14962 out.writeInt(mHasModemReporting ? 1 : 0);
14963
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014964 out.writeInt(mNumConnectivityChange);
14965 out.writeInt(mLoadedNumConnectivityChange);
14966 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014967 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014968 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014969 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014970 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014971 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014972 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014973 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014974 out.writeInt(mLowDischargeAmountSinceCharge);
14975 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014976 out.writeInt(mDischargeAmountScreenOn);
14977 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14978 out.writeInt(mDischargeAmountScreenOff);
14979 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014980 out.writeInt(mDischargeAmountScreenDoze);
14981 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014982 mDischargeStepTracker.writeToParcel(out);
14983 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014984 mDischargeCounter.writeToParcel(out);
14985 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014986 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080014987 mDischargeLightDozeCounter.writeToParcel(out);
14988 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014989 out.writeLong(mLastWriteTime);
14990
Bookatz50df7112017-08-04 14:53:26 -070014991 out.writeInt(mRpmStats.size());
14992 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14993 SamplingTimer rpmt = ent.getValue();
14994 if (rpmt != null) {
14995 out.writeInt(1);
14996 out.writeString(ent.getKey());
14997 rpmt.writeToParcel(out, uSecRealtime);
14998 } else {
14999 out.writeInt(0);
15000 }
15001 }
15002 out.writeInt(mScreenOffRpmStats.size());
15003 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
15004 SamplingTimer rpmt = ent.getValue();
15005 if (rpmt != null) {
15006 out.writeInt(1);
15007 out.writeString(ent.getKey());
15008 rpmt.writeToParcel(out, uSecRealtime);
15009 } else {
15010 out.writeInt(0);
15011 }
15012 }
15013
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015014 if (inclUids) {
15015 out.writeInt(mKernelWakelockStats.size());
15016 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
15017 SamplingTimer kwlt = ent.getValue();
15018 if (kwlt != null) {
15019 out.writeInt(1);
15020 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015021 kwlt.writeToParcel(out, uSecRealtime);
15022 } else {
15023 out.writeInt(0);
15024 }
15025 }
15026 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015027 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
15028 SamplingTimer timer = ent.getValue();
15029 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015030 out.writeInt(1);
15031 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015032 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015033 } else {
15034 out.writeInt(0);
15035 }
Evan Millarc64edde2009-04-18 12:26:32 -070015036 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015037 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070015038 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015039 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070015040 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070015041
James Carr3a226052016-07-01 14:49:52 -070015042 out.writeInt(mKernelMemoryStats.size());
15043 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
15044 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
15045 if (kmt != null) {
15046 out.writeInt(1);
15047 out.writeLong(mKernelMemoryStats.keyAt(i));
15048 kmt.writeToParcel(out, uSecRealtime);
15049 } else {
15050 out.writeInt(0);
15051 }
15052 }
15053
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015054 if (inclUids) {
15055 int size = mUidStats.size();
15056 out.writeInt(size);
15057 for (int i = 0; i < size; i++) {
15058 out.writeInt(mUidStats.keyAt(i));
15059 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015060
Bookatz867c0d72017-03-07 18:23:42 -080015061 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015062 }
15063 } else {
15064 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015065 }
15066 }
15067
15068 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
15069 new Parcelable.Creator<BatteryStatsImpl>() {
15070 public BatteryStatsImpl createFromParcel(Parcel in) {
15071 return new BatteryStatsImpl(in);
15072 }
15073
15074 public BatteryStatsImpl[] newArray(int size) {
15075 return new BatteryStatsImpl[size];
15076 }
15077 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070015078
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015079 public void prepareForDumpLocked() {
15080 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080015081 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070015082
15083 // Pull the clock time. This may update the time and make a new history entry
15084 // if we had originally pulled a time before the RTC was set.
15085 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015086 }
15087
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015088 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015089 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015090 pw.println("mOnBatteryTimeBase:");
15091 mOnBatteryTimeBase.dump(pw, " ");
15092 pw.println("mOnBatteryScreenOffTimeBase:");
15093 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015094 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070015095 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015096 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070015097 pr.println("*** Screen doze timer:");
15098 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015099 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015100 pr.println("*** Screen brightness #" + i + ":");
15101 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015102 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015103 pr.println("*** Interactive timer:");
15104 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015105 pr.println("*** Power save mode timer:");
15106 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015107 pr.println("*** Device idle mode light timer:");
15108 mDeviceIdleModeLightTimer.logState(pr, " ");
15109 pr.println("*** Device idle mode full timer:");
15110 mDeviceIdleModeFullTimer.logState(pr, " ");
15111 pr.println("*** Device light idling timer:");
15112 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015113 pr.println("*** Device idling timer:");
15114 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015115 pr.println("*** Phone timer:");
15116 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080015117 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070015118 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015119 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015120 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070015121 pr.println("*** Signal scanning :");
15122 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015123 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015124 pr.println("*** Data connection type #" + i + ":");
15125 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015126 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015127 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080015128 pr.println("*** Mobile network active timer:");
15129 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015130 pr.println("*** Mobile network active adjusted timer:");
15131 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015132 pr.println("*** Wifi Multicast WakeLock Timer:");
15133 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070015134 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015135 pr.println("*** Wifi timer:");
15136 mWifiOnTimer.logState(pr, " ");
15137 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070015138 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080015139 for (int i=0; i<NUM_WIFI_STATES; i++) {
15140 pr.println("*** Wifi state #" + i + ":");
15141 mWifiStateTimer[i].logState(pr, " ");
15142 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015143 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15144 pr.println("*** Wifi suppl state #" + i + ":");
15145 mWifiSupplStateTimer[i].logState(pr, " ");
15146 }
15147 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15148 pr.println("*** Wifi signal strength #" + i + ":");
15149 mWifiSignalStrengthsTimer[i].logState(pr, " ");
15150 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015151 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15152 pr.println("*** GPS signal quality #" + i + ":");
15153 mGpsSignalQualityTimer[i].logState(pr, " ");
15154 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015155 pr.println("*** Flashlight timer:");
15156 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015157 pr.println("*** Camera timer:");
15158 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015159 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015160 super.dumpLocked(context, pw, flags, reqUid, histStart);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015161 pw.print("Total cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015162 pw.println(mNumSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015163 pw.print("Batched cpu time reads: ");
Mike Ma234d1822018-03-13 18:53:21 -070015164 pw.println(mNumBatchedSingleUidCpuTimeReads);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015165 pw.print("Batching Duration (min): ");
15166 pw.println((mClocks.uptimeMillis() - mCpuTimeReadsTrackingStartTime) / (60 * 1000));
Mike Ma234d1822018-03-13 18:53:21 -070015167 pw.print("All UID cpu time reads since the later of device start or stats reset: ");
15168 pw.println(mNumAllUidCpuTimeReads);
15169 pw.print("UIDs removed since the later of device start or stats reset: ");
15170 pw.println(mNumUidsRemoved);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015172}