blob: ecab15fb81a5f9d84e0191d0ad1ecf446ea9f4d8 [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;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080024import android.content.ContentResolver;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080025import android.content.Context;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070026import android.content.Intent;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080027import android.database.ContentObserver;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070028import android.net.ConnectivityManager;
29import android.net.NetworkStats;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080030import android.net.Uri;
Adam Lesinski33dac552015-03-09 15:24:48 -070031import android.net.wifi.WifiActivityEnergyInfo;
Dianne Hackborn3251b902014-06-20 14:40:53 -070032import android.net.wifi.WifiManager;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070033import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.os.BatteryStats;
Dianne Hackborncd0e3352014-08-07 17:08:09 -070035import android.os.Build;
Siddharth Raya1fd0572017-11-13 14:20:47 -080036import android.os.connectivity.CellularBatteryStats;
Siddharth Rayb50a6842017-12-14 15:15:28 -080037import android.os.connectivity.WifiBatteryStats;
Siddharth Ray78ccaf52017-12-23 16:16:21 -080038import android.os.connectivity.GpsBatteryStats;
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;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080056import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070057import android.telephony.DataConnectionRealTimeInfo;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080058import android.telephony.ModemActivityInfo;
Amith Yamasanif37447b2009-10-08 18:28:01 -070059import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070060import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070061import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070062import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070063import android.util.ArrayMap;
Sudheer Shankab2f83c12017-11-13 19:25:01 -080064import android.util.IntArray;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080065import android.util.KeyValueListParser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070067import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070068import android.util.LongSparseArray;
69import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070070import android.util.MutableInt;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070071import android.util.Pools;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070072import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070074import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080076import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070077import android.util.SparseLongArray;
Bookatzc1a050a2017-10-10 15:49:28 -070078import android.util.StatsLog;
Dianne Hackbornae384452011-06-28 12:33:48 -070079import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080080import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070081import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
Adam Lesinski14ae39a2017-05-26 11:50:40 -070083import com.android.internal.annotations.GuardedBy;
Adam Lesinski98f0d462016-04-19 16:46:20 -070084import com.android.internal.annotations.VisibleForTesting;
Siddharth Ray78ccaf52017-12-23 16:16:21 -080085import com.android.internal.location.gnssmetrics.GnssMetrics;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070086import com.android.internal.net.NetworkStatsFactory;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080087import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070088import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080089import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070090import com.android.internal.util.JournaledFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080091import com.android.internal.util.XmlUtils;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070092
Narayan Kamath81822022017-12-08 11:56:01 +000093import java.util.List;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070094import libcore.util.EmptyArray;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080095import org.xmlpull.v1.XmlPullParser;
96import org.xmlpull.v1.XmlPullParserException;
97import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070098
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080099import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import java.io.File;
101import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800102import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.io.FileOutputStream;
104import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700105import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100106import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700108import java.util.Arrays;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800109import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.HashMap;
Evan Millarc64edde2009-04-18 12:26:32 -0700111import java.util.Iterator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import java.util.Map;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700113import java.util.concurrent.Future;
Christopher Tate4cee7252010-03-19 14:50:40 -0700114import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700115import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
117/**
118 * All information we are collecting about things that can happen that impact
119 * battery life. All times are represented in microseconds except where indicated
120 * otherwise.
121 */
Joe Onoratoabded112016-02-08 16:49:39 -0800122public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800124 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700125 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800126 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700127 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700128 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700129 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700130
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700131 // TODO: remove "tcp" from network methods, since we measure total stats.
132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700134 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
136 // Current on-disk Parcel version
Siddharth Rayb50a6842017-12-14 15:15:28 -0800137 private static final int VERSION = 174 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700138
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700139 // Maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100140 private static final int MAX_HISTORY_ITEMS;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700141
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700142 // No, really, THIS is the maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100143 private static final int MAX_MAX_HISTORY_ITEMS;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700144
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800145 // The maximum number of names wakelocks we will keep track of
146 // per uid; once the limit is reached, we batch the remaining wakelocks
147 // in to one common name.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100148 private static final int MAX_WAKELOCKS_PER_UID;
149
150 static final int MAX_HISTORY_BUFFER; // 256KB
151 static final int MAX_MAX_HISTORY_BUFFER; // 320KB
152
153 static {
154 if (ActivityManager.isLowRamDeviceStatic()) {
155 MAX_HISTORY_ITEMS = 800;
156 MAX_MAX_HISTORY_ITEMS = 1200;
157 MAX_WAKELOCKS_PER_UID = 40;
158 MAX_HISTORY_BUFFER = 96*1024; // 96KB
159 MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
160 } else {
Makoto Onuki44d64602018-01-18 08:44:28 -0800161 MAX_HISTORY_ITEMS = 4000;
162 MAX_MAX_HISTORY_ITEMS = 6000;
163 MAX_WAKELOCKS_PER_UID = 200;
164 MAX_HISTORY_BUFFER = 512*1024; // 512KB
165 MAX_MAX_HISTORY_BUFFER = 640*1024; // 640KB
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100166 }
167 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700168
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800169 // Number of transmit power states the Wifi controller can be in.
170 private static final int NUM_WIFI_TX_LEVELS = 1;
171
172 // Number of transmit power states the Bluetooth controller can be in.
173 private static final int NUM_BT_TX_LEVELS = 1;
174
Sudheer Shanka38383232017-07-25 09:55:03 -0700175 /**
176 * Holding a wakelock costs more than just using the cpu.
177 * Currently, we assign only half the cpu time to an app that is running but
178 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
179 * If no app is holding a wakelock, then the distribution is normal.
180 */
181 @VisibleForTesting
182 public static final int WAKE_LOCK_WEIGHT = 50;
183
Joe Onoratoabded112016-02-08 16:49:39 -0800184 protected Clocks mClocks;
185
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700186 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700187 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800188 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700190 static final int MSG_UPDATE_WAKELOCKS = 1;
191 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700192 static final int MSG_REPORT_CHARGING = 3;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700193 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700194
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700195 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
196 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
197
Sudheer Shanka38383232017-07-25 09:55:03 -0700198 @VisibleForTesting
199 protected KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
200 @VisibleForTesting
201 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
202 @VisibleForTesting
203 protected KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700204 new KernelUidCpuFreqTimeReader();
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800205 @VisibleForTesting
Mike Ma3d422c32017-10-25 11:08:57 -0700206 protected KernelUidCpuActiveTimeReader mKernelUidCpuActiveTimeReader =
207 new KernelUidCpuActiveTimeReader();
208 @VisibleForTesting
209 protected KernelUidCpuClusterTimeReader mKernelUidCpuClusterTimeReader =
210 new KernelUidCpuClusterTimeReader();
211 @VisibleForTesting
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800212 protected KernelSingleUidTimeReader mKernelSingleUidTimeReader;
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700213
James Carr3a226052016-07-01 14:49:52 -0700214 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
215 = new KernelMemoryBandwidthStats();
216 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
217 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
218 return mKernelMemoryStats;
219 }
220
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800221 @GuardedBy("this")
222 public boolean mPerProcStateCpuTimesAvailable = true;
223
224 /**
225 * Uids for which per-procstate cpu times need to be updated.
226 *
227 * Contains uid -> procState mappings.
228 */
229 @GuardedBy("this")
230 @VisibleForTesting
231 protected final SparseIntArray mPendingUids = new SparseIntArray();
232
Bookatz0b8a0502017-09-13 11:51:52 -0700233 /** Container for Resource Power Manager stats. Updated by updateRpmStatsLocked. */
Bookatz50df7112017-08-04 14:53:26 -0700234 private final RpmStats mTmpRpmStats = new RpmStats();
Bookatz0b8a0502017-09-13 11:51:52 -0700235 /** The soonest the RPM stats can be updated after it was last updated. */
236 private static final long RPM_STATS_UPDATE_FREQ_MS = 1000;
237 /** Last time that RPM stats were updated by updateRpmStatsLocked. */
238 private long mLastRpmStatsUpdateTimeMs = -RPM_STATS_UPDATE_FREQ_MS;
Bookatz50df7112017-08-04 14:53:26 -0700239
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700240 public interface BatteryCallback {
241 public void batteryNeedsCpuUpdate();
242 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700243 public void batterySendBroadcast(Intent intent);
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700244 }
245
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700246 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700247 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700248 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000249 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700250 }
251
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700252 public static abstract class UserInfoProvider {
253 private int[] userIds;
254 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700255 @VisibleForTesting
256 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700257 userIds = getUserIds();
258 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700259 @VisibleForTesting
260 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700261 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
262 }
263 }
264
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700265 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
266
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700267 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800268 public MyHandler(Looper looper) {
269 super(looper, null, true);
270 }
271
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700272 @Override
273 public void handleMessage(Message msg) {
274 BatteryCallback cb = mCallback;
275 switch (msg.what) {
276 case MSG_UPDATE_WAKELOCKS:
Adam Lesinski72478f02015-06-17 15:39:43 -0700277 synchronized (BatteryStatsImpl.this) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -0700278 updateCpuTimeLocked();
Adam Lesinski72478f02015-06-17 15:39:43 -0700279 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700280 if (cb != null) {
281 cb.batteryNeedsCpuUpdate();
282 }
283 break;
284 case MSG_REPORT_POWER_CHANGE:
285 if (cb != null) {
286 cb.batteryPowerChanged(msg.arg1 != 0);
287 }
288 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700289 case MSG_REPORT_CHARGING:
290 if (cb != null) {
291 final String action;
292 synchronized (BatteryStatsImpl.this) {
293 action = mCharging ? BatteryManager.ACTION_CHARGING
294 : BatteryManager.ACTION_DISCHARGING;
295 }
296 Intent intent = new Intent(action);
297 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
298 cb.batterySendBroadcast(intent);
299 }
300 break;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700301 }
302 }
303 }
304
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800305 /**
306 * Update per-freq cpu times for all the uids in {@link #mPendingUids}.
307 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800308 public void updateProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800309 final SparseIntArray uidStates;
310 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800311 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
312 return;
313 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800314 if(!initKernelSingleUidTimeReaderLocked()) {
315 return;
316 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800317 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
318 // compute deltas since it might result in mis-attributing cpu times to wrong states.
319 if (mKernelSingleUidTimeReader.hasStaleData()) {
320 mPendingUids.clear();
321 return;
322 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800323
324 if (mPendingUids.size() == 0) {
325 return;
326 }
327 uidStates = mPendingUids.clone();
328 mPendingUids.clear();
329 }
330 for (int i = uidStates.size() - 1; i >= 0; --i) {
331 final int uid = uidStates.keyAt(i);
332 final int procState = uidStates.valueAt(i);
333 final int[] isolatedUids;
334 final Uid u;
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800335 synchronized (BatteryStatsImpl.this) {
336 // It's possible that uid no longer exists and any internal references have
337 // already been deleted, so using {@link #getAvailableUidStatsLocked} to avoid
338 // creating an UidStats object if it doesn't already exist.
339 u = getAvailableUidStatsLocked(uid);
340 if (u == null) {
341 continue;
342 }
343 if (u.mChildUids == null) {
344 isolatedUids = null;
345 } else {
346 isolatedUids = u.mChildUids.toArray();
347 for (int j = isolatedUids.length - 1; j >= 0; --j) {
348 isolatedUids[j] = u.mChildUids.get(j);
349 }
350 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800351 }
352 long[] cpuTimesMs = mKernelSingleUidTimeReader.readDeltaMs(uid);
353 if (isolatedUids != null) {
354 for (int j = isolatedUids.length - 1; j >= 0; --j) {
355 cpuTimesMs = addCpuTimes(cpuTimesMs,
356 mKernelSingleUidTimeReader.readDeltaMs(isolatedUids[j]));
357 }
358 }
359 if (onBattery && cpuTimesMs != null) {
360 synchronized (BatteryStatsImpl.this) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800361 u.addProcStateTimesMs(procState, cpuTimesMs, onBattery);
362 u.addProcStateScreenOffTimesMs(procState, cpuTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800363 }
364 }
365 }
366 }
367
Sudheer Shankae544d162017-12-28 17:06:20 -0800368 public void copyFromAllUidsCpuTimes() {
369 synchronized (BatteryStatsImpl.this) {
370 copyFromAllUidsCpuTimes(
371 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
372 }
373 }
374
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800375 /**
376 * When the battery/screen state changes, we don't attribute the cpu times to any process
377 * but we still need to snapshots of all uids to get correct deltas later on. Since we
378 * already read this data for updating per-freq cpu times, we can use the same data for
379 * per-procstate cpu times.
380 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800381 public void copyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800382 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800383 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
384 return;
385 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800386 if(!initKernelSingleUidTimeReaderLocked()) {
387 return;
388 }
389
390 final SparseArray<long[]> allUidCpuFreqTimesMs =
391 mKernelUidCpuFreqTimeReader.getAllUidCpuFreqTimeMs();
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800392 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
393 // compute deltas since it might result in mis-attributing cpu times to wrong states.
394 if (mKernelSingleUidTimeReader.hasStaleData()) {
395 mKernelSingleUidTimeReader.setAllUidsCpuTimesMs(allUidCpuFreqTimesMs);
396 mKernelSingleUidTimeReader.markDataAsStale(false);
397 mPendingUids.clear();
398 return;
399 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800400 for (int i = allUidCpuFreqTimesMs.size() - 1; i >= 0; --i) {
401 final int uid = allUidCpuFreqTimesMs.keyAt(i);
402 final Uid u = getAvailableUidStatsLocked(mapUid(uid));
403 if (u == null) {
404 continue;
405 }
406 final long[] cpuTimesMs = allUidCpuFreqTimesMs.valueAt(i);
407 if (cpuTimesMs == null) {
408 continue;
409 }
410 final long[] deltaTimesMs = mKernelSingleUidTimeReader.computeDelta(
411 uid, cpuTimesMs.clone());
Sudheer Shankae544d162017-12-28 17:06:20 -0800412 if (onBattery && deltaTimesMs != null) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800413 final int procState;
414 final int idx = mPendingUids.indexOfKey(uid);
415 if (idx >= 0) {
416 procState = mPendingUids.valueAt(idx);
417 mPendingUids.removeAt(idx);
418 } else {
419 procState = u.mProcessState;
420 }
421 if (procState >= 0 && procState < Uid.NUM_PROCESS_STATE) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800422 u.addProcStateTimesMs(procState, deltaTimesMs, onBattery);
423 u.addProcStateScreenOffTimesMs(procState, deltaTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800424 }
425 }
426 }
427 }
428 }
429
430 @VisibleForTesting
431 public long[] addCpuTimes(long[] timesA, long[] timesB) {
432 if (timesA != null && timesB != null) {
433 for (int i = timesA.length - 1; i >= 0; --i) {
434 timesA[i] += timesB[i];
435 }
436 return timesA;
437 }
438 return timesA == null ? (timesB == null ? null : timesB) : timesA;
439 }
440
441 @GuardedBy("this")
442 private boolean initKernelSingleUidTimeReaderLocked() {
443 if (mKernelSingleUidTimeReader == null) {
444 if (mPowerProfile == null) {
445 return false;
446 }
447 if (mCpuFreqs == null) {
448 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
449 }
450 if (mCpuFreqs != null) {
451 mKernelSingleUidTimeReader = new KernelSingleUidTimeReader(mCpuFreqs.length);
452 } else {
453 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable();
454 return false;
455 }
456 }
457 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable()
458 && mKernelSingleUidTimeReader.singleUidCpuTimesAvailable();
459 return true;
460 }
461
Joe Onoratoabded112016-02-08 16:49:39 -0800462 public interface Clocks {
463 public long elapsedRealtime();
464 public long uptimeMillis();
465 }
466
467 public static class SystemClocks implements Clocks {
468 public long elapsedRealtime() {
469 return SystemClock.elapsedRealtime();
470 }
471
472 public long uptimeMillis() {
473 return SystemClock.uptimeMillis();
474 }
475 }
476
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700477 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700478 int UPDATE_CPU = 0x01;
479 int UPDATE_WIFI = 0x02;
480 int UPDATE_RADIO = 0x04;
481 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700482 int UPDATE_RPM = 0x10; // 16
483 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800484
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700485 Future<?> scheduleSync(String reason, int flags);
486 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Sudheer Shankae544d162017-12-28 17:06:20 -0800487 Future<?> scheduleReadProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
488 Future<?> scheduleCopyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800489 Future<?> scheduleCpuSyncDueToSettingChange();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700490 }
491
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800492 public Handler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700493 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700494 @VisibleForTesting
495 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700496
497 private BatteryCallback mCallback;
498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800500 * Mapping isolated uids to the actual owning app uid.
501 */
502 final SparseIntArray mIsolatedUids = new SparseIntArray();
503
504 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 * The statistics we have collected organized by uids.
506 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800507 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508
509 // A set of pools of currently active timers. When a timer is queried, we will divide the
510 // elapsed time by the number of active timers to arrive at that timer's share of the time.
511 // In order to do this, we must refresh each timer whenever the number of active timers
512 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700513 @VisibleForTesting
514 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700515 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
516 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700517 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700518 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
519 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
520 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
521 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
522 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
523 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
524 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
525 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700526 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
527 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800528 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700530 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700531 @VisibleForTesting
532 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 // These are the objects that will want to do something when the device
535 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800536 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800537
538 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700539 // is unplugged from power *and* the screen is off or doze.
540 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800541
542 // Set to true when we want to distribute CPU across wakelocks for the next
543 // CPU update, even if we aren't currently running wake locks.
544 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700545
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700546 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700547
Dianne Hackborn37de0982014-05-09 09:32:18 -0700548 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800549
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700550 long mHistoryBaseTime;
Narayan Kamath695cf722017-12-21 18:32:47 +0000551 protected boolean mHaveBatteryLevel = false;
552 protected boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700553 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700554
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700555 final Parcel mHistoryBuffer = Parcel.obtain();
556 final HistoryItem mHistoryLastWritten = new HistoryItem();
557 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700558 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700559 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700560 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800561 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800562 int[] mReadHistoryUids;
563 int mReadHistoryChars;
564 int mNextHistoryTagIdx = 0;
565 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700566 int mHistoryBufferLastPos = -1;
567 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700568 int mActiveHistoryStates = 0xffffffff;
569 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700570 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700571 long mTrackRunningHistoryElapsedRealtime = 0;
572 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700573
574 final HistoryItem mHistoryCur = new HistoryItem();
575
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700576 HistoryItem mHistory;
577 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700578 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700579 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700580
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800581 // Used by computeHistoryStepDetails
582 HistoryStepDetails mLastHistoryStepDetails = null;
583 byte mLastHistoryStepLevel = 0;
584 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
585 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
586 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700587
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800588 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700589 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800590 */
591 long mLastStepCpuUserTime;
592 long mCurStepCpuUserTime;
593 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700594 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800595 */
596 long mLastStepCpuSystemTime;
597 long mCurStepCpuSystemTime;
598 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700599 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800600 */
601 long mLastStepStatUserTime;
602 long mLastStepStatSystemTime;
603 long mLastStepStatIOWaitTime;
604 long mLastStepStatIrqTime;
605 long mLastStepStatSoftIrqTime;
606 long mLastStepStatIdleTime;
607 long mCurStepStatUserTime;
608 long mCurStepStatSystemTime;
609 long mCurStepStatIOWaitTime;
610 long mCurStepStatIrqTime;
611 long mCurStepStatSoftIrqTime;
612 long mCurStepStatIdleTime;
613
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700614 private HistoryItem mHistoryIterator;
615 private boolean mReadOverflow;
616 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 int mStartCount;
619
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800620 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700621 String mStartPlatformVersion;
622 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 long mUptime;
625 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 long mRealtime;
627 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700628
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800629 int mWakeLockNesting;
630 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700631 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700632 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800633
Mike Mac2f518a2017-09-19 16:06:03 -0700634 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
635 protected int mScreenState = Display.STATE_UNKNOWN;
636 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
637 protected StopwatchTimer mScreenOnTimer;
638 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
639 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700640
Dianne Hackborn617f8772009-03-31 15:04:46 -0700641 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700642 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700643
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800644 boolean mPretendScreenOff;
645
Jeff Browne95c3cd2014-05-02 16:59:26 -0700646 boolean mInteractive;
647 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700648
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700649 boolean mPowerSaveModeEnabled;
650 StopwatchTimer mPowerSaveModeEnabledTimer;
651
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700652 boolean mDeviceIdling;
653 StopwatchTimer mDeviceIdlingTimer;
654
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700655 boolean mDeviceLightIdling;
656 StopwatchTimer mDeviceLightIdlingTimer;
657
658 int mDeviceIdleMode;
659 long mLastIdleTimeStart;
660 long mLongestLightIdleTime;
661 long mLongestFullIdleTime;
662 StopwatchTimer mDeviceIdleModeLightTimer;
663 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700666 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700667
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700668 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700669 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700670
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700671 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700672 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700673
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700674 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700675 StopwatchTimer mFlashlightOnTimer;
676
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700677 int mCameraOnNesting;
678 StopwatchTimer mCameraOnTimer;
679
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800680 int mGpsSignalQualityBin = -1;
681 final StopwatchTimer[] mGpsSignalQualityTimer =
682 new StopwatchTimer[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
683
Dianne Hackborn627bba72009-03-24 22:32:56 -0700684 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800685 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700686 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800687 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700688
689 StopwatchTimer mPhoneSignalScanningTimer;
690
Dianne Hackborn627bba72009-03-24 22:32:56 -0700691 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700692 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700693 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700694
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800695 final LongSamplingCounter[] mNetworkByteActivityCounters =
696 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
697 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700698 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
699
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800700 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800701 * The WiFi Overall wakelock timer
702 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
703 * since addition of per UID timers would not result in an accurate value due to overlapp of
704 * per uid wakelock timers
705 */
706 StopwatchTimer mWifiMulticastWakelockTimer;
707
708 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800709 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
710 */
711 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700712
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800713 /**
714 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
715 */
716 ControllerActivityCounterImpl mBluetoothActivity;
717
718 /**
719 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
720 */
721 ControllerActivityCounterImpl mModemActivity;
722
723 /**
724 * Whether the device supports WiFi controller energy reporting. This is set to true on
725 * the first WiFi energy report. See {@link #mWifiActivity}.
726 */
727 boolean mHasWifiReporting = false;
728
729 /**
730 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
731 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
732 */
733 boolean mHasBluetoothReporting = false;
734
735 /**
736 * Whether the device supports Modem controller energy reporting. This is set to true on
737 * the first Modem energy report. See {@link #mModemActivity}.
738 */
739 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700740
The Android Open Source Project10592532009-03-18 17:39:46 -0700741 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700742 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700743
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700744 boolean mGlobalWifiRunning;
745 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700746
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800747 int mWifiState = -1;
748 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
749
Dianne Hackborn3251b902014-06-20 14:40:53 -0700750 int mWifiSupplState = -1;
751 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
752
753 int mWifiSignalStrengthBin = -1;
754 final StopwatchTimer[] mWifiSignalStrengthsTimer =
755 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
756
Siddharth Rayb50a6842017-12-14 15:15:28 -0800757 StopwatchTimer mWifiActiveTimer;
758
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800759 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800760 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
761 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800762
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700763 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700764 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800765 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800766 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700767 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800768 LongSamplingCounter mMobileRadioActiveUnknownTime;
769 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800770
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700771 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 /**
774 * These provide time bases that discount the time the device is plugged
775 * in to power.
776 */
777 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700778 @VisibleForTesting
779 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700780
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700781 /**
782 * External reporting of whether the device is actually charging.
783 */
784 boolean mCharging = true;
785 int mLastChargingStateLevel;
786
The Android Open Source Project10592532009-03-18 17:39:46 -0700787 /*
788 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
789 */
Evan Millar633a1742009-04-02 16:36:33 -0700790 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700791 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700792 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700793 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700794 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700795 int mLowDischargeAmountSinceCharge;
796 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800797 int mDischargeScreenOnUnplugLevel;
798 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700799 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800800 int mDischargeAmountScreenOn;
801 int mDischargeAmountScreenOnSinceCharge;
802 int mDischargeAmountScreenOff;
803 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700804 int mDischargeAmountScreenDoze;
805 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700806
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700807 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700808 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700809 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800810 private LongSamplingCounter mDischargeLightDozeCounter;
811 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700812
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700813 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700814
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700815 int mInitStepMode = 0;
816 int mCurStepMode = 0;
817 int mModStepMode = 0;
818
Dianne Hackborn260c5022014-04-29 11:23:16 -0700819 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700820 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800821 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
822 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700823 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700824
825 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700826 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800827 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
828 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
829
830 static final int MAX_DAILY_ITEMS = 10;
831
832 long mDailyStartTime = 0;
833 long mNextMinDailyDeadline = 0;
834 long mNextMaxDailyDeadline = 0;
835
836 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700839
Amith Yamasanif37447b2009-10-08 18:28:01 -0700840 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800841 private int mPhoneServiceStateRaw = -1;
842 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700843
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800844 private int mNumConnectivityChange;
845 private int mLoadedNumConnectivityChange;
846 private int mUnpluggedNumConnectivityChange;
847
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700848 private int mEstimatedBatteryCapacity = -1;
849
Jocelyn Dangc627d102017-04-14 13:15:14 -0700850 private int mMinLearnedBatteryCapacity = -1;
851 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800852
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700853 private long[] mCpuFreqs;
854
Sudheer Shanka38383232017-07-25 09:55:03 -0700855 @VisibleForTesting
856 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700857
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800858 @GuardedBy("this")
859 private final Constants mConstants;
860
Evan Millarc64edde2009-04-18 12:26:32 -0700861 /*
Bookatz50df7112017-08-04 14:53:26 -0700862 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
863 * recording their times when on-battery (regardless of screen state).
864 */
865 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
866 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
867 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
868
869 @Override
870 public Map<String, ? extends Timer> getRpmStats() {
871 return mRpmStats;
872 }
873
Bookatz82b341172017-09-07 19:06:08 -0700874 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700875 @Override
876 public Map<String, ? extends Timer> getScreenOffRpmStats() {
877 return mScreenOffRpmStats;
878 }
879
880 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700881 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
882 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700883 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700884
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700885 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700886 return mKernelWakelockStats;
887 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700888
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700889 String mLastWakeupReason = null;
890 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700891 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700892
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700893 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700894 return mWakeupReasonStats;
895 }
896
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700897 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700898 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700899 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700900 }
901
902 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700903 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700904 return mDischargeScreenOffCounter.getCountLocked(which);
905 }
906
907 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700908 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700909 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700910 }
911
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700912 @Override
Mike Ma15313c92017-11-15 17:58:21 -0800913 public long getUahDischargeLightDoze(int which) {
914 return mDischargeLightDozeCounter.getCountLocked(which);
915 }
916
917 @Override
918 public long getUahDischargeDeepDoze(int which) {
919 return mDischargeDeepDozeCounter.getCountLocked(which);
920 }
921
922 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700923 public int getEstimatedBatteryCapacity() {
924 return mEstimatedBatteryCapacity;
925 }
926
Jocelyn Dangc627d102017-04-14 13:15:14 -0700927 @Override
928 public int getMinLearnedBatteryCapacity() {
929 return mMinLearnedBatteryCapacity;
930 }
931
932 @Override
933 public int getMaxLearnedBatteryCapacity() {
934 return mMaxLearnedBatteryCapacity;
935 }
936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -0800938 this(new SystemClocks());
939 }
940
941 public BatteryStatsImpl(Clocks clocks) {
942 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700943 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700944 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800945 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700946 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700947 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700948 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800949 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700950 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 }
952
Joe Onoratoabded112016-02-08 16:49:39 -0800953 private void init(Clocks clocks) {
954 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -0800955 }
956
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700957 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800958 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
959 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
960 }
961
Joe Onoratoabded112016-02-08 16:49:39 -0800962 // methods are protected not private to be VisibleForTesting
963 public static class TimeBase {
964 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800965
Joe Onoratoabded112016-02-08 16:49:39 -0800966 protected long mUptime;
967 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800968
Joe Onoratoabded112016-02-08 16:49:39 -0800969 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800970
Joe Onoratoabded112016-02-08 16:49:39 -0800971 protected long mPastUptime;
972 protected long mUptimeStart;
973 protected long mPastRealtime;
974 protected long mRealtimeStart;
975 protected long mUnpluggedUptime;
976 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800977
978 public void dump(PrintWriter pw, String prefix) {
979 StringBuilder sb = new StringBuilder(128);
980 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
981 sb.setLength(0);
982 sb.append(prefix);
983 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700984 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800985 pw.println(sb.toString());
986 sb.setLength(0);
987 sb.append(prefix);
988 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700989 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800990 pw.println(sb.toString());
991 sb.setLength(0);
992 sb.append(prefix);
993 sb.append("mPastUptime=");
994 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
995 formatTimeMs(sb, mUptimeStart / 1000);
996 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
997 pw.println(sb.toString());
998 sb.setLength(0);
999 sb.append(prefix);
1000 sb.append("mPastRealtime=");
1001 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
1002 formatTimeMs(sb, mRealtimeStart / 1000);
1003 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
1004 pw.println(sb.toString());
1005 }
1006
1007 public void add(TimeBaseObs observer) {
1008 mObservers.add(observer);
1009 }
1010
1011 public void remove(TimeBaseObs observer) {
1012 if (!mObservers.remove(observer)) {
1013 Slog.wtf(TAG, "Removed unknown observer: " + observer);
1014 }
1015 }
1016
Joe Onoratoabded112016-02-08 16:49:39 -08001017 public boolean hasObserver(TimeBaseObs observer) {
1018 return mObservers.contains(observer);
1019 }
1020
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001021 public void init(long uptime, long realtime) {
1022 mRealtime = 0;
1023 mUptime = 0;
1024 mPastUptime = 0;
1025 mPastRealtime = 0;
1026 mUptimeStart = uptime;
1027 mRealtimeStart = realtime;
1028 mUnpluggedUptime = getUptime(mUptimeStart);
1029 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1030 }
1031
1032 public void reset(long uptime, long realtime) {
1033 if (!mRunning) {
1034 mPastUptime = 0;
1035 mPastRealtime = 0;
1036 } else {
1037 mUptimeStart = uptime;
1038 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001039 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1040 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001041 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001042 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001043 mUnpluggedRealtime = getRealtime(realtime);
1044 }
1045 }
1046
1047 public long computeUptime(long curTime, int which) {
1048 switch (which) {
1049 case STATS_SINCE_CHARGED:
1050 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001051 case STATS_CURRENT:
1052 return getUptime(curTime);
1053 case STATS_SINCE_UNPLUGGED:
1054 return getUptime(curTime) - mUnpluggedUptime;
1055 }
1056 return 0;
1057 }
1058
1059 public long computeRealtime(long curTime, int which) {
1060 switch (which) {
1061 case STATS_SINCE_CHARGED:
1062 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001063 case STATS_CURRENT:
1064 return getRealtime(curTime);
1065 case STATS_SINCE_UNPLUGGED:
1066 return getRealtime(curTime) - mUnpluggedRealtime;
1067 }
1068 return 0;
1069 }
1070
1071 public long getUptime(long curTime) {
1072 long time = mPastUptime;
1073 if (mRunning) {
1074 time += curTime - mUptimeStart;
1075 }
1076 return time;
1077 }
1078
1079 public long getRealtime(long curTime) {
1080 long time = mPastRealtime;
1081 if (mRunning) {
1082 time += curTime - mRealtimeStart;
1083 }
1084 return time;
1085 }
1086
1087 public long getUptimeStart() {
1088 return mUptimeStart;
1089 }
1090
1091 public long getRealtimeStart() {
1092 return mRealtimeStart;
1093 }
1094
1095 public boolean isRunning() {
1096 return mRunning;
1097 }
1098
1099 public boolean setRunning(boolean running, long uptime, long realtime) {
1100 if (mRunning != running) {
1101 mRunning = running;
1102 if (running) {
1103 mUptimeStart = uptime;
1104 mRealtimeStart = realtime;
1105 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1106 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
1107
1108 for (int i = mObservers.size() - 1; i >= 0; i--) {
1109 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
1110 }
1111 } else {
1112 mPastUptime += uptime - mUptimeStart;
1113 mPastRealtime += realtime - mRealtimeStart;
1114
1115 long batteryUptime = getUptime(uptime);
1116 long batteryRealtime = getRealtime(realtime);
1117
1118 for (int i = mObservers.size() - 1; i >= 0; i--) {
1119 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
1120 }
1121 }
1122 return true;
1123 }
1124 return false;
1125 }
1126
1127 public void readSummaryFromParcel(Parcel in) {
1128 mUptime = in.readLong();
1129 mRealtime = in.readLong();
1130 }
1131
1132 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1133 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1134 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1135 }
1136
1137 public void readFromParcel(Parcel in) {
1138 mRunning = false;
1139 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001140 mPastUptime = in.readLong();
1141 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001142 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001143 mPastRealtime = in.readLong();
1144 mRealtimeStart = in.readLong();
1145 mUnpluggedUptime = in.readLong();
1146 mUnpluggedRealtime = in.readLong();
1147 }
1148
1149 public void writeToParcel(Parcel out, long uptime, long realtime) {
1150 final long runningUptime = getUptime(uptime);
1151 final long runningRealtime = getRealtime(realtime);
1152 out.writeLong(mUptime);
1153 out.writeLong(runningUptime);
1154 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001155 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001156 out.writeLong(runningRealtime);
1157 out.writeLong(mRealtimeStart);
1158 out.writeLong(mUnpluggedUptime);
1159 out.writeLong(mUnpluggedRealtime);
1160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001164 * State for keeping track of counting information.
1165 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001166 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -07001167 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001168 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001169 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001170 int mUnpluggedCount;
1171 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001172
Bookatz8c6f3c52017-05-24 12:00:17 -07001173 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001174 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -07001175 mPluggedCount = in.readInt();
1176 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001177 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001178 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001179 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001180 }
1181
Bookatz8c6f3c52017-05-24 12:00:17 -07001182 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001183 mTimeBase = timeBase;
1184 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001185 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001186
Dianne Hackborn617f8772009-03-31 15:04:46 -07001187 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001188 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001189 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001190 out.writeInt(mUnpluggedCount);
1191 }
1192
Bookatz8c6f3c52017-05-24 12:00:17 -07001193 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001194 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001195 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001196 }
1197
Bookatz8c6f3c52017-05-24 12:00:17 -07001198 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001199 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001200 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001201 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001202
Dianne Hackborn617f8772009-03-31 15:04:46 -07001203 /**
1204 * Writes a possibly null Counter to a Parcel.
1205 *
1206 * @param out the Parcel to be written to.
1207 * @param counter a Counter, or null.
1208 */
1209 public static void writeCounterToParcel(Parcel out, Counter counter) {
1210 if (counter == null) {
1211 out.writeInt(0); // indicates null
1212 return;
1213 }
1214 out.writeInt(1); // indicates non-null
1215
1216 counter.writeToParcel(out);
1217 }
1218
1219 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001220 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001221 int val = mCount.get();
1222 if (which == STATS_SINCE_UNPLUGGED) {
1223 val -= mUnpluggedCount;
1224 } else if (which != STATS_SINCE_CHARGED) {
1225 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001226 }
1227
1228 return val;
1229 }
1230
1231 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001232 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001233 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001234 + " mUnpluggedCount=" + mUnpluggedCount
1235 + " mPluggedCount=" + mPluggedCount);
1236 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001237
Bookatz8c6f3c52017-05-24 12:00:17 -07001238 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1239 public void stepAtomic() {
1240 if (mTimeBase.isRunning()) {
1241 mCount.incrementAndGet();
1242 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001243 }
1244
Bookatz4ebc0642017-05-11 12:21:19 -07001245 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001246 if (mTimeBase.isRunning()) {
1247 mCount.addAndGet(delta);
1248 }
Bookatz4ebc0642017-05-11 12:21:19 -07001249 }
1250
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001251 /**
1252 * Clear state of this counter.
1253 */
1254 void reset(boolean detachIfReset) {
1255 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001256 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001257 if (detachIfReset) {
1258 detach();
1259 }
1260 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001261
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001262 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001263 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001264 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001265
Bookatz8c6f3c52017-05-24 12:00:17 -07001266 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1267 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001268 int count = mCount.get();
1269 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001270 }
1271
Bookatz8c6f3c52017-05-24 12:00:17 -07001272 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1273 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001274 mLoadedCount = in.readInt();
1275 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001276 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001277 }
1278 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001279
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001280 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001281 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1282 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001283 public long[] mCounts;
1284 public long[] mLoadedCounts;
1285 public long[] mUnpluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001286
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001287 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001288 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001289 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001290 mLoadedCounts = in.createLongArray();
1291 mUnpluggedCounts = in.createLongArray();
1292 timeBase.add(this);
1293 }
1294
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001295 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001296 mTimeBase = timeBase;
1297 timeBase.add(this);
1298 }
1299
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001300 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001301 out.writeLongArray(mCounts);
1302 out.writeLongArray(mLoadedCounts);
1303 out.writeLongArray(mUnpluggedCounts);
1304 }
1305
1306 @Override
1307 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001308 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001309 }
1310
1311 @Override
1312 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001313 }
1314
1315 @Override
1316 public long[] getCountsLocked(int which) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001317 long[] val = copyArray(mCounts, null);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001318 if (which == STATS_SINCE_UNPLUGGED) {
1319 subtract(val, mUnpluggedCounts);
1320 } else if (which != STATS_SINCE_CHARGED) {
1321 subtract(val, mLoadedCounts);
1322 }
1323 return val;
1324 }
1325
1326 @Override
1327 public void logState(Printer pw, String prefix) {
1328 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1329 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
Sudheer Shankae544d162017-12-28 17:06:20 -08001330 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001331 }
1332
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001333 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001334 addCountLocked(counts, mTimeBase.isRunning());
1335 }
1336
1337 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001338 if (counts == null) {
1339 return;
1340 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001341 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001342 if (mCounts == null) {
1343 mCounts = new long[counts.length];
1344 }
1345 for (int i = 0; i < counts.length; ++i) {
1346 mCounts[i] += counts[i];
1347 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001348 }
1349 }
1350
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001351 public int getSize() {
1352 return mCounts == null ? 0 : mCounts.length;
1353 }
1354
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001355 /**
1356 * Clear state of this counter.
1357 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001358 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001359 fillArray(mCounts, 0);
1360 fillArray(mLoadedCounts, 0);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001361 fillArray(mUnpluggedCounts, 0);
1362 if (detachIfReset) {
1363 detach();
1364 }
1365 }
1366
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001367 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001368 mTimeBase.remove(this);
1369 }
1370
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001371 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001372 out.writeLongArray(mCounts);
1373 }
1374
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001375 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001376 mCounts = in.createLongArray();
1377 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1378 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001379 }
1380
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001381 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1382 if (counterArray != null) {
1383 out.writeInt(1);
1384 counterArray.writeToParcel(out);
1385 } else {
1386 out.writeInt(0);
1387 }
1388 }
1389
1390 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1391 if (in.readInt() != 0) {
1392 return new LongSamplingCounterArray(timeBase, in);
1393 } else {
1394 return null;
1395 }
1396 }
1397
1398 public static void writeSummaryToParcelLocked(Parcel out,
1399 LongSamplingCounterArray counterArray) {
1400 if (counterArray != null) {
1401 out.writeInt(1);
1402 counterArray.writeSummaryToParcelLocked(out);
1403 } else {
1404 out.writeInt(0);
1405 }
1406 }
1407
1408 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1409 TimeBase timeBase) {
1410 if (in.readInt() != 0) {
1411 final LongSamplingCounterArray counterArray
1412 = new LongSamplingCounterArray(timeBase);
1413 counterArray.readSummaryFromParcelLocked(in);
1414 return counterArray;
1415 } else {
1416 return null;
1417 }
1418 }
1419
Bookatz8c6f3c52017-05-24 12:00:17 -07001420 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001421 if (a != null) {
1422 Arrays.fill(a, val);
1423 }
1424 }
1425
Bookatz8c6f3c52017-05-24 12:00:17 -07001426 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001427 if (toSubtract == null) {
1428 return;
1429 }
1430 for (int i = 0; i < val.length; i++) {
1431 val[i] -= toSubtract[i];
1432 }
1433 }
1434
Bookatz8c6f3c52017-05-24 12:00:17 -07001435 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001436 if (src == null) {
1437 return null;
1438 } else {
1439 if (dest == null) {
1440 dest = new long[src.length];
1441 }
1442 System.arraycopy(src, 0, dest, 0, src.length);
1443 return dest;
1444 }
1445 }
1446 }
1447
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001448 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001449 final TimeBase mTimeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001450 long mCount;
1451 long mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001452 long mUnpluggedCount;
1453 long mPluggedCount;
1454
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001455 LongSamplingCounter(TimeBase timeBase, Parcel in) {
1456 mTimeBase = timeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001457 mPluggedCount = in.readLong();
1458 mCount = mPluggedCount;
1459 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001460 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001461 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001462 }
1463
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001464 LongSamplingCounter(TimeBase timeBase) {
1465 mTimeBase = timeBase;
1466 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001467 }
1468
1469 public void writeToParcel(Parcel out) {
1470 out.writeLong(mCount);
1471 out.writeLong(mLoadedCount);
1472 out.writeLong(mUnpluggedCount);
1473 }
1474
1475 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001476 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001477 mUnpluggedCount = mPluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001478 }
1479
1480 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001481 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001482 mPluggedCount = mCount;
1483 }
1484
1485 public long getCountLocked(int which) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001486 long val = mTimeBase.isRunning() ? mCount : mPluggedCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001487 if (which == STATS_SINCE_UNPLUGGED) {
1488 val -= mUnpluggedCount;
1489 } else if (which != STATS_SINCE_CHARGED) {
1490 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001491 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001492 return val;
1493 }
1494
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001495 @Override
1496 public void logState(Printer pw, String prefix) {
1497 pw.println(prefix + "mCount=" + mCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001498 + " mLoadedCount=" + mLoadedCount
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001499 + " mUnpluggedCount=" + mUnpluggedCount
1500 + " mPluggedCount=" + mPluggedCount);
1501 }
1502
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001503 void addCountLocked(long count) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001504 if (mTimeBase.isRunning()) {
1505 mCount += count;
1506 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001507 }
1508
1509 /**
1510 * Clear state of this counter.
1511 */
1512 void reset(boolean detachIfReset) {
1513 mCount = 0;
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001514 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001515 if (detachIfReset) {
1516 detach();
1517 }
1518 }
1519
1520 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001521 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001522 }
1523
1524 void writeSummaryFromParcelLocked(Parcel out) {
1525 out.writeLong(mCount);
1526 }
1527
1528 void readSummaryFromParcelLocked(Parcel in) {
1529 mLoadedCount = in.readLong();
1530 mCount = mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001531 mUnpluggedCount = mPluggedCount = mLoadedCount;
1532 }
1533 }
1534
Dianne Hackborn617f8772009-03-31 15:04:46 -07001535 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 * State for keeping track of timing information.
1537 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001538 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001539 protected final Clocks mClocks;
1540 protected final int mType;
1541 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001542
Joe Onoratoabded112016-02-08 16:49:39 -08001543 protected int mCount;
1544 protected int mLoadedCount;
1545 protected int mLastCount;
1546 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 // Times are in microseconds for better accuracy when dividing by the
1549 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 /**
1552 * The total time we have accumulated since the start of the original
1553 * boot, to the last time something interesting happened in the
1554 * current run.
1555 */
Joe Onoratoabded112016-02-08 16:49:39 -08001556 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 /**
1559 * The total time we loaded for the previous runs. Subtract this from
1560 * mTotalTime to find the time for the current run of the system.
1561 */
Joe Onoratoabded112016-02-08 16:49:39 -08001562 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 /**
1565 * The run time of the last run of the system, as loaded from the
1566 * saved data.
1567 */
Joe Onoratoabded112016-02-08 16:49:39 -08001568 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 /**
1571 * The value of mTotalTime when unplug() was last called. Subtract
1572 * this from mTotalTime to find the time since the last unplug from
1573 * power.
1574 */
Joe Onoratoabded112016-02-08 16:49:39 -08001575 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001576
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001577 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001578 * The total time this timer has been running until the latest mark has been set.
1579 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1580 */
Joe Onoratoabded112016-02-08 16:49:39 -08001581 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001582
1583 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001584 * Constructs from a parcel.
1585 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001586 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001587 * @param in
1588 */
Joe Onoratoabded112016-02-08 16:49:39 -08001589 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1590 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001592 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 mCount = in.readInt();
1595 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001596 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 mUnpluggedCount = in.readInt();
1598 mTotalTime = in.readLong();
1599 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001600 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001602 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001603 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001604 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
1606
Joe Onoratoabded112016-02-08 16:49:39 -08001607 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1608 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001610 mTimeBase = timeBase;
1611 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 }
Evan Millarc64edde2009-04-18 12:26:32 -07001613
1614 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001615
Evan Millarc64edde2009-04-18 12:26:32 -07001616 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001617
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001618 /**
1619 * Clear state of this timer. Returns true if the timer is inactive
1620 * so can be completely dropped.
1621 */
Joe Onoratoabded112016-02-08 16:49:39 -08001622 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001623 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001624 mCount = mLoadedCount = mLastCount = 0;
1625 if (detachIfReset) {
1626 detach();
1627 }
1628 return true;
1629 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001630
Joe Onoratoabded112016-02-08 16:49:39 -08001631 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001632 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001633 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001634
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001635 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001636 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1637 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001638 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001641 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001644 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
1646
Adam Lesinskie08af192015-03-25 16:42:59 -07001647 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001648 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001650 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 + " old mUnpluggedTime=" + mUnpluggedTime
1652 + " old mUnpluggedCount=" + mUnpluggedCount);
1653 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001654 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001655 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 if (DEBUG && mType < 0) {
1657 Log.v(TAG, "unplug #" + mType
1658 + ": new mUnpluggedTime=" + mUnpluggedTime
1659 + " new mUnpluggedCount=" + mUnpluggedCount);
1660 }
1661 }
1662
Adam Lesinskie08af192015-03-25 16:42:59 -07001663 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001664 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001665 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001666 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001667 + " old mTotalTime=" + mTotalTime);
1668 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001669 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001670 mCount = computeCurrentCountLocked();
1671 if (DEBUG && mType < 0) {
1672 Log.v(TAG, "plug #" + mType
1673 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 }
1675 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 /**
1678 * Writes a possibly null Timer to a Parcel.
1679 *
1680 * @param out the Parcel to be written to.
1681 * @param timer a Timer, or null.
1682 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001683 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 if (timer == null) {
1685 out.writeInt(0); // indicates null
1686 return;
1687 }
1688 out.writeInt(1); // indicates non-null
1689
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001690 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 }
1692
1693 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001694 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001695 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1696 if (which == STATS_SINCE_UNPLUGGED) {
1697 val -= mUnpluggedTime;
1698 } else if (which != STATS_SINCE_CHARGED) {
1699 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 }
1701
1702 return val;
1703 }
1704
1705 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001706 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001707 int val = computeCurrentCountLocked();
1708 if (which == STATS_SINCE_UNPLUGGED) {
1709 val -= mUnpluggedCount;
1710 } else if (which != STATS_SINCE_CHARGED) {
1711 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
1713
1714 return val;
1715 }
1716
Adam Lesinskie08af192015-03-25 16:42:59 -07001717 @Override
1718 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1719 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1720 return val - mTimeBeforeMark;
1721 }
1722
1723 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001724 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001725 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1727 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001728 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001730 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001732 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001733
1734
Joe Onoratoabded112016-02-08 16:49:39 -08001735 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001736 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1737 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001738 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001739 }
1740
Joe Onoratoabded112016-02-08 16:49:39 -08001741 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001742 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001743 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001744 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001745 mUnpluggedTime = mTotalTime;
1746 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001747 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001748 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001749
1750 // When reading the summary, we set the mark to be the latest information.
1751 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001752 }
1753 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001754
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001755 /**
1756 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1757 * method. The state of the timer according to its {@link TimeBase} will determine how much
1758 * of the value is recorded.
1759 *
1760 * If the value being recorded resets, {@link #endSample()} can be called in order to
1761 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1762 * between calls, the {@link #endSample()} is automatically called and the new value is
1763 * expected to increase monotonically from that point on.
1764 */
Joe Onoratoabded112016-02-08 16:49:39 -08001765 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001766
Evan Millarc64edde2009-04-18 12:26:32 -07001767 /**
1768 * The most recent reported count from /proc/wakelocks.
1769 */
1770 int mCurrentReportedCount;
1771
1772 /**
1773 * The reported count from /proc/wakelocks when unplug() was last
1774 * called.
1775 */
1776 int mUnpluggedReportedCount;
1777
1778 /**
1779 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001780 */
Evan Millarc64edde2009-04-18 12:26:32 -07001781 long mCurrentReportedTotalTime;
1782
1783
1784 /**
1785 * The reported total_time from /proc/wakelocks when unplug() was last
1786 * called.
1787 */
1788 long mUnpluggedReportedTotalTime;
1789
1790 /**
1791 * Whether we are currently in a discharge cycle.
1792 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001793 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001794
1795 /**
1796 * Whether we are currently recording reported values.
1797 */
1798 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001799
Evan Millarc64edde2009-04-18 12:26:32 -07001800 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001801 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001802 */
1803 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001804
Adam Lesinski98f0d462016-04-19 16:46:20 -07001805 @VisibleForTesting
1806 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001807 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001808 mCurrentReportedCount = in.readInt();
1809 mUnpluggedReportedCount = in.readInt();
1810 mCurrentReportedTotalTime = in.readLong();
1811 mUnpluggedReportedTotalTime = in.readLong();
1812 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001813 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001814 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001815
Adam Lesinski98f0d462016-04-19 16:46:20 -07001816 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001817 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001818 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001819 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001820 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001821 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001822
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001823 /**
1824 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1825 * be less than the values used for a previous invocation.
1826 */
1827 public void endSample() {
1828 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1829 mCount = computeCurrentCountLocked();
1830 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1831 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001832 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001833
Evan Millarc64edde2009-04-18 12:26:32 -07001834 public void setUpdateVersion(int version) {
1835 mUpdateVersion = version;
1836 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001837
Evan Millarc64edde2009-04-18 12:26:32 -07001838 public int getUpdateVersion() {
1839 return mUpdateVersion;
1840 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001841
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001842 /**
1843 * Updates the current recorded values. These are meant to be monotonically increasing
1844 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1845 *
1846 * If the values being recorded have been reset, the monotonically increasing requirement
1847 * will be broken. In this case, {@link #endSample()} is automatically called and
1848 * the total value of totalTime and count are recorded, starting a new monotonically
1849 * increasing sample.
1850 *
1851 * @param totalTime total time of sample in microseconds.
1852 * @param count total number of times the event being sampled occurred.
1853 */
1854 public void update(long totalTime, int count) {
1855 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001856 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001857 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001858 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001859 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001860
1861 mTrackingReportedValues = true;
1862
1863 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1864 endSample();
1865 }
1866
1867 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001868 mCurrentReportedCount = count;
1869 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001870
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001871 /**
1872 * Adds deltaTime and deltaCount to the current sample.
1873 *
1874 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1875 * @param deltaCount additional number of times the event being sampled occurred.
1876 */
1877 public void add(long deltaTime, int deltaCount) {
1878 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001879 }
1880
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001881 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001882 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
1883 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001884 if (mTrackingReportedValues) {
1885 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
1886 mUnpluggedReportedCount = mCurrentReportedCount;
1887 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001888 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07001889 }
1890
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001891 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001892 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1893 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1894 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07001895 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001896
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001897 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001898 public void logState(Printer pw, String prefix) {
1899 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001900 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07001901 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
1902 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
1903 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
1904 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001905
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001906 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001907 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001908 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001909 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
1910 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001911
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001912 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001913 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001914 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001915 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
1916 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001917
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001918 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001919 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1920 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001921 out.writeInt(mCurrentReportedCount);
1922 out.writeInt(mUnpluggedReportedCount);
1923 out.writeLong(mCurrentReportedTotalTime);
1924 out.writeLong(mUnpluggedReportedTotalTime);
1925 out.writeInt(mTrackingReportedValues ? 1 : 0);
1926 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001927
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001928 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001929 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001930 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001931 mTrackingReportedValues = false;
1932 mUnpluggedReportedTotalTime = 0;
1933 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001934 return true;
1935 }
Evan Millarc64edde2009-04-18 12:26:32 -07001936 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001937
Evan Millarc64edde2009-04-18 12:26:32 -07001938 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001939 * A timer that increments in batches. It does not run for durations, but just jumps
1940 * for a pre-determined amount.
1941 */
Joe Onoratoabded112016-02-08 16:49:39 -08001942 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001943 final Uid mUid;
1944
1945 /**
1946 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
1947 */
1948 long mLastAddedTime;
1949
1950 /**
1951 * The last duration that we added to the timer. This is in microseconds.
1952 */
1953 long mLastAddedDuration;
1954
1955 /**
1956 * Whether we are currently in a discharge cycle.
1957 */
1958 boolean mInDischarge;
1959
Joe Onoratoabded112016-02-08 16:49:39 -08001960 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
1961 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001962 mUid = uid;
1963 mLastAddedTime = in.readLong();
1964 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001965 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001966 }
1967
Joe Onoratoabded112016-02-08 16:49:39 -08001968 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
1969 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001970 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001971 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001972 }
1973
1974 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001975 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1976 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001977 out.writeLong(mLastAddedTime);
1978 out.writeLong(mLastAddedDuration);
1979 }
1980
1981 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001982 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001983 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001984 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001985 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001986 }
1987
1988 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001989 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001990 recomputeLastDuration(elapsedRealtime, false);
1991 mInDischarge = true;
1992 // If we are still within the last added duration, then re-added whatever remains.
1993 if (mLastAddedTime == elapsedRealtime) {
1994 mTotalTime += mLastAddedDuration;
1995 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001996 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001997 }
1998
1999 @Override
2000 public void logState(Printer pw, String prefix) {
2001 super.logState(pw, prefix);
2002 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
2003 + " mLastAddedDuration=" + mLastAddedDuration);
2004 }
2005
2006 private long computeOverage(long curTime) {
2007 if (mLastAddedTime > 0) {
2008 return mLastTime + mLastAddedDuration - curTime;
2009 }
2010 return 0;
2011 }
2012
2013 private void recomputeLastDuration(long curTime, boolean abort) {
2014 final long overage = computeOverage(curTime);
2015 if (overage > 0) {
2016 // Aborting before the duration ran out -- roll back the remaining
2017 // duration. Only do this if currently discharging; otherwise we didn't
2018 // actually add the time.
2019 if (mInDischarge) {
2020 mTotalTime -= overage;
2021 }
2022 if (abort) {
2023 mLastAddedTime = 0;
2024 } else {
2025 mLastAddedTime = curTime;
2026 mLastAddedDuration -= overage;
2027 }
2028 }
2029 }
2030
2031 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08002032 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002033 recomputeLastDuration(now, true);
2034 mLastAddedTime = now;
2035 mLastAddedDuration = durationMillis * 1000;
2036 if (mInDischarge) {
2037 mTotalTime += mLastAddedDuration;
2038 mCount++;
2039 }
2040 }
2041
2042 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002043 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002044 recomputeLastDuration(now, true);
2045 }
2046
2047 @Override
2048 protected int computeCurrentCountLocked() {
2049 return mCount;
2050 }
2051
2052 @Override
2053 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002054 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002055 if (overage > 0) {
2056 return mTotalTime = overage;
2057 }
2058 return mTotalTime;
2059 }
2060
2061 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002062 public boolean reset(boolean detachIfReset) {
2063 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002064 recomputeLastDuration(now, true);
2065 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002066 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002067 return !stillActive;
2068 }
2069 }
2070
Joe Onorato92fd23f2016-07-25 11:18:42 -07002071
2072 /**
2073 * A StopwatchTimer that also tracks the total and max individual
2074 * time spent active according to the given timebase. Whereas
2075 * StopwatchTimer apportions the time amongst all in the pool,
2076 * the total and max durations are not apportioned.
2077 */
2078 public static class DurationTimer extends StopwatchTimer {
2079 /**
2080 * The time (in ms) that the timer was last acquired or the time base
2081 * last (re-)started. Increasing the nesting depth does not reset this time.
2082 *
2083 * -1 if the timer is currently not running or the time base is not running.
2084 *
2085 * If written to a parcel, the start time is reset, as is mNesting in the base class
2086 * StopwatchTimer.
2087 */
2088 long mStartTimeMs = -1;
2089
2090 /**
Bookatz867c0d72017-03-07 18:23:42 -08002091 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002092 */
2093 long mMaxDurationMs;
2094
2095 /**
Bookatz867c0d72017-03-07 18:23:42 -08002096 * The time (in ms) that that the timer has been active since most recent
2097 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002098 */
2099 long mCurrentDurationMs;
2100
Bookatz867c0d72017-03-07 18:23:42 -08002101 /**
2102 * The total time (in ms) that that the timer has been active since most recent reset()
2103 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2104 * (but not including the present currentDuration) since reset. Not pooled.
2105 */
2106 long mTotalDurationMs;
2107
Joe Onorato92fd23f2016-07-25 11:18:42 -07002108 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2109 TimeBase timeBase, Parcel in) {
2110 super(clocks, uid, type, timerPool, timeBase, in);
2111 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002112 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002113 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002114 }
2115
2116 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2117 TimeBase timeBase) {
2118 super(clocks, uid, type, timerPool, timeBase);
2119 }
2120
2121 @Override
2122 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2123 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002124 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002125 out.writeLong(mTotalDurationMs);
2126 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002127 }
2128
2129 /**
2130 * Write the summary to the parcel.
2131 *
2132 * Since the time base is probably meaningless after we come back, reading
2133 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002134 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002135 */
2136 @Override
2137 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2138 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002139 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002140 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002141 }
2142
2143 /**
2144 * Read the summary parcel.
2145 *
2146 * Has the side effect of stopping the timer.
2147 */
2148 @Override
2149 public void readSummaryFromParcelLocked(Parcel in) {
2150 super.readSummaryFromParcelLocked(in);
2151 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002152 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002153 mStartTimeMs = -1;
2154 mCurrentDurationMs = 0;
2155 }
2156
2157 /**
2158 * The TimeBase time started (again).
2159 *
2160 * If the timer is also running, store the start time.
2161 */
2162 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2163 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2164 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002165 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002166 }
2167 }
2168
2169 /**
2170 * The TimeBase stopped running.
2171 *
2172 * If the timer is running, add the duration into mCurrentDurationMs.
2173 */
2174 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002175 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2176 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002177 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002178 // baseRealtimeUs has already been converted to the timebase's realtime.
2179 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002180 }
2181 mStartTimeMs = -1;
2182 }
2183
2184 @Override
2185 public void logState(Printer pw, String prefix) {
2186 super.logState(pw, prefix);
2187 }
2188
2189 @Override
2190 public void startRunningLocked(long elapsedRealtimeMs) {
2191 super.startRunningLocked(elapsedRealtimeMs);
2192 if (mNesting == 1 && mTimeBase.isRunning()) {
2193 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002194 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002195 }
2196 }
2197
2198 /**
2199 * Decrements the mNesting ref-count on this timer.
2200 *
2201 * If it actually stopped (mNesting went to 0), then possibly update
2202 * mMaxDuration if the current duration was the longest ever.
2203 */
2204 @Override
2205 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002206 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002207 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002208 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002209 if (durationMs > mMaxDurationMs) {
2210 mMaxDurationMs = durationMs;
2211 }
2212 mStartTimeMs = -1;
2213 mCurrentDurationMs = 0;
2214 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002215 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2216 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2217 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002218 }
2219
2220 @Override
2221 public boolean reset(boolean detachIfReset) {
2222 boolean result = super.reset(detachIfReset);
2223 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002224 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002225 mCurrentDurationMs = 0;
2226 if (mNesting > 0) {
2227 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2228 } else {
2229 mStartTimeMs = -1;
2230 }
2231 return result;
2232 }
2233
2234 /**
2235 * Returns the max duration that this timer has ever seen.
2236 *
2237 * Note that this time is NOT split between the timers in the timer group that
2238 * this timer is attached to. It is the TOTAL time.
2239 */
2240 @Override
2241 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2242 if (mNesting > 0) {
2243 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2244 if (durationMs > mMaxDurationMs) {
2245 return durationMs;
2246 }
2247 }
2248 return mMaxDurationMs;
2249 }
2250
2251 /**
2252 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002253 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002254 *
2255 * Note that this time is NOT split between the timers in the timer group that
2256 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002257 *
2258 * Note that if running timer is parceled and unparceled, this method will return
2259 * current duration value at the time of parceling even though timer may not be
2260 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002261 */
2262 @Override
2263 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2264 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002265 if (mNesting > 0 && mTimeBase.isRunning()) {
2266 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2267 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002268 }
2269 return durationMs;
2270 }
Bookatz867c0d72017-03-07 18:23:42 -08002271
2272 /**
2273 * Returns the total cumulative duration that this timer has been on since reset().
2274 * If mTimerPool == null, this should be the same
2275 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2276 *
2277 * Note that this time is NOT split between the timers in the timer group that
2278 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2279 * the result will not be equivalent to getTotalTimeLocked.
2280 */
2281 @Override
2282 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2283 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2284 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002285 }
2286
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002287 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002288 * State for keeping track of timing information.
2289 */
Joe Onoratoabded112016-02-08 16:49:39 -08002290 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002291 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002292 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002293
Evan Millarc64edde2009-04-18 12:26:32 -07002294 int mNesting;
2295
Evan Millarc64edde2009-04-18 12:26:32 -07002296 /**
2297 * The last time at which we updated the timer. If mNesting is > 0,
2298 * subtract this from the current battery time to find the amount of
2299 * time we have been running since we last computed an update.
2300 */
2301 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002302
Evan Millarc64edde2009-04-18 12:26:32 -07002303 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002304 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002305 * was actually held for an interesting duration. If time base was not running when timer
2306 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002307 */
Bookatzceebafe2017-04-06 11:59:13 -07002308 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002309
Amith Yamasanif37447b2009-10-08 18:28:01 -07002310 long mTimeout;
2311
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002312 /**
2313 * For partial wake locks, keep track of whether we are in the list
2314 * to consume CPU cycles.
2315 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002316 @VisibleForTesting
2317 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002318
Joe Onoratoabded112016-02-08 16:49:39 -08002319 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002320 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002321 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002322 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002323 mTimerPool = timerPool;
2324 mUpdateTime = in.readLong();
2325 }
2326
Joe Onoratoabded112016-02-08 16:49:39 -08002327 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002328 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002329 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002330 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002331 mTimerPool = timerPool;
2332 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002333
Joe Onoratoabded112016-02-08 16:49:39 -08002334 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002335 mTimeout = timeout;
2336 }
2337
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002338 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2339 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002340 out.writeLong(mUpdateTime);
2341 }
2342
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002343 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002344 if (mNesting > 0) {
2345 if (DEBUG && mType < 0) {
2346 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2347 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002348 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2349 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002350 if (DEBUG && mType < 0) {
2351 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2352 }
2353 }
2354 }
2355
2356 public void logState(Printer pw, String prefix) {
2357 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002358 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 + " mAcquireTime=" + mAcquireTime);
2360 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002361
Joe Onoratoabded112016-02-08 16:49:39 -08002362 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002364 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002365 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 if (mTimerPool != null) {
2367 // Accumulate time to all currently active timers before adding
2368 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002369 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 // Add this timer to the active pool
2371 mTimerPool.add(this);
2372 }
Bookatzceebafe2017-04-06 11:59:13 -07002373 if (mTimeBase.isRunning()) {
2374 // Increment the count
2375 mCount++;
2376 mAcquireTime = mTotalTime;
2377 } else {
2378 mAcquireTime = -1;
2379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 if (DEBUG && mType < 0) {
2381 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2382 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2383 + " mAcquireTime=" + mAcquireTime);
2384 }
2385 }
2386 }
2387
Joe Onoratoabded112016-02-08 16:49:39 -08002388 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002389 return mNesting > 0;
2390 }
2391
Joe Onoratoabded112016-02-08 16:49:39 -08002392 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002393 // Ignore attempt to stop a timer that isn't running
2394 if (mNesting == 0) {
2395 return;
2396 }
2397 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002398 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002399 if (mTimerPool != null) {
2400 // Accumulate time to all active counters, scaled by the total
2401 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002402 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002403 // Remove this timer from the active pool
2404 mTimerPool.remove(this);
2405 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 mNesting = 1;
2407 mTotalTime = computeRunTimeLocked(batteryRealtime);
2408 mNesting = 0;
2409 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 if (DEBUG && mType < 0) {
2412 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2413 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2414 + " mAcquireTime=" + mAcquireTime);
2415 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002416
Bookatzceebafe2017-04-06 11:59:13 -07002417 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 // If there was no change in the time, then discard this
2419 // count. A somewhat cheezy strategy, but hey.
2420 mCount--;
2421 }
2422 }
2423 }
2424
Joe Onoratoabded112016-02-08 16:49:39 -08002425 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002426 if (mNesting > 0) {
2427 mNesting = 1;
2428 stopRunningLocked(elapsedRealtimeMs);
2429 }
2430 }
2431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 // Update the total time for all other running Timers with the same type as this Timer
2433 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002434 private static long refreshTimersLocked(long batteryRealtime,
2435 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002436 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 final int N = pool.size();
2438 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002439 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 long heldTime = batteryRealtime - t.mUpdateTime;
2441 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002442 final long myTime = heldTime / N;
2443 if (t == self) {
2444 selfTime = myTime;
2445 }
2446 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 }
2448 t.mUpdateTime = batteryRealtime;
2449 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002450 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 }
2452
Evan Millarc64edde2009-04-18 12:26:32 -07002453 @Override
2454 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002455 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2456 curBatteryRealtime = mUpdateTime + mTimeout;
2457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 return mTotalTime + (mNesting > 0
2459 ? (curBatteryRealtime - mUpdateTime)
2460 / (mTimerPool != null ? mTimerPool.size() : 1)
2461 : 0);
2462 }
2463
Evan Millarc64edde2009-04-18 12:26:32 -07002464 @Override
2465 protected int computeCurrentCountLocked() {
2466 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 }
2468
Adam Lesinskie08af192015-03-25 16:42:59 -07002469 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002470 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002471 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002472 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002473 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002474 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002475 }
Bookatzceebafe2017-04-06 11:59:13 -07002476 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002477 return canDetach;
2478 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002479
Adam Lesinskie08af192015-03-25 16:42:59 -07002480 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002481 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002482 super.detach();
2483 if (mTimerPool != null) {
2484 mTimerPool.remove(this);
2485 }
2486 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002487
Adam Lesinskie08af192015-03-25 16:42:59 -07002488 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002489 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002490 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 mNesting = 0;
2492 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002493
2494 /**
2495 * Set the mark so that we can query later for the total time the timer has
2496 * accumulated since this point. The timer can be running or not.
2497 *
2498 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2499 */
2500 public void setMark(long elapsedRealtimeMs) {
2501 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2502 if (mNesting > 0) {
2503 // We are running.
2504 if (mTimerPool != null) {
2505 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2506 } else {
2507 mTotalTime += batteryRealtime - mUpdateTime;
2508 mUpdateTime = batteryRealtime;
2509 }
2510 }
2511 mTimeBeforeMark = mTotalTime;
2512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002514
Bookatz867c0d72017-03-07 18:23:42 -08002515 /**
2516 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2517 * TimeBase is effectively a subset of the other.
2518 */
Bookatzaa4594a2017-03-24 12:39:56 -07002519 public static class DualTimer extends DurationTimer {
2520 // This class both is a DurationTimer and also holds a second DurationTimer.
2521 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2522 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2523 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002524 // mSubTimer typically tracks only part of the total time, such as background time, as
2525 // determined by a subTimeBase. It is NOT pooled.
2526 private final DurationTimer mSubTimer;
2527
2528 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002529 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2530 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002531 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002532 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002533 */
2534 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2535 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002536 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002537 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2538 }
2539
2540 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002541 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2542 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002543 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002544 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002545 */
2546 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2547 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002548 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002549 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2550 }
2551
Bookatz867c0d72017-03-07 18:23:42 -08002552 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002553 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002554 public DurationTimer getSubTimer() {
2555 return mSubTimer;
2556 }
2557
Bookatzaa4594a2017-03-24 12:39:56 -07002558 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002559 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002560 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002561 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2562 }
2563
Bookatzaa4594a2017-03-24 12:39:56 -07002564 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002565 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002566 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002567 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2568 }
2569
Bookatzaa4594a2017-03-24 12:39:56 -07002570 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002571 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002572 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002573 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2574 }
2575
Bookatzaa4594a2017-03-24 12:39:56 -07002576 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002577 public boolean reset(boolean detachIfReset) {
2578 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002579 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2580 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002581 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002582 return !active;
2583 }
2584
Bookatzaa4594a2017-03-24 12:39:56 -07002585 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002586 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002587 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002588 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002589 }
2590
Bookatzaa4594a2017-03-24 12:39:56 -07002591 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002592 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002593 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002594 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2595 }
2596
Bookatzaa4594a2017-03-24 12:39:56 -07002597 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002598 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002599 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002600 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2601 }
2602
Bookatzaa4594a2017-03-24 12:39:56 -07002603 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002604 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002605 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002606 mSubTimer.readSummaryFromParcelLocked(in);
2607 }
2608 }
2609
2610
Dianne Hackbornd953c532014-08-16 18:17:38 -07002611 public abstract class OverflowArrayMap<T> {
2612 private static final String OVERFLOW_NAME = "*overflow*";
2613
Dianne Hackborn657153b2016-07-29 14:54:14 -07002614 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002615 final ArrayMap<String, T> mMap = new ArrayMap<>();
2616 T mCurOverflow;
2617 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002618 long mLastOverflowTime;
2619 long mLastOverflowFinishTime;
2620 long mLastClearTime;
2621 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002622
Dianne Hackborn657153b2016-07-29 14:54:14 -07002623 public OverflowArrayMap(int uid) {
2624 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002625 }
2626
2627 public ArrayMap<String, T> getMap() {
2628 return mMap;
2629 }
2630
2631 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002632 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002633 mMap.clear();
2634 mCurOverflow = null;
2635 mActiveOverflow = null;
2636 }
2637
2638 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002639 if (name == null) {
2640 name = "";
2641 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002642 mMap.put(name, obj);
2643 if (OVERFLOW_NAME.equals(name)) {
2644 mCurOverflow = obj;
2645 }
2646 }
2647
2648 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002649 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002650 if (mActiveOverflow != null) {
2651 if (mActiveOverflow.size() == 0) {
2652 mActiveOverflow = null;
2653 }
2654 }
2655 if (mActiveOverflow == null) {
2656 // There is no currently active overflow, so we should no longer have
2657 // an overflow entry.
2658 if (mMap.containsKey(OVERFLOW_NAME)) {
2659 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2660 + mMap.get(OVERFLOW_NAME));
2661 mMap.remove(OVERFLOW_NAME);
2662 }
2663 mCurOverflow = null;
2664 } else {
2665 // There is currently active overflow, so we should still have an overflow entry.
2666 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2667 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2668 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2669 }
2670 }
2671 }
2672
2673 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002674 if (name == null) {
2675 name = "";
2676 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002677 T obj = mMap.get(name);
2678 if (obj != null) {
2679 return obj;
2680 }
2681
2682 // No object exists for the given name, but do we currently have it
2683 // running as part of the overflow?
2684 if (mActiveOverflow != null) {
2685 MutableInt over = mActiveOverflow.get(name);
2686 if (over != null) {
2687 // We are already actively counting this name in the overflow object.
2688 obj = mCurOverflow;
2689 if (obj == null) {
2690 // Shouldn't be here, but we'll try to recover.
2691 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2692 obj = mCurOverflow = instantiateObject();
2693 mMap.put(OVERFLOW_NAME, obj);
2694 }
2695 over.value++;
2696 return obj;
2697 }
2698 }
2699
2700 // No object exists for given name nor in the overflow; we need to make
2701 // a new one.
2702 final int N = mMap.size();
2703 if (N >= MAX_WAKELOCKS_PER_UID) {
2704 // Went over the limit on number of objects to track; this one goes
2705 // in to the overflow.
2706 obj = mCurOverflow;
2707 if (obj == null) {
2708 // Need to start overflow now...
2709 obj = mCurOverflow = instantiateObject();
2710 mMap.put(OVERFLOW_NAME, obj);
2711 }
2712 if (mActiveOverflow == null) {
2713 mActiveOverflow = new ArrayMap<>();
2714 }
2715 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002716 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002717 return obj;
2718 }
2719
2720 // Normal case where we just need to make a new object.
2721 obj = instantiateObject();
2722 mMap.put(name, obj);
2723 return obj;
2724 }
2725
2726 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002727 if (name == null) {
2728 name = "";
2729 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002730 T obj = mMap.get(name);
2731 if (obj != null) {
2732 return obj;
2733 }
2734
2735 // No object exists for the given name, but do we currently have it
2736 // running as part of the overflow?
2737 if (mActiveOverflow != null) {
2738 MutableInt over = mActiveOverflow.get(name);
2739 if (over != null) {
2740 // We are already actively counting this name in the overflow object.
2741 obj = mCurOverflow;
2742 if (obj != null) {
2743 over.value--;
2744 if (over.value <= 0) {
2745 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002746 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002747 }
2748 return obj;
2749 }
2750 }
2751 }
2752
2753 // Huh, they are stopping an active operation but we can't find one!
2754 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002755 StringBuilder sb = new StringBuilder();
2756 sb.append("Unable to find object for ");
2757 sb.append(name);
2758 sb.append(" in uid ");
2759 sb.append(mUid);
2760 sb.append(" mapsize=");
2761 sb.append(mMap.size());
2762 sb.append(" activeoverflow=");
2763 sb.append(mActiveOverflow);
2764 sb.append(" curoverflow=");
2765 sb.append(mCurOverflow);
2766 long now = SystemClock.elapsedRealtime();
2767 if (mLastOverflowTime != 0) {
2768 sb.append(" lastOverflowTime=");
2769 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2770 }
2771 if (mLastOverflowFinishTime != 0) {
2772 sb.append(" lastOverflowFinishTime=");
2773 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2774 }
2775 if (mLastClearTime != 0) {
2776 sb.append(" lastClearTime=");
2777 TimeUtils.formatDuration(mLastClearTime-now, sb);
2778 }
2779 if (mLastCleanupTime != 0) {
2780 sb.append(" lastCleanupTime=");
2781 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2782 }
2783 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002784 return null;
2785 }
2786
2787 public abstract T instantiateObject();
2788 }
2789
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002790 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2791 implements Parcelable {
2792 private final LongSamplingCounter mIdleTimeMillis;
Siddharth Rayb50a6842017-12-14 15:15:28 -08002793 private final LongSamplingCounter mScanTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002794 private final LongSamplingCounter mRxTimeMillis;
2795 private final LongSamplingCounter[] mTxTimeMillis;
2796 private final LongSamplingCounter mPowerDrainMaMs;
2797
2798 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2799 mIdleTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002800 mScanTimeMillis = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002801 mRxTimeMillis = new LongSamplingCounter(timeBase);
2802 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2803 for (int i = 0; i < numTxStates; i++) {
2804 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2805 }
2806 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2807 }
2808
2809 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2810 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002811 mScanTimeMillis = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002812 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2813 final int recordedTxStates = in.readInt();
2814 if (recordedTxStates != numTxStates) {
2815 throw new ParcelFormatException("inconsistent tx state lengths");
2816 }
2817
2818 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2819 for (int i = 0; i < numTxStates; i++) {
2820 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2821 }
2822 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2823 }
2824
2825 public void readSummaryFromParcel(Parcel in) {
2826 mIdleTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002827 mScanTimeMillis.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002828 mRxTimeMillis.readSummaryFromParcelLocked(in);
2829 final int recordedTxStates = in.readInt();
2830 if (recordedTxStates != mTxTimeMillis.length) {
2831 throw new ParcelFormatException("inconsistent tx state lengths");
2832 }
2833 for (LongSamplingCounter counter : mTxTimeMillis) {
2834 counter.readSummaryFromParcelLocked(in);
2835 }
2836 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2837 }
2838
2839 @Override
2840 public int describeContents() {
2841 return 0;
2842 }
2843
2844 public void writeSummaryToParcel(Parcel dest) {
2845 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002846 mScanTimeMillis.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002847 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2848 dest.writeInt(mTxTimeMillis.length);
2849 for (LongSamplingCounter counter : mTxTimeMillis) {
2850 counter.writeSummaryFromParcelLocked(dest);
2851 }
2852 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2853 }
2854
2855 @Override
2856 public void writeToParcel(Parcel dest, int flags) {
2857 mIdleTimeMillis.writeToParcel(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002858 mScanTimeMillis.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002859 mRxTimeMillis.writeToParcel(dest);
2860 dest.writeInt(mTxTimeMillis.length);
2861 for (LongSamplingCounter counter : mTxTimeMillis) {
2862 counter.writeToParcel(dest);
2863 }
2864 mPowerDrainMaMs.writeToParcel(dest);
2865 }
2866
2867 public void reset(boolean detachIfReset) {
2868 mIdleTimeMillis.reset(detachIfReset);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002869 mScanTimeMillis.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002870 mRxTimeMillis.reset(detachIfReset);
2871 for (LongSamplingCounter counter : mTxTimeMillis) {
2872 counter.reset(detachIfReset);
2873 }
2874 mPowerDrainMaMs.reset(detachIfReset);
2875 }
2876
2877 public void detach() {
2878 mIdleTimeMillis.detach();
Siddharth Rayb50a6842017-12-14 15:15:28 -08002879 mScanTimeMillis.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002880 mRxTimeMillis.detach();
2881 for (LongSamplingCounter counter : mTxTimeMillis) {
2882 counter.detach();
2883 }
2884 mPowerDrainMaMs.detach();
2885 }
2886
2887 /**
2888 * @return a LongSamplingCounter, measuring time spent in the idle state in
2889 * milliseconds.
2890 */
2891 @Override
2892 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07002893 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002894 }
2895
2896 /**
Siddharth Rayb50a6842017-12-14 15:15:28 -08002897 * @return a LongSamplingCounter, measuring time spent in the scan state in
2898 * milliseconds.
2899 */
2900 @Override
2901 public LongSamplingCounter getScanTimeCounter() {
2902 return mScanTimeMillis;
2903 }
2904
2905 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002906 * @return a LongSamplingCounter, measuring time spent in the receive state in
2907 * milliseconds.
2908 */
2909 @Override
2910 public LongSamplingCounter getRxTimeCounter() {
2911 return mRxTimeMillis;
2912 }
2913
2914 /**
2915 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
2916 * milliseconds.
2917 */
2918 @Override
2919 public LongSamplingCounter[] getTxTimeCounters() {
2920 return mTxTimeMillis;
2921 }
2922
2923 /**
2924 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
2925 */
2926 @Override
2927 public LongSamplingCounter getPowerCounter() {
2928 return mPowerDrainMaMs;
2929 }
2930 }
2931
Bookatz50df7112017-08-04 14:53:26 -07002932 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
2933 public SamplingTimer getRpmTimerLocked(String name) {
2934 SamplingTimer rpmt = mRpmStats.get(name);
2935 if (rpmt == null) {
2936 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2937 mRpmStats.put(name, rpmt);
2938 }
2939 return rpmt;
2940 }
2941
2942 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
2943 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
2944 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
2945 if (rpmt == null) {
2946 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
2947 mScreenOffRpmStats.put(name, rpmt);
2948 }
2949 return rpmt;
2950 }
2951
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002952 /*
2953 * Get the wakeup reason counter, and create a new one if one
2954 * doesn't already exist.
2955 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002956 public SamplingTimer getWakeupReasonTimerLocked(String name) {
2957 SamplingTimer timer = mWakeupReasonStats.get(name);
2958 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002959 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002960 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002961 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002962 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002963 }
2964
Evan Millarc64edde2009-04-18 12:26:32 -07002965 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002966 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07002967 * doesn't already exist.
2968 */
2969 public SamplingTimer getKernelWakelockTimerLocked(String name) {
2970 SamplingTimer kwlt = mKernelWakelockStats.get(name);
2971 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002972 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07002973 mKernelWakelockStats.put(name, kwlt);
2974 }
2975 return kwlt;
2976 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07002977
James Carr3a226052016-07-01 14:49:52 -07002978 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
2979 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
2980 if (kmt == null) {
2981 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2982 mKernelMemoryStats.put(bucket, kmt);
2983 }
2984 return kmt;
2985 }
2986
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002987 private int writeHistoryTag(HistoryTag tag) {
2988 Integer idxObj = mHistoryTagPool.get(tag);
2989 int idx;
2990 if (idxObj != null) {
2991 idx = idxObj;
2992 } else {
2993 idx = mNextHistoryTagIdx;
2994 HistoryTag key = new HistoryTag();
2995 key.setTo(tag);
2996 tag.poolIdx = idx;
2997 mHistoryTagPool.put(key, idx);
2998 mNextHistoryTagIdx++;
2999 mNumHistoryTagChars += key.string.length() + 1;
3000 }
3001 return idx;
3002 }
3003
3004 private void readHistoryTag(int index, HistoryTag tag) {
3005 tag.string = mReadHistoryStrings[index];
3006 tag.uid = mReadHistoryUids[index];
3007 tag.poolIdx = index;
3008 }
3009
Adam Lesinski926969b2016-04-28 17:31:12 -07003010 /*
3011 The history delta format uses flags to denote further data in subsequent ints in the parcel.
3012
3013 There is always the first token, which may contain the delta time, or an indicator of
3014 the length of the time (int or long) following this token.
3015
3016 First token: always present,
3017 31 23 15 7 0
3018 â–ˆ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â–ˆ
3019
3020 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
3021 follows containing the time, and 0x7ffff indicates a long immediately follows with the
3022 delta time.
3023 A: battery level changed and an int follows with battery data.
3024 B: state changed and an int follows with state change data.
3025 C: state2 has changed and an int follows with state2 change data.
3026 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
3027 E: event data has changed and an event struct follows.
3028 F: battery charge in coulombs has changed and an int with the charge follows.
3029 G: state flag denoting that the mobile radio was active.
3030 H: state flag denoting that the wifi radio was active.
3031 I: state flag denoting that a wifi scan occurred.
3032 J: state flag denoting that a wifi full lock was held.
3033 K: state flag denoting that the gps was on.
3034 L: state flag denoting that a wakelock was held.
3035 M: state flag denoting that the cpu was running.
3036
3037 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3038 with the time delta.
3039
3040 Battery level int: if A in the first token is set,
3041 31 23 15 7 0
3042 â–ˆ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â–ˆ
3043
3044 D: indicates that extra history details follow.
3045 V: the battery voltage.
3046 T: the battery temperature.
3047 L: the battery level (out of 100).
3048
3049 State change int: if B in the first token is set,
3050 31 23 15 7 0
3051 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3052
3053 A: wifi multicast was on.
3054 B: battery was plugged in.
3055 C: screen was on.
3056 D: phone was scanning for signal.
3057 E: audio was on.
3058 F: a sensor was active.
3059
3060 State2 change int: if C in the first token is set,
3061 31 23 15 7 0
3062 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3063
3064 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3065 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3066 C: a bluetooth scan was active.
3067 D: the camera was active.
3068 E: bluetooth was on.
3069 F: a phone call was active.
3070 G: the device was charging.
3071 H: 2 bits indicating the device-idle (doze) state: off, light, full
3072 I: the flashlight was on.
3073 J: wifi was on.
3074 K: wifi was running.
3075 L: video was playing.
3076 M: power save mode was on.
3077
3078 Wakelock/wakereason struct: if D in the first token is set,
3079 TODO(adamlesinski): describe wakelock/wakereason struct.
3080
3081 Event struct: if E in the first token is set,
3082 TODO(adamlesinski): describe the event struct.
3083
3084 History step details struct: if D in the battery level int is set,
3085 TODO(adamlesinski): describe the history step details struct.
3086
3087 Battery charge int: if F in the first token is set, an int representing the battery charge
3088 in coulombs follows.
3089 */
3090
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003091 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003092 static final int DELTA_TIME_MASK = 0x7ffff;
3093 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3094 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3095 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003096 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003097 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003098 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003099 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003100 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003101 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003102 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003103 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003104 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003105 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003106 // Flag in delta int: contains the battery charge count in uAh.
3107 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003108 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003109 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003110
3111 // These are the pieces of battery state that are packed in to the upper bits of
3112 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003113 // in STATE_BATTERY_MASK.
3114 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003115 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3116 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3117 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3118 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3119 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3120 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003121
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003122 // We use the low bit of the battery state int to indicate that we have full details
3123 // from a battery level change.
3124 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3125
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003126 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003127 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003128 dest.writeInt(DELTA_TIME_ABS);
3129 cur.writeToParcel(dest, 0);
3130 return;
3131 }
3132
3133 final long deltaTime = cur.time - last.time;
3134 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3135 final int lastStateInt = buildStateInt(last);
3136
3137 int deltaTimeToken;
3138 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3139 deltaTimeToken = DELTA_TIME_LONG;
3140 } else if (deltaTime >= DELTA_TIME_ABS) {
3141 deltaTimeToken = DELTA_TIME_INT;
3142 } else {
3143 deltaTimeToken = (int)deltaTime;
3144 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003145 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003146 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3147 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3148 final boolean computeStepDetails = includeStepDetails != 0
3149 || mLastHistoryStepDetails == null;
3150 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003151 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3152 if (batteryLevelIntChanged) {
3153 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3154 }
3155 final int stateInt = buildStateInt(cur);
3156 final boolean stateIntChanged = stateInt != lastStateInt;
3157 if (stateIntChanged) {
3158 firstToken |= DELTA_STATE_FLAG;
3159 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003160 final boolean state2IntChanged = cur.states2 != last.states2;
3161 if (state2IntChanged) {
3162 firstToken |= DELTA_STATE2_FLAG;
3163 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003164 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003165 firstToken |= DELTA_WAKELOCK_FLAG;
3166 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003167 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3168 firstToken |= DELTA_EVENT_FLAG;
3169 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003170
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003171 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3172 if (batteryChargeChanged) {
3173 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003174 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003175 dest.writeInt(firstToken);
3176 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3177 + " deltaTime=" + deltaTime);
3178
3179 if (deltaTimeToken >= DELTA_TIME_INT) {
3180 if (deltaTimeToken == DELTA_TIME_INT) {
3181 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3182 dest.writeInt((int)deltaTime);
3183 } else {
3184 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3185 dest.writeLong(deltaTime);
3186 }
3187 }
3188 if (batteryLevelIntChanged) {
3189 dest.writeInt(batteryLevelInt);
3190 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3191 + Integer.toHexString(batteryLevelInt)
3192 + " batteryLevel=" + cur.batteryLevel
3193 + " batteryTemp=" + cur.batteryTemperature
3194 + " batteryVolt=" + (int)cur.batteryVoltage);
3195 }
3196 if (stateIntChanged) {
3197 dest.writeInt(stateInt);
3198 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3199 + Integer.toHexString(stateInt)
3200 + " batteryStatus=" + cur.batteryStatus
3201 + " batteryHealth=" + cur.batteryHealth
3202 + " batteryPlugType=" + cur.batteryPlugType
3203 + " states=0x" + Integer.toHexString(cur.states));
3204 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003205 if (state2IntChanged) {
3206 dest.writeInt(cur.states2);
3207 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3208 + Integer.toHexString(cur.states2));
3209 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003210 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3211 int wakeLockIndex;
3212 int wakeReasonIndex;
3213 if (cur.wakelockTag != null) {
3214 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3215 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3216 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3217 } else {
3218 wakeLockIndex = 0xffff;
3219 }
3220 if (cur.wakeReasonTag != null) {
3221 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3222 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3223 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3224 } else {
3225 wakeReasonIndex = 0xffff;
3226 }
3227 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003228 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003229 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003230 int index = writeHistoryTag(cur.eventTag);
3231 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003232 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003233 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3234 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3235 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003236 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003237 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003238 if (mPlatformIdleStateCallback != null) {
3239 mCurHistoryStepDetails.statPlatformIdleState =
3240 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3241 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3242 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003243
3244 mCurHistoryStepDetails.statSubsystemPowerState =
3245 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3246 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3247 mCurHistoryStepDetails.statSubsystemPowerState);
3248
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003249 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003250 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3251 if (includeStepDetails != 0) {
3252 mCurHistoryStepDetails.writeToParcel(dest);
3253 }
3254 cur.stepDetails = mCurHistoryStepDetails;
3255 mLastHistoryStepDetails = mCurHistoryStepDetails;
3256 } else {
3257 cur.stepDetails = null;
3258 }
3259 if (mLastHistoryStepLevel < cur.batteryLevel) {
3260 mLastHistoryStepDetails = null;
3261 }
3262 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003263
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003264 if (batteryChargeChanged) {
3265 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3266 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003267 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003268 }
3269
3270 private int buildBatteryLevelInt(HistoryItem h) {
3271 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003272 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3273 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3274 }
3275
3276 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3277 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3278 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3279 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003280 }
3281
3282 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003283 int plugType = 0;
3284 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3285 plugType = 1;
3286 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3287 plugType = 2;
3288 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3289 plugType = 3;
3290 }
3291 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3292 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3293 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003294 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003295 }
3296
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003297 private void computeHistoryStepDetails(final HistoryStepDetails out,
3298 final HistoryStepDetails last) {
3299 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3300
3301 // Perform a CPU update right after we do this collection, so we have started
3302 // collecting good data for the next step.
3303 requestImmediateCpuUpdate();
3304
3305 if (last == null) {
3306 // We are not generating a delta, so all we need to do is reset the stats
3307 // we will later be doing a delta from.
3308 final int NU = mUidStats.size();
3309 for (int i=0; i<NU; i++) {
3310 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3311 uid.mLastStepUserTime = uid.mCurStepUserTime;
3312 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3313 }
3314 mLastStepCpuUserTime = mCurStepCpuUserTime;
3315 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3316 mLastStepStatUserTime = mCurStepStatUserTime;
3317 mLastStepStatSystemTime = mCurStepStatSystemTime;
3318 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3319 mLastStepStatIrqTime = mCurStepStatIrqTime;
3320 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3321 mLastStepStatIdleTime = mCurStepStatIdleTime;
3322 tmp.clear();
3323 return;
3324 }
3325 if (DEBUG) {
3326 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3327 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3328 + " irq=" + mLastStepStatIrqTime + " sirq="
3329 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3330 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3331 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3332 + " irq=" + mCurStepStatIrqTime + " sirq="
3333 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3334 }
3335 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3336 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3337 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3338 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3339 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3340 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3341 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3342 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3343 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3344 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3345 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3346 final int NU = mUidStats.size();
3347 for (int i=0; i<NU; i++) {
3348 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3349 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3350 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3351 final int totalTime = totalUTime + totalSTime;
3352 uid.mLastStepUserTime = uid.mCurStepUserTime;
3353 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3354 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3355 continue;
3356 }
3357 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3358 out.appCpuUid3 = uid.mUid;
3359 out.appCpuUTime3 = totalUTime;
3360 out.appCpuSTime3 = totalSTime;
3361 } else {
3362 out.appCpuUid3 = out.appCpuUid2;
3363 out.appCpuUTime3 = out.appCpuUTime2;
3364 out.appCpuSTime3 = out.appCpuSTime2;
3365 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3366 out.appCpuUid2 = uid.mUid;
3367 out.appCpuUTime2 = totalUTime;
3368 out.appCpuSTime2 = totalSTime;
3369 } else {
3370 out.appCpuUid2 = out.appCpuUid1;
3371 out.appCpuUTime2 = out.appCpuUTime1;
3372 out.appCpuSTime2 = out.appCpuSTime1;
3373 out.appCpuUid1 = uid.mUid;
3374 out.appCpuUTime1 = totalUTime;
3375 out.appCpuSTime1 = totalSTime;
3376 }
3377 }
3378 }
3379 mLastStepCpuUserTime = mCurStepCpuUserTime;
3380 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3381 mLastStepStatUserTime = mCurStepStatUserTime;
3382 mLastStepStatSystemTime = mCurStepStatSystemTime;
3383 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3384 mLastStepStatIrqTime = mCurStepStatIrqTime;
3385 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3386 mLastStepStatIdleTime = mCurStepStatIdleTime;
3387 }
3388
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003389 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3390 int firstToken = src.readInt();
3391 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003392 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003393 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003394 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3395 + " deltaTimeToken=" + deltaTimeToken);
3396
3397 if (deltaTimeToken < DELTA_TIME_ABS) {
3398 cur.time += deltaTimeToken;
3399 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3400 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003401 cur.numReadInts += 2;
3402 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003403 cur.readFromParcel(src);
3404 return;
3405 } else if (deltaTimeToken == DELTA_TIME_INT) {
3406 int delta = src.readInt();
3407 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003408 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003409 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3410 } else {
3411 long delta = src.readLong();
3412 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3413 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003414 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003415 }
3416
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003417 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003418 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003419 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003420 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003421 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003422 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3423 + Integer.toHexString(batteryLevelInt)
3424 + " batteryLevel=" + cur.batteryLevel
3425 + " batteryTemp=" + cur.batteryTemperature
3426 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003427 } else {
3428 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003429 }
3430
3431 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3432 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003433 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003434 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3435 & STATE_BATTERY_STATUS_MASK);
3436 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3437 & STATE_BATTERY_HEALTH_MASK);
3438 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3439 & STATE_BATTERY_PLUG_MASK);
3440 switch (cur.batteryPlugType) {
3441 case 1:
3442 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3443 break;
3444 case 2:
3445 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3446 break;
3447 case 3:
3448 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3449 break;
3450 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003451 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003452 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3453 + Integer.toHexString(stateInt)
3454 + " batteryStatus=" + cur.batteryStatus
3455 + " batteryHealth=" + cur.batteryHealth
3456 + " batteryPlugType=" + cur.batteryPlugType
3457 + " states=0x" + Integer.toHexString(cur.states));
3458 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003459 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003460 }
3461
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003462 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3463 cur.states2 = src.readInt();
3464 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3465 + Integer.toHexString(cur.states2));
3466 }
3467
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003468 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003469 int indexes = src.readInt();
3470 int wakeLockIndex = indexes&0xffff;
3471 int wakeReasonIndex = (indexes>>16)&0xffff;
3472 if (wakeLockIndex != 0xffff) {
3473 cur.wakelockTag = cur.localWakelockTag;
3474 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3475 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3476 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3477 } else {
3478 cur.wakelockTag = null;
3479 }
3480 if (wakeReasonIndex != 0xffff) {
3481 cur.wakeReasonTag = cur.localWakeReasonTag;
3482 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3483 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3484 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3485 } else {
3486 cur.wakeReasonTag = null;
3487 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003488 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003489 } else {
3490 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003491 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003492 }
3493
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003494 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003495 cur.eventTag = cur.localEventTag;
3496 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003497 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003498 final int index = ((codeAndIndex>>16)&0xffff);
3499 readHistoryTag(index, cur.eventTag);
3500 cur.numReadInts += 1;
3501 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3502 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3503 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003504 } else {
3505 cur.eventCode = HistoryItem.EVENT_NONE;
3506 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003507
3508 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3509 cur.stepDetails = mReadHistoryStepDetails;
3510 cur.stepDetails.readFromParcel(src);
3511 } else {
3512 cur.stepDetails = null;
3513 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003514
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003515 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3516 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003517 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003518 }
3519
Dianne Hackbornfc064132014-06-02 12:42:12 -07003520 @Override
3521 public void commitCurrentHistoryBatchLocked() {
3522 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3523 }
3524
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003525 void addHistoryBufferLocked(long elapsedRealtimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003526 if (!mHaveBatteryLevel || !mRecordingHistory) {
3527 return;
3528 }
3529
Dianne Hackborn40c87252014-03-19 16:55:40 -07003530 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003531 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3532 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003533 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003534 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003535 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3536 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003537 + Integer.toHexString(lastDiffStates) + " diff2="
3538 + Integer.toHexString(diffStates2) + " lastDiff2="
3539 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003540 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003541 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003542 && (diffStates2&lastDiffStates2) == 0
3543 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3544 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003545 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003546 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003547 || cur.eventCode == HistoryItem.EVENT_NONE)
3548 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3549 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3550 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3551 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3552 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3553 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003554 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003555 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003556 // as long as no bit has changed both between now and the last entry, as
3557 // well as the last entry and the one before it (so we capture any toggles).
3558 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003559 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3560 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3561 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003562 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003563 // If the last written history had a wakelock tag, we need to retain it.
3564 // Note that the condition above made sure that we aren't in a case where
3565 // both it and the current history item have a wakelock tag.
3566 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003567 cur.wakelockTag = cur.localWakelockTag;
3568 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003569 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003570 // If the last written history had a wake reason tag, we need to retain it.
3571 // Note that the condition above made sure that we aren't in a case where
3572 // both it and the current history item have a wakelock tag.
3573 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003574 cur.wakeReasonTag = cur.localWakeReasonTag;
3575 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003576 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003577 // If the last written history had an event, we need to retain it.
3578 // Note that the condition above made sure that we aren't in a case where
3579 // both it and the current history item have an event.
3580 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003581 cur.eventCode = mHistoryLastWritten.eventCode;
3582 cur.eventTag = cur.localEventTag;
3583 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003584 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003585 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003586 }
3587
Adam Lesinski45489782016-12-15 23:45:17 -08003588 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003589 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003590 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3591 // Clients can't deal with history buffers this large. This only
3592 // really happens when the device is on charger and interacted with
3593 // for long periods of time, like in retail mode. Since the device is
3594 // most likely charged, when unplugged, stats would have reset anyways.
3595 // Reset the stats and mark that we overflowed.
3596 // b/32540341
3597 resetAllStatsLocked();
3598
3599 // Mark that we want to set *OVERFLOW* event and the RESET:START
3600 // events.
3601 recordResetDueToOverflow = true;
3602
3603 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003604 if (!mHistoryOverflow) {
3605 mHistoryOverflow = true;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003606 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
3607 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003608 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003609 }
3610
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003611 // After overflow, we allow various bit-wise states to settle to 0.
3612 boolean writeAnyway = false;
3613 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3614 & mActiveHistoryStates;
3615 if (mHistoryLastWritten.states != curStates) {
3616 // mActiveHistoryStates keeps track of which bits in .states are now being
3617 // forced to 0.
3618 int old = mActiveHistoryStates;
3619 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3620 writeAnyway |= old != mActiveHistoryStates;
3621 }
3622 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3623 & mActiveHistoryStates2;
3624 if (mHistoryLastWritten.states2 != curStates2) {
3625 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3626 // forced to 0.
3627 int old = mActiveHistoryStates2;
3628 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3629 writeAnyway |= old != mActiveHistoryStates2;
3630 }
3631
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003632 // Once we've reached the maximum number of items, we only
3633 // record changes to the battery level and the most interesting states.
3634 // Once we've reached the maximum maximum number of items, we only
3635 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003636 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003637 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003638 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003639 & HistoryItem.MOST_INTERESTING_STATES) == 0
3640 || ((mHistoryLastWritten.states2^cur.states2)
3641 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003642 return;
3643 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003644
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003645 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003646 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003647 }
3648
Adam Lesinski45489782016-12-15 23:45:17 -08003649 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003650 // The history is currently empty; we need it to start with a time stamp.
3651 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003652 if (recordResetDueToOverflow) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003653 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Adam Lesinski45489782016-12-15 23:45:17 -08003654 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003655 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_RESET, cur);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003656 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003657 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003658 }
3659
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003660 private void addHistoryBufferLocked(long elapsedRealtimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003661 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003662 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003663 }
3664 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3665 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003666 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003667 mHistoryLastWritten.states &= mActiveHistoryStates;
3668 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003669 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003670 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003671 cur.wakelockTag = null;
3672 cur.wakeReasonTag = null;
3673 cur.eventCode = HistoryItem.EVENT_NONE;
3674 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003675 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3676 + " now " + mHistoryBuffer.dataPosition()
3677 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003678 }
3679
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003680 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003681 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003682
Dianne Hackborn40c87252014-03-19 16:55:40 -07003683 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003684 if (mTrackRunningHistoryElapsedRealtime != 0) {
3685 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3686 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3687 if (diffUptime < (diffElapsed-20)) {
3688 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3689 mHistoryAddTmp.setTo(mHistoryLastWritten);
3690 mHistoryAddTmp.wakelockTag = null;
3691 mHistoryAddTmp.wakeReasonTag = null;
3692 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3693 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003694 addHistoryRecordInnerLocked(wakeElapsedTime, mHistoryAddTmp);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003695 }
3696 }
3697 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3698 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3699 mTrackRunningHistoryUptime = uptimeMs;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003700 addHistoryRecordInnerLocked(elapsedRealtimeMs, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003701 }
3702
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003703 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, HistoryItem cur) {
3704 addHistoryBufferLocked(elapsedRealtimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003705
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003706 if (!USE_OLD_HISTORY) {
3707 return;
3708 }
3709
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003710 if (!mHaveBatteryLevel || !mRecordingHistory) {
3711 return;
3712 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003713
3714 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003715 // and no states have since the last recorded entry changed and
3716 // are now resetting back to their original value, then just collapse
3717 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003718 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003719 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003720 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3721 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003722 // If the current is the same as the one before, then we no
3723 // longer need the entry.
3724 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003725 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003726 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003727 mHistoryLastEnd.next = null;
3728 mHistoryEnd.next = mHistoryCache;
3729 mHistoryCache = mHistoryEnd;
3730 mHistoryEnd = mHistoryLastEnd;
3731 mHistoryLastEnd = null;
3732 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003733 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3734 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003735 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003736 }
3737 return;
3738 }
3739
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003740 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003741 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003742
3743 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3744 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003745 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003746 }
3747
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003748 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3749 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003750 // record changes to the battery level and the most interesting states.
3751 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003752 // record changes to the battery level.
3753 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003754 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003755 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003756 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003757 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003758 return;
3759 }
3760 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003761
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003762 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003763 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003764
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003765 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003766 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003767 mHistoryCur.eventCode = code;
3768 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3769 mHistoryCur.eventTag.string = name;
3770 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003771 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003772 }
3773
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003774 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003775 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003776 if (rec != null) {
3777 mHistoryCache = rec.next;
3778 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003779 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003780 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003781 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003782
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003783 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003784 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003785
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003786 void addHistoryRecordLocked(HistoryItem rec) {
3787 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003788 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003789 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003790 if (mHistoryEnd != null) {
3791 mHistoryEnd.next = rec;
3792 mHistoryEnd = rec;
3793 } else {
3794 mHistory = mHistoryEnd = rec;
3795 }
3796 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003797
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003798 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003799 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003800 if (USE_OLD_HISTORY) {
3801 if (mHistory != null) {
3802 mHistoryEnd.next = mHistoryCache;
3803 mHistoryCache = mHistory;
3804 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3805 }
3806 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003807 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003808
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003809 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003810 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003811 mTrackRunningHistoryElapsedRealtime = 0;
3812 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003813
3814 mHistoryBuffer.setDataSize(0);
3815 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003816 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003817 mHistoryLastLastWritten.clear();
3818 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003819 mHistoryTagPool.clear();
3820 mNextHistoryTagIdx = 0;
3821 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003822 mHistoryBufferLastPos = -1;
3823 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003824 mActiveHistoryStates = 0xffffffff;
3825 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003826 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003827
Mike Mac2f518a2017-09-19 16:06:03 -07003828 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003829 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003830 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003831 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3832 final boolean updateOnBatteryScreenOffTimeBase =
3833 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003834
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003835 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3836 if (updateOnBatteryScreenOffTimeBase) {
3837 updateKernelWakelocksLocked();
3838 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003839 }
Bookatz82b341172017-09-07 19:06:08 -07003840 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3841 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3842 // improved, remove the surrounding if{}.
3843 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3844 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3845 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003846 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003847 Slog.d(TAG, "Updating cpu time because screen is now "
3848 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003849 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003850 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -07003851 updateCpuTimeLocked();
Sudheer Shankae544d162017-12-28 17:06:20 -08003852 mExternalSync.scheduleCopyFromAllUidsCpuTimes(mOnBatteryTimeBase.isRunning(),
3853 mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003854
3855 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07003856 if (updateOnBatteryTimeBase) {
3857 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3858 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003859 }
Mike Mac2f518a2017-09-19 16:06:03 -07003860 }
3861 if (updateOnBatteryScreenOffTimeBase) {
3862 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
3863 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3864 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003865 }
Bookatzc8c44962017-05-11 12:12:54 -07003866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 }
3868 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003869
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003870 private void updateBatteryPropertiesLocked() {
3871 try {
3872 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
3873 ServiceManager.getService("batteryproperties"));
3874 registrar.scheduleUpdate();
3875 } catch (RemoteException e) {
3876 // Ignore.
3877 }
3878 }
3879
Dianne Hackborn099bc622014-01-22 13:39:16 -08003880 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
3881 mIsolatedUids.put(isolatedUid, appUid);
Bookatz90867622018-01-31 15:05:57 -08003882 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid,
3883 StatsLog.ISOLATED_UID_CHANGED__EVENT__CREATED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003884 final Uid u = getUidStatsLocked(appUid);
3885 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003886 }
3887
Adam Lesinski61db88f2015-07-01 15:05:07 -07003888 /**
3889 * Schedules a read of the latest cpu times before removing the isolated UID.
3890 * @see #removeIsolatedUidLocked(int)
3891 */
3892 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003893 int curUid = mIsolatedUids.get(isolatedUid, -1);
3894 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07003895 if (mExternalSync != null) {
3896 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
3897 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08003898 }
3899 }
3900
Adam Lesinski61db88f2015-07-01 15:05:07 -07003901 /**
3902 * This should only be called after the cpu times have been read.
3903 * @see #scheduleRemoveIsolatedUidLocked(int, int)
3904 */
3905 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003906 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08003907 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1),
3908 isolatedUid, StatsLog.ISOLATED_UID_CHANGED__EVENT__REMOVED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003909 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
3910 if (idx >= 0) {
3911 final int ownerUid = mIsolatedUids.valueAt(idx);
3912 final Uid u = getUidStatsLocked(ownerUid);
3913 u.removeIsolatedUid(isolatedUid);
3914 mIsolatedUids.removeAt(idx);
3915 }
3916 mKernelUidCpuTimeReader.removeUid(isolatedUid);
3917 mKernelUidCpuFreqTimeReader.removeUid(isolatedUid);
Mike Mafae87da2018-01-19 20:07:20 -08003918 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
3919 mKernelUidCpuActiveTimeReader.removeUid(isolatedUid);
3920 mKernelUidCpuClusterTimeReader.removeUid(isolatedUid);
3921 }
Adam Lesinski61db88f2015-07-01 15:05:07 -07003922 }
3923
Dianne Hackborn099bc622014-01-22 13:39:16 -08003924 public int mapUid(int uid) {
3925 int isolated = mIsolatedUids.get(uid, -1);
3926 return isolated > 0 ? isolated : uid;
3927 }
3928
3929 public void noteEventLocked(int code, String name, int uid) {
3930 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003931 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3932 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003933 }
Joe Onoratoabded112016-02-08 16:49:39 -08003934 final long elapsedRealtime = mClocks.elapsedRealtime();
3935 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003936 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003937 }
3938
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003939 boolean ensureStartClockTime(final long currentTime) {
3940 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
3941 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
3942 // If the start clock time has changed by more than a year, then presumably
3943 // the previous time was completely bogus. So we are going to figure out a
3944 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08003945 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003946 return true;
3947 }
3948 return false;
3949 }
3950
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003951 public void noteCurrentTimeChangedLocked() {
3952 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003953 final long elapsedRealtime = mClocks.elapsedRealtime();
3954 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003955 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003956 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003957 }
3958
Dianne Hackborn61659e52014-07-09 16:13:01 -07003959 public void noteProcessStartLocked(String name, int uid) {
3960 uid = mapUid(uid);
3961 if (isOnBattery()) {
3962 Uid u = getUidStatsLocked(uid);
3963 u.getProcessStatsLocked(name).incStartsLocked();
3964 }
3965 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3966 return;
3967 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003968 if (!mRecordAllHistory) {
3969 return;
3970 }
Joe Onoratoabded112016-02-08 16:49:39 -08003971 final long elapsedRealtime = mClocks.elapsedRealtime();
3972 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07003973 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
3974 }
3975
Dianne Hackborn1e01d162014-12-04 17:46:42 -08003976 public void noteProcessCrashLocked(String name, int uid) {
3977 uid = mapUid(uid);
3978 if (isOnBattery()) {
3979 Uid u = getUidStatsLocked(uid);
3980 u.getProcessStatsLocked(name).incNumCrashesLocked();
3981 }
3982 }
3983
3984 public void noteProcessAnrLocked(String name, int uid) {
3985 uid = mapUid(uid);
3986 if (isOnBattery()) {
3987 Uid u = getUidStatsLocked(uid);
3988 u.getProcessStatsLocked(name).incNumAnrsLocked();
3989 }
3990 }
3991
Dianne Hackborna8d10942015-11-19 17:55:19 -08003992 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07003993 int parentUid = mapUid(uid);
3994 if (uid != parentUid) {
3995 // Isolated UIDs process state is already rolled up into parent, so no need to track
3996 // Otherwise the parent's process state will get downgraded incorrectly
3997 return;
3998 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08003999 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004000 }
4001
4002 public void noteProcessFinishLocked(String name, int uid) {
4003 uid = mapUid(uid);
4004 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4005 return;
4006 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004007 if (!mRecordAllHistory) {
4008 return;
4009 }
Joe Onoratoabded112016-02-08 16:49:39 -08004010 final long elapsedRealtime = mClocks.elapsedRealtime();
4011 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004012 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004013 }
4014
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004015 public void noteSyncStartLocked(String name, int uid) {
4016 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004017 final long elapsedRealtime = mClocks.elapsedRealtime();
4018 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004019 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4020 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4021 return;
4022 }
4023 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4024 }
4025
4026 public void noteSyncFinishLocked(String name, int uid) {
4027 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004028 final long elapsedRealtime = mClocks.elapsedRealtime();
4029 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004030 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4031 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4032 return;
4033 }
4034 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4035 }
4036
4037 public void noteJobStartLocked(String name, int uid) {
4038 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004039 final long elapsedRealtime = mClocks.elapsedRealtime();
4040 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004041 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4042 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4043 return;
4044 }
4045 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4046 }
4047
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004048 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004049 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004050 final long elapsedRealtime = mClocks.elapsedRealtime();
4051 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004052 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004053 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4054 return;
4055 }
4056 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4057 }
4058
Narayan Kamath695cf722017-12-21 18:32:47 +00004059 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4060 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004061 }
4062
Narayan Kamath695cf722017-12-21 18:32:47 +00004063 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4064 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4065 }
4066
4067 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4068 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004069 if (!mRecordAllHistory) {
4070 return;
4071 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004072
Joe Onoratoabded112016-02-08 16:49:39 -08004073 final long elapsedRealtime = mClocks.elapsedRealtime();
4074 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004075
4076 if (workSource != null) {
4077 for (int i = 0; i < workSource.size(); ++i) {
4078 uid = mapUid(workSource.get(i));
4079 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4080 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4081 }
4082 }
4083
4084 List<WorkChain> workChains = workSource.getWorkChains();
4085 if (workChains != null) {
4086 for (int i = 0; i < workChains.size(); ++i) {
4087 uid = mapUid(workChains.get(i).getAttributionUid());
4088 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4089 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4090 }
4091 }
4092 }
4093 } else {
4094 uid = mapUid(uid);
4095
4096 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4097 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4098 }
4099 }
4100 }
4101
4102 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4103 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004104 if (workSource != null) {
4105 for (int i = 0; i < workSource.size(); ++i) {
4106 uid = workSource.get(i);
4107 final String workSourceName = workSource.getName(i);
4108
Tej Singh6f724c42018-01-03 20:02:03 -08004109 if (isOnBattery()) {
4110 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4111 workSourceName != null ? workSourceName : packageName);
4112 pkg.noteWakeupAlarmLocked(tag);
4113 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004114 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4115 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004116 }
4117
4118 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4119 if (workChains != null) {
4120 for (int i = 0; i < workChains.size(); ++i) {
4121 final WorkChain wc = workChains.get(i);
4122 uid = wc.getAttributionUid();
4123
Tej Singh6f724c42018-01-03 20:02:03 -08004124 if (isOnBattery()) {
4125 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4126 pkg.noteWakeupAlarmLocked(tag);
4127 }
Yangster-macafad8c62018-01-05 22:30:49 -08004128 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004129 }
4130 }
4131 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004132 if (isOnBattery()) {
4133 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4134 pkg.noteWakeupAlarmLocked(tag);
4135 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004136 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004137 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004138 }
4139
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004140 private void requestWakelockCpuUpdate() {
4141 if (!mHandler.hasMessages(MSG_UPDATE_WAKELOCKS)) {
4142 Message m = mHandler.obtainMessage(MSG_UPDATE_WAKELOCKS);
4143 mHandler.sendMessageDelayed(m, DELAY_UPDATE_WAKELOCKS);
4144 }
4145 }
4146
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004147 private void requestImmediateCpuUpdate() {
4148 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
4149 mHandler.sendEmptyMessage(MSG_UPDATE_WAKELOCKS);
4150 }
4151
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004152 public void setRecordAllHistoryLocked(boolean enabled) {
4153 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004154 if (!enabled) {
4155 // Clear out any existing state.
4156 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004157 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004158 // Record the currently running processes as stopping, now that we are no
4159 // longer tracking them.
4160 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4161 HistoryItem.EVENT_PROC);
4162 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004163 long mSecRealtime = mClocks.elapsedRealtime();
4164 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004165 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4166 SparseIntArray uids = ent.getValue();
4167 for (int j=0; j<uids.size(); j++) {
4168 addHistoryEventLocked(mSecRealtime, mSecUptime,
4169 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4170 }
4171 }
4172 }
4173 } else {
4174 // Record the currently running processes as starting, now that we are tracking them.
4175 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4176 HistoryItem.EVENT_PROC);
4177 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004178 long mSecRealtime = mClocks.elapsedRealtime();
4179 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004180 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4181 SparseIntArray uids = ent.getValue();
4182 for (int j=0; j<uids.size(); j++) {
4183 addHistoryEventLocked(mSecRealtime, mSecUptime,
4184 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4185 }
4186 }
4187 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004188 }
4189 }
4190
Dianne Hackborn9a755432014-05-15 17:05:22 -07004191 public void setNoAutoReset(boolean enabled) {
4192 mNoAutoReset = enabled;
4193 }
4194
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004195 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004196 if (mPretendScreenOff != pretendScreenOff) {
4197 mPretendScreenOff = pretendScreenOff;
4198 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4199 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004200 }
4201
Dianne Hackborn9a755432014-05-15 17:05:22 -07004202 private String mInitialAcquireWakeName;
4203 private int mInitialAcquireWakeUid = -1;
4204
Narayan Kamath81822022017-12-08 11:56:01 +00004205 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4206 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004207 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004208 if (type == WAKE_TYPE_PARTIAL) {
4209 // Only care about partial wake locks, since full wake locks
4210 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004211 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004212 if (historyName == null) {
4213 historyName = name;
4214 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004215 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004216 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4217 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004218 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004219 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004220 }
4221 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004222 if (mWakeLockNesting == 0) {
4223 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4224 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4225 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004226 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004227 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004228 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004229 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004230 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004231 } else if (!mWakeLockImportant && !unimportantForLogging
4232 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004233 if (mHistoryLastWritten.wakelockTag != null) {
4234 // We'll try to update the last tag.
4235 mHistoryLastWritten.wakelockTag = null;
4236 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004237 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004238 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004239 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004240 }
4241 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004242 }
4243 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004244 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004245 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004246 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4247 // We only update the cpu time when a wake lock is acquired if the screen is off.
4248 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4249 if (DEBUG_ENERGY_CPU) {
4250 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4251 }
4252 requestWakelockCpuUpdate();
4253 }
Narayan Kamath81822022017-12-08 11:56:01 +00004254
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004255 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004256
Yangster-mac20877162017-12-22 17:19:39 -08004257 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004258 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004259 getPowerManagerWakeLockLevel(type), name,
4260 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Yangster-macafad8c62018-01-05 22:30:49 -08004261 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004262 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004263 getPowerManagerWakeLockLevel(type), name,
4264 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Narayan Kamath81822022017-12-08 11:56:01 +00004265 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004266 }
4267 }
4268
Narayan Kamath81822022017-12-08 11:56:01 +00004269 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4270 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004271 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004272 if (type == WAKE_TYPE_PARTIAL) {
4273 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004274 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004275 if (historyName == null) {
4276 historyName = name;
4277 }
4278 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4279 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004280 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004281 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004282 }
4283 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004284 if (mWakeLockNesting == 0) {
4285 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4286 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4287 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004288 mInitialAcquireWakeName = null;
4289 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004290 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004291 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004292 }
4293 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004294 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4295 if (DEBUG_ENERGY_CPU) {
4296 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4297 }
4298 requestWakelockCpuUpdate();
4299 }
Narayan Kamath81822022017-12-08 11:56:01 +00004300
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004301 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004302 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004303 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004304 getPowerManagerWakeLockLevel(type), name,
4305 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Yangster-macafad8c62018-01-05 22:30:49 -08004306 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004307 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004308 getPowerManagerWakeLockLevel(type), name,
4309 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Narayan Kamath81822022017-12-08 11:56:01 +00004310 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004311 }
4312 }
4313
Bookatz1a1b0462018-01-12 11:47:03 -08004314 /**
4315 * Converts BatteryStats wakelock types back into PowerManager wakelock levels.
4316 * This is the inverse map of Notifier.getBatteryStatsWakeLockMonitorType().
4317 * These are estimations, since batterystats loses some of the original data.
4318 * TODO: Delete this. Instead, StatsLog.write should be called from PowerManager's Notifier.
4319 */
4320 private int getPowerManagerWakeLockLevel(int battertStatsWakelockType) {
4321 switch (battertStatsWakelockType) {
4322 // PowerManager.PARTIAL_WAKE_LOCK or PROXIMITY_SCREEN_OFF_WAKE_LOCK
4323 case BatteryStats.WAKE_TYPE_PARTIAL:
4324 return PowerManager.PARTIAL_WAKE_LOCK;
4325
4326 // PowerManager.SCREEN_DIM_WAKE_LOCK or SCREEN_BRIGHT_WAKE_LOCK
4327 case BatteryStats.WAKE_TYPE_FULL:
4328 return PowerManager.FULL_WAKE_LOCK;
4329
4330 case BatteryStats.WAKE_TYPE_DRAW:
4331 return PowerManager.DRAW_WAKE_LOCK;
4332
4333 // It appears that nothing can ever make a Window and PowerManager lacks an equivalent.
4334 case BatteryStats.WAKE_TYPE_WINDOW:
4335 Slog.e(TAG, "Illegal window wakelock type observed in batterystats.");
4336 return -1;
4337
4338 default:
4339 Slog.e(TAG, "Illegal wakelock type in batterystats: " + battertStatsWakelockType);
4340 return -1;
4341 }
4342 }
4343
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004344 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4345 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004346 final long elapsedRealtime = mClocks.elapsedRealtime();
4347 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004348 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004349 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004350 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4351 unimportantForLogging, elapsedRealtime, uptime);
4352 }
4353
4354 List<WorkChain> wcs = ws.getWorkChains();
4355 if (wcs != null) {
4356 for (int i = 0; i < wcs.size(); ++i) {
4357 final WorkChain wc = wcs.get(i);
4358 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4359 unimportantForLogging, elapsedRealtime, uptime);
4360 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004361 }
4362 }
4363
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004364 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4365 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004366 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004367 final long elapsedRealtime = mClocks.elapsedRealtime();
4368 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004369
4370 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4371
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004372 // For correct semantics, we start the need worksources first, so that we won't
4373 // make inappropriate history items as if all wake locks went away and new ones
4374 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004375 //
4376 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004377 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004378 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004379 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004380 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004381 }
Narayan Kamath81822022017-12-08 11:56:01 +00004382 if (wcs != null) {
4383 List<WorkChain> newChains = wcs[0];
4384 if (newChains != null) {
4385 for (int i = 0; i < newChains.size(); ++i) {
4386 final WorkChain newChain = newChains.get(i);
4387 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4388 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4389 uptime);
4390 }
4391 }
4392 }
4393
4394 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004395 final int NO = ws.size();
4396 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004397 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4398 uptime);
4399 }
4400 if (wcs != null) {
4401 List<WorkChain> goneChains = wcs[1];
4402 if (goneChains != null) {
4403 for (int i = 0; i < goneChains.size(); ++i) {
4404 final WorkChain goneChain = goneChains.get(i);
4405 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4406 historyName, type, elapsedRealtime, uptime);
4407 }
4408 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004409 }
4410 }
4411
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004412 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4413 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004414 final long elapsedRealtime = mClocks.elapsedRealtime();
4415 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004416 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004417 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004418 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4419 uptime);
4420 }
4421
4422 List<WorkChain> wcs = ws.getWorkChains();
4423 if (wcs != null) {
4424 for (int i = 0; i < wcs.size(); ++i) {
4425 final WorkChain wc = wcs.get(i);
4426 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4427 elapsedRealtime, uptime);
4428 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004429 }
4430 }
4431
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004432 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004433 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004434 uid, null, name, historyName,
4435 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08004436
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004437 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004438 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004439 }
4440
4441 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4442 WorkSource workSource) {
4443 final int N = workSource.size();
4444 for (int i = 0; i < N; ++i) {
4445 final int uid = mapUid(workSource.get(i));
4446 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004447 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004448 workSource.get(i), workSource.getName(i), name, historyName,
4449 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004450 }
4451
4452 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4453 if (workChains != null) {
4454 for (int i = 0; i < workChains.size(); ++i) {
4455 final WorkChain workChain = workChains.get(i);
4456 final int uid = workChain.getAttributionUid();
4457 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4458
Yangster-macafad8c62018-01-05 22:30:49 -08004459 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004460 workChain.getUids(), workChain.getTags(), name, historyName,
4461 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004462 }
4463 }
4464 }
4465
4466 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004467 final long elapsedRealtime = mClocks.elapsedRealtime();
4468 final long uptime = mClocks.uptimeMillis();
4469 if (historyName == null) {
4470 historyName = name;
4471 }
4472 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4473 0)) {
4474 return;
4475 }
4476 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4477 historyName, uid);
4478 }
4479
4480 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Bookatz90867622018-01-31 15:05:57 -08004481 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, null,
4482 name, historyName, StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08004483
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004484 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004485 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004486 }
4487
4488 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4489 WorkSource workSource) {
4490 final int N = workSource.size();
4491 for (int i = 0; i < N; ++i) {
4492 final int uid = mapUid(workSource.get(i));
4493 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004494 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004495 workSource.get(i), workSource.getName(i), name, historyName,
4496 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004497 }
4498
4499 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4500 if (workChains != null) {
4501 for (int i = 0; i < workChains.size(); ++i) {
4502 final WorkChain workChain = workChains.get(i);
4503 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004504 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004505 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004506 workChain.getUids(), workChain.getTags(), name, historyName,
4507 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004508 }
4509 }
4510 }
4511
4512 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004513 final long elapsedRealtime = mClocks.elapsedRealtime();
4514 final long uptime = mClocks.uptimeMillis();
4515 if (historyName == null) {
4516 historyName = name;
4517 }
4518 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4519 0)) {
4520 return;
4521 }
4522 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4523 historyName, uid);
4524 }
4525
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004526 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4527 if (mLastWakeupReason != null) {
4528 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004529 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004530 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz90867622018-01-31 15:05:57 -08004531 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
4532 /* duration_usec */ deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004533 mLastWakeupReason = null;
4534 }
4535 }
4536
4537 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004538 final long elapsedRealtime = mClocks.elapsedRealtime();
4539 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004540 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004541 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004542 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004543 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4544 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004545 mHistoryCur.wakeReasonTag.uid = 0;
4546 mLastWakeupReason = reason;
4547 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004548 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004549 }
4550
Adam Lesinski72478f02015-06-17 15:39:43 -07004551 public boolean startAddingCpuLocked() {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004552 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
Adam Lesinski72478f02015-06-17 15:39:43 -07004553 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004554 }
4555
Adam Lesinski72478f02015-06-17 15:39:43 -07004556 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4557 int statSystemTime, int statIOWaitTime, int statIrqTime,
4558 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004559 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4560 + " user=" + statUserTime + " sys=" + statSystemTime
4561 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4562 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4563 mCurStepCpuUserTime += totalUTime;
4564 mCurStepCpuSystemTime += totalSTime;
4565 mCurStepStatUserTime += statUserTime;
4566 mCurStepStatSystemTime += statSystemTime;
4567 mCurStepStatIOWaitTime += statIOWaitTime;
4568 mCurStepStatIrqTime += statIrqTime;
4569 mCurStepStatSoftIrqTime += statSoftIrqTime;
4570 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004571 }
4572
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004573 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004574 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004575 Uid u = mUidStats.get(uid);
4576 if (u != null) {
4577 u.mPids.remove(pid);
4578 }
4579 }
4580
4581 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004582 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004583 Uid u = mUidStats.get(uid);
4584 if (u != null) {
4585 Uid.Pid p = u.mPids.get(pid);
4586 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004587 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004588 }
4589 }
4590 return 0;
4591 }
4592
Dianne Hackborn287952c2010-09-22 22:34:31 -07004593 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004594 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004595 Uid u = mUidStats.get(uid);
4596 if (u != null) {
4597 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4598 }
4599 }
4600
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004601 int mSensorNesting;
4602
4603 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004604 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004605 final long elapsedRealtime = mClocks.elapsedRealtime();
4606 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004607 if (mSensorNesting == 0) {
4608 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4609 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4610 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004611 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004612 }
4613 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004614 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004615 }
4616
4617 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004618 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004619 final long elapsedRealtime = mClocks.elapsedRealtime();
4620 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004621 mSensorNesting--;
4622 if (mSensorNesting == 0) {
4623 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4624 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4625 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004626 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004627 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004628 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004629 }
4630
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004631 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004632
Narayan Kamath32684dd2018-01-08 17:32:51 +00004633 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4634 for (int i = 0; i < newWs.size(); ++i) {
4635 noteStartGpsLocked(newWs.get(i), null);
4636 }
4637
4638 for (int i = 0; i < oldWs.size(); ++i) {
4639 noteStopGpsLocked((oldWs.get(i)), null);
4640 }
4641
4642 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4643 if (wcs != null) {
4644 if (wcs[0] != null) {
4645 final List<WorkChain> newChains = wcs[0];
4646 for (int i = 0; i < newChains.size(); ++i) {
4647 noteStartGpsLocked(-1, newChains.get(i));
4648 }
4649 }
4650
4651 if (wcs[1] != null) {
4652 final List<WorkChain> goneChains = wcs[1];
4653 for (int i = 0; i < goneChains.size(); ++i) {
4654 noteStopGpsLocked(-1, goneChains.get(i));
4655 }
4656 }
4657 }
4658 }
4659
4660 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4661 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004662 final long elapsedRealtime = mClocks.elapsedRealtime();
4663 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004664 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004665 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004666 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4667 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004668 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004669 }
4670 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004671
4672 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004673 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4674 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004675 } else {
4676 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004677 workChain.getUids(), workChain.getTags(),
4678 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004679 }
4680
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004681 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004683
Narayan Kamath32684dd2018-01-08 17:32:51 +00004684 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4685 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004686 final long elapsedRealtime = mClocks.elapsedRealtime();
4687 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004688 mGpsNesting--;
4689 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004690 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004691 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4692 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004693 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004694 stopAllGpsSignalQualityTimersLocked(-1);
4695 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004696 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004697
4698 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004699 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4700 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004701 } else {
4702 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08004703 workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004704 }
4705
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004706 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004708
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004709 public void noteGpsSignalQualityLocked(int signalLevel) {
4710 if (mGpsNesting == 0) {
4711 return;
4712 }
4713 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4714 stopAllGpsSignalQualityTimersLocked(-1);
4715 return;
4716 }
4717 final long elapsedRealtime = mClocks.elapsedRealtime();
4718 final long uptime = mClocks.uptimeMillis();
4719 if (mGpsSignalQualityBin != signalLevel) {
4720 if (mGpsSignalQualityBin >= 0) {
4721 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4722 }
4723 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4724 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4725 }
4726 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4727 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4728 addHistoryRecordLocked(elapsedRealtime, uptime);
4729 mGpsSignalQualityBin = signalLevel;
4730 }
4731 return;
4732 }
4733
Jeff Browne95c3cd2014-05-02 16:59:26 -07004734 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004735 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004736
4737 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4738 // original 4 are mapped to one of the originals.
4739 if (state > MAX_TRACKED_SCREEN_STATE) {
4740 switch (state) {
4741 case Display.STATE_VR:
4742 state = Display.STATE_ON;
4743 break;
4744 default:
4745 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4746 break;
4747 }
4748 }
4749
Jeff Browne95c3cd2014-05-02 16:59:26 -07004750 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004751 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004752 final int oldState = mScreenState;
4753 mScreenState = state;
4754 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4755 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004756
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004757 if (state != Display.STATE_UNKNOWN) {
4758 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004759 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4760 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4761 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004762 } else {
4763 Slog.wtf(TAG, "Unexpected screen state: " + state);
4764 }
4765 }
4766
Mike Mac2f518a2017-09-19 16:06:03 -07004767 final long elapsedRealtime = mClocks.elapsedRealtime();
4768 final long uptime = mClocks.uptimeMillis();
4769
4770 boolean updateHistory = false;
4771 if (isScreenDoze(state)) {
4772 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4773 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4774 updateHistory = true;
4775 } else if (isScreenDoze(oldState)) {
4776 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4777 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4778 updateHistory = true;
4779 }
4780 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004781 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4782 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4783 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004784 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4785 if (mScreenBrightnessBin >= 0) {
4786 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4787 }
Mike Mac2f518a2017-09-19 16:06:03 -07004788 updateHistory = true;
4789 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004790 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4791 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4792 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004793 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4794 if (mScreenBrightnessBin >= 0) {
4795 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4796 }
Mike Mac2f518a2017-09-19 16:06:03 -07004797 updateHistory = true;
4798 }
4799 if (updateHistory) {
4800 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4801 + Display.stateToString(state));
4802 addHistoryRecordLocked(elapsedRealtime, uptime);
4803 }
4804 if (isScreenOn(state)) {
4805 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4806 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4807 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004808 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004809 elapsedRealtime, uptime);
4810 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004811 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004812 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004813 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004814 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004815 }
4816 // Update discharge amounts.
4817 if (mOnBatteryInternal) {
4818 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004819 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004820 }
4821 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004822
Dianne Hackborn617f8772009-03-31 15:04:46 -07004823 public void noteScreenBrightnessLocked(int brightness) {
4824 // Bin the brightness.
4825 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4826 if (bin < 0) bin = 0;
4827 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4828 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004829 final long elapsedRealtime = mClocks.elapsedRealtime();
4830 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004831 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4832 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004833 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4834 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004835 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004836 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004837 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004838 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004839 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004840 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004841 }
4842 mScreenBrightnessBin = bin;
4843 }
4844 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004845
Dianne Hackborn617f8772009-03-31 15:04:46 -07004846 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004847 if (mOnBatteryInternal) {
4848 uid = mapUid(uid);
4849 getUidStatsLocked(uid).noteUserActivityLocked(event);
4850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004851 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004852
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004853 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004854 final long elapsedRealtime = mClocks.elapsedRealtime();
4855 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004856 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4857 reason, reasonUid);
4858 }
4859
Jeff Browne95c3cd2014-05-02 16:59:26 -07004860 public void noteInteractiveLocked(boolean interactive) {
4861 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08004862 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004863 mInteractive = interactive;
4864 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
4865 if (interactive) {
4866 mInteractiveTimer.startRunningLocked(elapsedRealtime);
4867 } else {
4868 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
4869 }
4870 }
4871 }
4872
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004873 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004874 final long elapsedRealtime = mClocks.elapsedRealtime();
4875 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004876 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4877 extra, type);
4878 mNumConnectivityChange++;
4879 }
4880
Adam Lesinski5f056f62016-07-14 16:56:08 -07004881 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4882 final long uptimeMillis, int uid) {
4883 uid = mapUid(uid);
4884 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4885 uid);
4886 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4887 }
4888
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004889 /**
4890 * Updates the radio power state and returns true if an external stats collection should occur.
4891 */
4892 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004893 final long elapsedRealtime = mClocks.elapsedRealtime();
4894 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004895 if (mMobileRadioPowerState != powerState) {
4896 long realElapsedRealtimeMs;
4897 final boolean active =
4898 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4899 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4900 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004901 if (uid > 0) {
4902 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4903 }
4904
Adam Lesinski9acfd812016-04-19 18:29:50 -07004905 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004906 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4907 } else {
4908 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004909 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004910 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4911 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4912 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004913 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004914 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4915 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4916 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004917 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004918 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4919 }
4920 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4921 + Integer.toHexString(mHistoryCur.states));
4922 addHistoryRecordLocked(elapsedRealtime, uptime);
4923 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08004924 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004925 if (active) {
4926 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4927 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4928 } else {
4929 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004930 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004931 // Tell the caller to collect radio network/power stats.
4932 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004933 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004934 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004935 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004936 }
4937
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004938 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004939 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004940 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4941 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4942 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004943 final long elapsedRealtime = mClocks.elapsedRealtime();
4944 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004945 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004946 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004947 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4948 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004949 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004950 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004951 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004952 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4953 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004954 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004955 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004956 }
4957 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatz90867622018-01-31 15:05:57 -08004958 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
4959 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
4960 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004961 }
4962 }
4963
Bookatzddccf0a2017-11-28 16:48:14 -08004964 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004965 final long elapsedRealtime = mClocks.elapsedRealtime();
4966 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004967 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004968 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004969 // We don't go out of general idling mode until explicitly taken out of
4970 // device idle through going active or significant motion.
4971 nowIdling = true;
4972 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004973 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
4974 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
4975 // We don't go out of general light idling mode until explicitly taken out of
4976 // device idle through going active or significant motion.
4977 nowLightIdling = true;
4978 }
4979 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
4980 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
4981 activeReason, activeUid);
4982 }
Bookatzddccf0a2017-11-28 16:48:14 -08004983 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
4984 int statsmode;
4985 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
4986 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
4987 else statsmode = DEVICE_IDLE_MODE_OFF;
4988 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
4989 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004990 if (mDeviceIdling != nowIdling) {
4991 mDeviceIdling = nowIdling;
4992 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
4993 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
4994 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004995 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004996 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
4997 } else {
4998 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
4999 }
5000 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005001 if (mDeviceLightIdling != nowLightIdling) {
5002 mDeviceLightIdling = nowLightIdling;
5003 if (nowLightIdling) {
5004 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005005 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005006 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005007 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005008 }
5009 if (mDeviceIdleMode != mode) {
5010 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
5011 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
5012 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
5013 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005014 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005015 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
5016 mLastIdleTimeStart = elapsedRealtime;
5017 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
5018 if (lastDuration > mLongestLightIdleTime) {
5019 mLongestLightIdleTime = lastDuration;
5020 }
5021 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005022 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005023 if (lastDuration > mLongestFullIdleTime) {
5024 mLongestFullIdleTime = lastDuration;
5025 }
5026 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
5027 }
5028 if (mode == DEVICE_IDLE_MODE_LIGHT) {
5029 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005030 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005031 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
5032 }
5033 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08005034 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005035 }
5036 }
5037
Dianne Hackborn3accca02013-09-20 09:32:11 -07005038 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08005039 final long elapsedRealtime = mClocks.elapsedRealtime();
5040 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07005041 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005042 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07005043 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005044 PackageChange pc = new PackageChange();
5045 pc.mPackageName = pkgName;
5046 pc.mUpdate = true;
5047 pc.mVersionCode = versionCode;
5048 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005049 }
5050
5051 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005052 final long elapsedRealtime = mClocks.elapsedRealtime();
5053 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005054 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5055 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005056 PackageChange pc = new PackageChange();
5057 pc.mPackageName = pkgName;
5058 pc.mUpdate = true;
5059 addPackageChange(pc);
5060 }
5061
5062 private void addPackageChange(PackageChange pc) {
5063 if (mDailyPackageChanges == null) {
5064 mDailyPackageChanges = new ArrayList<>();
5065 }
5066 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005067 }
5068
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005069 void stopAllGpsSignalQualityTimersLocked(int except) {
5070 final long elapsedRealtime = mClocks.elapsedRealtime();
5071 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5072 if (i == except) {
5073 continue;
5074 }
5075 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5076 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5077 }
5078 }
5079 }
5080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005081 public void notePhoneOnLocked() {
5082 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005083 final long elapsedRealtime = mClocks.elapsedRealtime();
5084 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005085 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005086 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5087 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005088 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005090 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091 }
5092 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 public void notePhoneOffLocked() {
5095 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005096 final long elapsedRealtime = mClocks.elapsedRealtime();
5097 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005098 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005099 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5100 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005101 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005102 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005103 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005104 }
5105 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005106
Dianne Hackborn3251b902014-06-20 14:40:53 -07005107 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005108 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005109 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005110 if (i == except) {
5111 continue;
5112 }
5113 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005114 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005115 }
5116 }
5117 }
5118
Dianne Hackborne4a59512010-12-07 11:08:07 -08005119 private int fixPhoneServiceState(int state, int signalBin) {
5120 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5121 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5122 // to infer that we are scanning from other data.
5123 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005124 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005125 state = ServiceState.STATE_IN_SERVICE;
5126 }
5127 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005128
Dianne Hackborne4a59512010-12-07 11:08:07 -08005129 return state;
5130 }
5131
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005132 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005133 boolean scanning = false;
5134 boolean newHistory = false;
5135
5136 mPhoneServiceStateRaw = state;
5137 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005138 mPhoneSignalStrengthBinRaw = strengthBin;
5139
Joe Onoratoabded112016-02-08 16:49:39 -08005140 final long elapsedRealtime = mClocks.elapsedRealtime();
5141 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005142
5143 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5144 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5145 // to infer that we are scanning from other data.
5146 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005147 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005148 state = ServiceState.STATE_IN_SERVICE;
5149 }
5150 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005151
5152 // If the phone is powered off, stop all timers.
5153 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005154 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005155
Dianne Hackborne4a59512010-12-07 11:08:07 -08005156 // If we are in service, make sure the correct signal string timer is running.
5157 } else if (state == ServiceState.STATE_IN_SERVICE) {
5158 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005159
5160 // If we're out of service, we are in the lowest signal strength
5161 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005162 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005163 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005164 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005165 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005166 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005167 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005168 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5169 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005170 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005171 }
5172 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005173
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005174 if (!scanning) {
5175 // If we are no longer scanning, then stop the scanning timer.
5176 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5177 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5178 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5179 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005180 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005181 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005182 }
5183 }
5184
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005185 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005186 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5187 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005188 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005189 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005190 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005191 mPhoneServiceState = state;
5192 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005193
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005194 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005195 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005196 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005197 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005198 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005199 if (strengthBin >= 0) {
5200 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005201 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005202 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005203 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5204 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005205 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005206 + Integer.toHexString(mHistoryCur.states));
5207 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005208 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005209 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005210 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005211 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005212 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005213 }
5214
5215 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005216 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005217 }
5218 }
5219
5220 /**
5221 * Telephony stack updates the phone state.
5222 * @param state phone state from ServiceState.getState()
5223 */
5224 public void notePhoneStateLocked(int state, int simState) {
5225 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005226 }
5227
Wink Savillee9b06d72009-05-18 21:47:50 -07005228 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005229 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005230 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005231 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005232 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005233
Dianne Hackborn627bba72009-03-24 22:32:56 -07005234 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
5235 int bin = DATA_CONNECTION_NONE;
5236 if (hasData) {
5237 switch (dataType) {
5238 case TelephonyManager.NETWORK_TYPE_EDGE:
5239 bin = DATA_CONNECTION_EDGE;
5240 break;
5241 case TelephonyManager.NETWORK_TYPE_GPRS:
5242 bin = DATA_CONNECTION_GPRS;
5243 break;
5244 case TelephonyManager.NETWORK_TYPE_UMTS:
5245 bin = DATA_CONNECTION_UMTS;
5246 break;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005247 case TelephonyManager.NETWORK_TYPE_CDMA:
5248 bin = DATA_CONNECTION_CDMA;
5249 break;
5250 case TelephonyManager.NETWORK_TYPE_EVDO_0:
5251 bin = DATA_CONNECTION_EVDO_0;
5252 break;
5253 case TelephonyManager.NETWORK_TYPE_EVDO_A:
5254 bin = DATA_CONNECTION_EVDO_A;
5255 break;
5256 case TelephonyManager.NETWORK_TYPE_1xRTT:
5257 bin = DATA_CONNECTION_1xRTT;
5258 break;
5259 case TelephonyManager.NETWORK_TYPE_HSDPA:
5260 bin = DATA_CONNECTION_HSDPA;
5261 break;
5262 case TelephonyManager.NETWORK_TYPE_HSUPA:
5263 bin = DATA_CONNECTION_HSUPA;
5264 break;
5265 case TelephonyManager.NETWORK_TYPE_HSPA:
5266 bin = DATA_CONNECTION_HSPA;
5267 break;
5268 case TelephonyManager.NETWORK_TYPE_IDEN:
5269 bin = DATA_CONNECTION_IDEN;
5270 break;
5271 case TelephonyManager.NETWORK_TYPE_EVDO_B:
5272 bin = DATA_CONNECTION_EVDO_B;
5273 break;
Robert Greenwalt962a9902010-11-02 11:10:25 -07005274 case TelephonyManager.NETWORK_TYPE_LTE:
5275 bin = DATA_CONNECTION_LTE;
5276 break;
5277 case TelephonyManager.NETWORK_TYPE_EHRPD:
5278 bin = DATA_CONNECTION_EHRPD;
5279 break;
Patrick Tjinb71703c2013-11-06 09:27:03 -08005280 case TelephonyManager.NETWORK_TYPE_HSPAP:
5281 bin = DATA_CONNECTION_HSPAP;
5282 break;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005283 default:
5284 bin = DATA_CONNECTION_OTHER;
5285 break;
5286 }
5287 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005288 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005289 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005290 final long elapsedRealtime = mClocks.elapsedRealtime();
5291 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005292 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5293 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005294 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5295 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005296 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005297 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005298 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005299 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005300 }
5301 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005302 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005303 }
5304 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005305
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005306 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005307 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005308 final long elapsedRealtime = mClocks.elapsedRealtime();
5309 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005310 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005311 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5312 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005313 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005314 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005315 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005316 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005317 }
5318 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005319
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005320 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005321 final long elapsedRealtime = mClocks.elapsedRealtime();
5322 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005323 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005324 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005325 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5326 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005327 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005328 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005329 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005330 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005331 }
5332 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005333
5334 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005335 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005336 final long elapsedRealtime = mClocks.elapsedRealtime();
5337 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005338 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005339 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005340 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5341 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005342 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005343 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005344 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005345 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005346 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005347 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005348
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005349 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005350 if (mAudioOnNesting == 0) {
5351 return;
5352 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005353 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005354 final long elapsedRealtime = mClocks.elapsedRealtime();
5355 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005356 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005357 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005358 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5359 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005360 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005361 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005362 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005363 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005364 }
5365
5366 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005367 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005368 final long elapsedRealtime = mClocks.elapsedRealtime();
5369 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005370 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005371 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005372 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5373 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005374 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005375 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005376 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005377 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005378 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005379 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005380
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005381 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005382 if (mVideoOnNesting == 0) {
5383 return;
5384 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005385 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005386 final long elapsedRealtime = mClocks.elapsedRealtime();
5387 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005388 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005389 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005390 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5391 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005392 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005393 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005394 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005395 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005396 }
5397
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005398 public void noteResetAudioLocked() {
5399 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005400 final long elapsedRealtime = mClocks.elapsedRealtime();
5401 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005402 mAudioOnNesting = 0;
5403 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5404 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5405 + Integer.toHexString(mHistoryCur.states));
5406 addHistoryRecordLocked(elapsedRealtime, uptime);
5407 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5408 for (int i=0; i<mUidStats.size(); i++) {
5409 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5410 uid.noteResetAudioLocked(elapsedRealtime);
5411 }
5412 }
5413 }
5414
5415 public void noteResetVideoLocked() {
5416 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005417 final long elapsedRealtime = mClocks.elapsedRealtime();
5418 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005419 mAudioOnNesting = 0;
5420 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5421 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5422 + Integer.toHexString(mHistoryCur.states));
5423 addHistoryRecordLocked(elapsedRealtime, uptime);
5424 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5425 for (int i=0; i<mUidStats.size(); i++) {
5426 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5427 uid.noteResetVideoLocked(elapsedRealtime);
5428 }
5429 }
5430 }
5431
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005432 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005433 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005434 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005435 }
5436
5437 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005438 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005439 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005440 }
5441
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005442 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005443 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005444 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5445 }
5446
5447 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005448 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005449 getUidStatsLocked(uid).noteVibratorOffLocked();
5450 }
5451
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005452 public void noteFlashlightOnLocked(int uid) {
5453 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005454 final long elapsedRealtime = mClocks.elapsedRealtime();
5455 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005456 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005457 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5458 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005459 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005460 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005461 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5462 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005463 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5464 }
5465
5466 public void noteFlashlightOffLocked(int uid) {
5467 if (mFlashlightOnNesting == 0) {
5468 return;
5469 }
5470 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005471 final long elapsedRealtime = mClocks.elapsedRealtime();
5472 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005473 if (--mFlashlightOnNesting == 0) {
5474 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5475 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5476 + Integer.toHexString(mHistoryCur.states2));
5477 addHistoryRecordLocked(elapsedRealtime, uptime);
5478 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5479 }
5480 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5481 }
5482
5483 public void noteCameraOnLocked(int uid) {
5484 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005485 final long elapsedRealtime = mClocks.elapsedRealtime();
5486 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005487 if (mCameraOnNesting++ == 0) {
5488 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5489 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5490 + Integer.toHexString(mHistoryCur.states2));
5491 addHistoryRecordLocked(elapsedRealtime, uptime);
5492 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5493 }
5494 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5495 }
5496
5497 public void noteCameraOffLocked(int uid) {
5498 if (mCameraOnNesting == 0) {
5499 return;
5500 }
5501 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005502 final long elapsedRealtime = mClocks.elapsedRealtime();
5503 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005504 if (--mCameraOnNesting == 0) {
5505 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5506 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5507 + Integer.toHexString(mHistoryCur.states2));
5508 addHistoryRecordLocked(elapsedRealtime, uptime);
5509 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5510 }
5511 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5512 }
5513
5514 public void noteResetCameraLocked() {
5515 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005516 final long elapsedRealtime = mClocks.elapsedRealtime();
5517 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005518 mCameraOnNesting = 0;
5519 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5520 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5521 + Integer.toHexString(mHistoryCur.states2));
5522 addHistoryRecordLocked(elapsedRealtime, uptime);
5523 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5524 for (int i=0; i<mUidStats.size(); i++) {
5525 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5526 uid.noteResetCameraLocked(elapsedRealtime);
5527 }
5528 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005529 }
5530
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005531 public void noteResetFlashlightLocked() {
5532 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005533 final long elapsedRealtime = mClocks.elapsedRealtime();
5534 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005535 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005536 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5537 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005538 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005539 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005540 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5541 for (int i=0; i<mUidStats.size(); i++) {
5542 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5543 uid.noteResetFlashlightLocked(elapsedRealtime);
5544 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005545 }
5546 }
5547
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005548 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5549 boolean isUnoptimized) {
5550 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005551 final long elapsedRealtime = mClocks.elapsedRealtime();
5552 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005553 if (mBluetoothScanNesting == 0) {
5554 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5555 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5556 + Integer.toHexString(mHistoryCur.states2));
5557 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005558 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005559 }
5560 mBluetoothScanNesting++;
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005561
Yangster-macafad8c62018-01-05 22:30:49 -08005562 if (workChain != null) {
5563 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005564 workChain.getUids(), workChain.getTags(),
5565 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005566 if (isUnoptimized) {
5567 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005568 workChain.getUids(), workChain.getTags(),
5569 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005570 }
5571 } else {
Bookatz90867622018-01-31 15:05:57 -08005572 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null,
5573 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005574 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005575 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08005576 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005577 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005578 }
5579
Bookatzb1f04f32017-05-19 13:57:32 -07005580 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005581 if (workChain != null) {
5582 getUidStatsLocked(uid).addBluetoothWorkChain(workChain, isUnoptimized);
5583 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005584 }
5585
Bookatzb1f04f32017-05-19 13:57:32 -07005586 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005587 final int N = ws.size();
5588 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005589 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5590 }
5591
5592 final List<WorkChain> workChains = ws.getWorkChains();
5593 if (workChains != null) {
5594 for (int i = 0; i < workChains.size(); ++i) {
5595 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5596 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005597 }
5598 }
5599
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005600 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5601 boolean isUnoptimized) {
5602 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005603 final long elapsedRealtime = mClocks.elapsedRealtime();
5604 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005605 mBluetoothScanNesting--;
5606 if (mBluetoothScanNesting == 0) {
5607 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5608 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5609 + Integer.toHexString(mHistoryCur.states2));
5610 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005611 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005612 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005613
Yangster-macafad8c62018-01-05 22:30:49 -08005614 if (workChain != null) {
5615 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08005616 StatsLog.BLE_SCAN_STATE_CHANGED, workChain.getUids(), workChain.getTags(),
5617 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005618 if (isUnoptimized) {
5619 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005620 workChain.getUids(), workChain.getTags(),
5621 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005622 }
5623 } else {
Bookatz90867622018-01-31 15:05:57 -08005624 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null,
5625 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005626 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005627 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08005628 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005629 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005630 }
5631
Bookatz94c5a312017-07-11 16:49:17 -07005632 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005633 if (workChain != null) {
5634 getUidStatsLocked(uid).removeBluetoothWorkChain(workChain, isUnoptimized);
5635 }
5636 }
5637
5638 private int getAttributionUid(int uid, WorkChain workChain) {
5639 if (workChain != null) {
5640 return mapUid(workChain.getAttributionUid());
5641 }
5642
5643 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005644 }
5645
Bookatz94c5a312017-07-11 16:49:17 -07005646 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005647 final int N = ws.size();
5648 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005649 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5650 }
5651
5652 final List<WorkChain> workChains = ws.getWorkChains();
5653 if (workChains != null) {
5654 for (int i = 0; i < workChains.size(); ++i) {
5655 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5656 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005657 }
5658 }
5659
5660 public void noteResetBluetoothScanLocked() {
5661 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005662 final long elapsedRealtime = mClocks.elapsedRealtime();
5663 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005664 mBluetoothScanNesting = 0;
5665 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5666 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5667 + Integer.toHexString(mHistoryCur.states2));
5668 addHistoryRecordLocked(elapsedRealtime, uptime);
5669 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005670
5671
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005672 for (int i=0; i<mUidStats.size(); i++) {
5673 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5674 uid.noteResetBluetoothScanLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005675
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005676 List<WorkChain> allWorkChains = uid.getAllBluetoothWorkChains();
5677 if (allWorkChains != null) {
5678 for (int j = 0; j < allWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005679 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005680 allWorkChains.get(j).getUids(),
Bookatz90867622018-01-31 15:05:57 -08005681 allWorkChains.get(j).getTags(),
5682 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005683 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005684 allWorkChains.clear();
5685 }
5686
5687 List<WorkChain> unoptimizedWorkChains = uid.getUnoptimizedBluetoothWorkChains();
5688 if (unoptimizedWorkChains != null) {
5689 for (int j = 0; j < unoptimizedWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005690 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005691 unoptimizedWorkChains.get(j).getUids(),
Bookatz90867622018-01-31 15:05:57 -08005692 unoptimizedWorkChains.get(j).getTags(),
5693 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005694 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005695 unoptimizedWorkChains.clear();
5696 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005697 }
5698 }
5699 }
5700
Bookatz4ebc0642017-05-11 12:21:19 -07005701 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005702 final int N = ws.size();
5703 for (int i = 0; i < N; i++) {
5704 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005705 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005706 StatsLog.write_non_chained(StatsLog.BLE_SCAN_RESULT_RECEIVED, ws.get(i), ws.getName(i),
5707 numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005708 }
5709
5710 final List<WorkChain> workChains = ws.getWorkChains();
5711 if (workChains != null) {
5712 for (int i = 0; i < workChains.size(); ++i) {
5713 final WorkChain wc = workChains.get(i);
5714 int uid = mapUid(wc.getAttributionUid());
5715 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-macafad8c62018-01-05 22:30:49 -08005716 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED,
5717 wc.getUids(), wc.getTags(), numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005718 }
Bookatz956f36bf2017-04-28 09:48:17 -07005719 }
5720 }
5721
Adam Lesinski5f056f62016-07-14 16:56:08 -07005722 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5723 final long uptimeMillis, int uid) {
5724 uid = mapUid(uid);
5725 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5726 uid);
5727 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5728 }
5729
5730 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005731 final long elapsedRealtime = mClocks.elapsedRealtime();
5732 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005733 if (mWifiRadioPowerState != powerState) {
5734 final boolean active =
5735 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5736 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5737 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005738 if (uid > 0) {
5739 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5740 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005741 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005742 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005743 } else {
5744 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005745 mWifiActiveTimer.stopRunningLocked(
5746 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005747 }
5748 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5749 + Integer.toHexString(mHistoryCur.states));
5750 addHistoryRecordLocked(elapsedRealtime, uptime);
5751 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005752 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005753 }
5754 }
5755
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005756 public void noteWifiRunningLocked(WorkSource ws) {
5757 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005758 final long elapsedRealtime = mClocks.elapsedRealtime();
5759 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005760 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005761 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5762 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005763 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005764 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005765 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005766 int N = ws.size();
5767 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005768 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005769 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005770 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005771
5772 List<WorkChain> workChains = ws.getWorkChains();
5773 if (workChains != null) {
5774 for (int i = 0; i < workChains.size(); ++i) {
5775 int uid = mapUid(workChains.get(i).getAttributionUid());
5776 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5777 }
5778 }
5779
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005780 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005781 } else {
5782 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005783 }
5784 }
5785
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005786 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5787 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005788 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005789 int N = oldWs.size();
5790 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005791 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005792 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005793 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005794
5795 List<WorkChain> workChains = oldWs.getWorkChains();
5796 if (workChains != null) {
5797 for (int i = 0; i < workChains.size(); ++i) {
5798 int uid = mapUid(workChains.get(i).getAttributionUid());
5799 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5800 }
5801 }
5802
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005803 N = newWs.size();
5804 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005805 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005806 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005807 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005808
5809 workChains = newWs.getWorkChains();
5810 if (workChains != null) {
5811 for (int i = 0; i < workChains.size(); ++i) {
5812 int uid = mapUid(workChains.get(i).getAttributionUid());
5813 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5814 }
5815 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005816 } else {
5817 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5818 }
5819 }
5820
5821 public void noteWifiStoppedLocked(WorkSource ws) {
5822 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005823 final long elapsedRealtime = mClocks.elapsedRealtime();
5824 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005825 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005826 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5827 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005828 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005829 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005830 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005831 int N = ws.size();
5832 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005833 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005834 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005835 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005836
5837 List<WorkChain> workChains = ws.getWorkChains();
5838 if (workChains != null) {
5839 for (int i = 0; i < workChains.size(); ++i) {
5840 int uid = mapUid(workChains.get(i).getAttributionUid());
5841 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5842 }
5843 }
5844
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005845 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005846 } else {
5847 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005848 }
5849 }
5850
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005851 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5852 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5853 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005854 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005855 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005856 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005857 }
5858 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005859 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005860 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005861 }
5862 }
5863
Dianne Hackborn3251b902014-06-20 14:40:53 -07005864 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5865 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5866 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005867 final long elapsedRealtime = mClocks.elapsedRealtime();
5868 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005869 if (mWifiSupplState >= 0) {
5870 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5871 }
5872 mWifiSupplState = supplState;
5873 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5874 mHistoryCur.states2 =
5875 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5876 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5877 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5878 + Integer.toHexString(mHistoryCur.states2));
5879 addHistoryRecordLocked(elapsedRealtime, uptime);
5880 }
5881 }
5882
5883 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005884 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005885 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5886 if (i == except) {
5887 continue;
5888 }
5889 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5890 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5891 }
5892 }
5893 }
5894
5895 public void noteWifiRssiChangedLocked(int newRssi) {
5896 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5897 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5898 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005899 final long elapsedRealtime = mClocks.elapsedRealtime();
5900 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005901 if (mWifiSignalStrengthBin >= 0) {
5902 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5903 elapsedRealtime);
5904 }
5905 if (strengthBin >= 0) {
5906 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5907 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Bookatze5885242017-10-24 20:10:31 -07005908 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07005909 }
5910 mHistoryCur.states2 =
5911 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5912 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5913 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5914 + Integer.toHexString(mHistoryCur.states2));
5915 addHistoryRecordLocked(elapsedRealtime, uptime);
5916 } else {
5917 stopAllWifiSignalStrengthTimersLocked(-1);
5918 }
5919 mWifiSignalStrengthBin = strengthBin;
5920 }
5921 }
5922
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005923 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005924
The Android Open Source Project10592532009-03-18 17:39:46 -07005925 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005926 final long elapsedRealtime = mClocks.elapsedRealtime();
5927 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005928 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005929 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005930 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5931 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005932 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005933 }
5934 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005935 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005936 }
5937
5938 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005939 final long elapsedRealtime = mClocks.elapsedRealtime();
5940 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005941 mWifiFullLockNesting--;
5942 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005943 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005944 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
5945 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005946 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005947 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005948 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005949 }
5950
Nick Pelly6ccaa542012-06-15 15:22:47 -07005951 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005952
Nick Pelly6ccaa542012-06-15 15:22:47 -07005953 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005954 final long elapsedRealtime = mClocks.elapsedRealtime();
5955 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005956 if (mWifiScanNesting == 0) {
5957 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
5958 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005959 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005960 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005961 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07005962 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005963 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005964 }
5965
Nick Pelly6ccaa542012-06-15 15:22:47 -07005966 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005967 final long elapsedRealtime = mClocks.elapsedRealtime();
5968 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005969 mWifiScanNesting--;
5970 if (mWifiScanNesting == 0) {
5971 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
5972 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005973 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005974 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005975 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005976 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005977 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005978
Robert Greenwalta029ea12013-09-25 16:38:12 -07005979 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005980 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005981 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005982 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005983 }
5984
5985 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005986 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005987 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005988 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005989 }
5990
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005991 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005992
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005993 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005994 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005995 final long elapsedRealtime = mClocks.elapsedRealtime();
5996 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005997 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005998 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005999 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
6000 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006001 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006002
6003 // Start Wifi Multicast overall timer
6004 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
6005 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
6006 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
6007 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006008 }
6009 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006010 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006011 }
6012
6013 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006014 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006015 final long elapsedRealtime = mClocks.elapsedRealtime();
6016 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006017 mWifiMulticastNesting--;
6018 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006019 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006020 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
6021 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006022 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006023
6024 // Stop Wifi Multicast overall timer
6025 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
6026 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
6027 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
6028 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006029 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006030 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006031 }
6032
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006033 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
6034 int N = ws.size();
6035 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006036 final int uid = mapUid(ws.get(i));
6037 noteFullWifiLockAcquiredLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006038 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6039 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006040 }
6041
6042 final List<WorkChain> workChains = ws.getWorkChains();
6043 if (workChains != null) {
6044 for (int i = 0; i < workChains.size(); ++i) {
6045 final WorkChain workChain = workChains.get(i);
6046 final int uid = mapUid(workChain.getAttributionUid());
6047 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006048 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006049 workChain.getUids(), workChain.getTags(),
6050 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006051 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006052 }
6053 }
6054
6055 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
6056 int N = ws.size();
6057 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006058 final int uid = mapUid(ws.get(i));
6059 noteFullWifiLockReleasedLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006060 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6061 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006062 }
6063
6064 final List<WorkChain> workChains = ws.getWorkChains();
6065 if (workChains != null) {
6066 for (int i = 0; i < workChains.size(); ++i) {
6067 final WorkChain workChain = workChains.get(i);
6068 final int uid = mapUid(workChain.getAttributionUid());
6069 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006070 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006071 workChain.getUids(), workChain.getTags(),
6072 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006073 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006074 }
6075 }
6076
Nick Pelly6ccaa542012-06-15 15:22:47 -07006077 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006078 int N = ws.size();
6079 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006080 final int uid = mapUid(ws.get(i));
6081 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006082 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006083 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006084 }
6085
6086 final List<WorkChain> workChains = ws.getWorkChains();
6087 if (workChains != null) {
6088 for (int i = 0; i < workChains.size(); ++i) {
6089 final WorkChain workChain = workChains.get(i);
6090 final int uid = mapUid(workChain.getAttributionUid());
6091 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006092 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08006093 workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006094 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006095 }
6096 }
6097
Nick Pelly6ccaa542012-06-15 15:22:47 -07006098 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006099 int N = ws.size();
6100 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006101 final int uid = mapUid(ws.get(i));
6102 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006103 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006104 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006105 }
6106
6107 final List<WorkChain> workChains = ws.getWorkChains();
6108 if (workChains != null) {
6109 for (int i = 0; i < workChains.size(); ++i) {
6110 final WorkChain workChain = workChains.get(i);
6111 final int uid = mapUid(workChain.getAttributionUid());
6112 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006113 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006114 workChain.getUids(), workChain.getTags(),
6115 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006116 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006117 }
6118 }
6119
Robert Greenwalta029ea12013-09-25 16:38:12 -07006120 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6121 int N = ws.size();
6122 for (int i=0; i<N; i++) {
6123 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6124 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006125
6126 final List<WorkChain> workChains = ws.getWorkChains();
6127 if (workChains != null) {
6128 for (int i = 0; i < workChains.size(); ++i) {
6129 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6130 }
6131 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006132 }
6133
6134 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6135 int N = ws.size();
6136 for (int i=0; i<N; i++) {
6137 noteWifiBatchedScanStoppedLocked(ws.get(i));
6138 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006139
6140 final List<WorkChain> workChains = ws.getWorkChains();
6141 if (workChains != null) {
6142 for (int i = 0; i < workChains.size(); ++i) {
6143 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6144 }
6145 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006146 }
6147
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006148 private static String[] includeInStringArray(String[] array, String str) {
6149 if (ArrayUtils.indexOf(array, str) >= 0) {
6150 return array;
6151 }
6152 String[] newArray = new String[array.length+1];
6153 System.arraycopy(array, 0, newArray, 0, array.length);
6154 newArray[array.length] = str;
6155 return newArray;
6156 }
6157
6158 private static String[] excludeFromStringArray(String[] array, String str) {
6159 int index = ArrayUtils.indexOf(array, str);
6160 if (index >= 0) {
6161 String[] newArray = new String[array.length-1];
6162 if (index > 0) {
6163 System.arraycopy(array, 0, newArray, 0, index);
6164 }
6165 if (index < array.length-1) {
6166 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6167 }
6168 return newArray;
6169 }
6170 return array;
6171 }
6172
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006173 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006174 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006175
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006176 synchronized (mModemNetworkLock) {
6177 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6178 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6179 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6180 } else {
6181 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6182 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6183 }
6184 }
6185
6186 synchronized (mWifiNetworkLock) {
6187 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6188 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6189 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6190 } else {
6191 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6192 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6193 }
6194 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006195 }
6196
David Chenc8a43242017-10-17 16:23:28 -07006197 public String[] getWifiIfaces() {
6198 synchronized (mWifiNetworkLock) {
6199 return mWifiIfaces;
6200 }
6201 }
6202
6203 public String[] getMobileIfaces() {
6204 synchronized (mModemNetworkLock) {
6205 return mModemIfaces;
6206 }
6207 }
6208
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006209 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6210 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006212
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006213 @Override public int getScreenOnCount(int which) {
6214 return mScreenOnTimer.getCountLocked(which);
6215 }
6216
Mike Mac2f518a2017-09-19 16:06:03 -07006217 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6218 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6219 }
6220
6221 @Override public int getScreenDozeCount(int which) {
6222 return mScreenDozeTimer.getCountLocked(which);
6223 }
6224
Dianne Hackborn617f8772009-03-31 15:04:46 -07006225 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006226 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006227 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006228 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006229 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006230
Kweku Adams87b19ec2017-10-09 12:40:03 -07006231 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6232 return mScreenBrightnessTimer[brightnessBin];
6233 }
6234
Jeff Browne95c3cd2014-05-02 16:59:26 -07006235 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6236 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006237 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006238
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006239 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6240 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006241 }
6242
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006243 @Override public int getPowerSaveModeEnabledCount(int which) {
6244 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6245 }
6246
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006247 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6248 int which) {
6249 switch (mode) {
6250 case DEVICE_IDLE_MODE_LIGHT:
6251 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006252 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006253 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6254 }
6255 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006256 }
6257
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006258 @Override public int getDeviceIdleModeCount(int mode, int which) {
6259 switch (mode) {
6260 case DEVICE_IDLE_MODE_LIGHT:
6261 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006262 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006263 return mDeviceIdleModeFullTimer.getCountLocked(which);
6264 }
6265 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006266 }
6267
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006268 @Override public long getLongestDeviceIdleModeTime(int mode) {
6269 switch (mode) {
6270 case DEVICE_IDLE_MODE_LIGHT:
6271 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006272 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006273 return mLongestFullIdleTime;
6274 }
6275 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006276 }
6277
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006278 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6279 switch (mode) {
6280 case DEVICE_IDLE_MODE_LIGHT:
6281 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006282 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006283 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6284 }
6285 return 0;
6286 }
6287
6288 @Override public int getDeviceIdlingCount(int mode, int which) {
6289 switch (mode) {
6290 case DEVICE_IDLE_MODE_LIGHT:
6291 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006292 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006293 return mDeviceIdlingTimer.getCountLocked(which);
6294 }
6295 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006296 }
6297
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006298 @Override public int getNumConnectivityChange(int which) {
6299 int val = mNumConnectivityChange;
6300 if (which == STATS_CURRENT) {
6301 val -= mLoadedNumConnectivityChange;
6302 } else if (which == STATS_SINCE_UNPLUGGED) {
6303 val -= mUnpluggedNumConnectivityChange;
6304 }
6305 return val;
6306 }
6307
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006308 @Override public long getGpsSignalQualityTime(int strengthBin,
6309 long elapsedRealtimeUs, int which) {
6310 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6311 return 0;
6312 }
6313 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6314 elapsedRealtimeUs, which);
6315 }
6316
6317 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006318 final double opVolt = mPowerProfile.getAveragePower(
6319 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6320 if (opVolt == 0) {
6321 return 0;
6322 }
6323 double energyUsedMaMs = 0.0;
6324 final int which = STATS_SINCE_CHARGED;
6325 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6326 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6327 energyUsedMaMs
6328 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6329 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6330 }
6331 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006332 }
6333
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006334 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6335 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006337
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006338 @Override public int getPhoneOnCount(int which) {
6339 return mPhoneOnTimer.getCountLocked(which);
6340 }
6341
Dianne Hackborn627bba72009-03-24 22:32:56 -07006342 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006343 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006344 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006345 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006346 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006347
6348 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006349 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006350 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006351 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006352 }
6353
Kweku Adams87b19ec2017-10-09 12:40:03 -07006354 @Override public Timer getPhoneSignalScanningTimer() {
6355 return mPhoneSignalScanningTimer;
6356 }
6357
Catherine Liufb900812012-07-17 14:12:56 -05006358 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6359 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006360 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006361
Kweku Adams87b19ec2017-10-09 12:40:03 -07006362 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6363 return mPhoneSignalStrengthsTimer[strengthBin];
6364 }
6365
Dianne Hackborn627bba72009-03-24 22:32:56 -07006366 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006367 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006368 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006369 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006370 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006371
Dianne Hackborn617f8772009-03-31 15:04:46 -07006372 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006373 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006374 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006375
Kweku Adams87b19ec2017-10-09 12:40:03 -07006376 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6377 return mPhoneDataConnectionsTimer[dataType];
6378 }
6379
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006380 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6381 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006382 }
6383
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006384 @Override public int getMobileRadioActiveCount(int which) {
6385 return mMobileRadioActiveTimer.getCountLocked(which);
6386 }
6387
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006388 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6389 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6390 }
6391
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006392 @Override public long getMobileRadioActiveUnknownTime(int which) {
6393 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6394 }
6395
6396 @Override public int getMobileRadioActiveUnknownCount(int which) {
6397 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6398 }
6399
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006400 @Override public long getWifiMulticastWakelockTime(
6401 long elapsedRealtimeUs, int which) {
6402 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6403 elapsedRealtimeUs, which);
6404 }
6405
6406 @Override public int getWifiMulticastWakelockCount(int which) {
6407 return mWifiMulticastWakelockTimer.getCountLocked(which);
6408 }
6409
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006410 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6411 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006412 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006413
Siddharth Rayb50a6842017-12-14 15:15:28 -08006414 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6415 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6416 }
6417
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006418 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6419 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006420 }
6421
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006422 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006423 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006424 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006425 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006426 }
6427
6428 @Override public int getWifiStateCount(int wifiState, int which) {
6429 return mWifiStateTimer[wifiState].getCountLocked(which);
6430 }
6431
Kweku Adams87b19ec2017-10-09 12:40:03 -07006432 @Override public Timer getWifiStateTimer(int wifiState) {
6433 return mWifiStateTimer[wifiState];
6434 }
6435
Dianne Hackborn3251b902014-06-20 14:40:53 -07006436 @Override public long getWifiSupplStateTime(int state,
6437 long elapsedRealtimeUs, int which) {
6438 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6439 elapsedRealtimeUs, which);
6440 }
6441
6442 @Override public int getWifiSupplStateCount(int state, int which) {
6443 return mWifiSupplStateTimer[state].getCountLocked(which);
6444 }
6445
Kweku Adams87b19ec2017-10-09 12:40:03 -07006446 @Override public Timer getWifiSupplStateTimer(int state) {
6447 return mWifiSupplStateTimer[state];
6448 }
6449
Dianne Hackborn3251b902014-06-20 14:40:53 -07006450 @Override public long getWifiSignalStrengthTime(int strengthBin,
6451 long elapsedRealtimeUs, int which) {
6452 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6453 elapsedRealtimeUs, which);
6454 }
6455
6456 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6457 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6458 }
6459
Kweku Adams87b19ec2017-10-09 12:40:03 -07006460 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6461 return mWifiSignalStrengthsTimer[strengthBin];
6462 }
6463
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006464 @Override
6465 public ControllerActivityCounter getBluetoothControllerActivity() {
6466 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006467 }
6468
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006469 @Override
6470 public ControllerActivityCounter getWifiControllerActivity() {
6471 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006472 }
6473
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006474 @Override
6475 public ControllerActivityCounter getModemControllerActivity() {
6476 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006477 }
6478
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006479 @Override
6480 public boolean hasBluetoothActivityReporting() {
6481 return mHasBluetoothReporting;
6482 }
6483
6484 @Override
6485 public boolean hasWifiActivityReporting() {
6486 return mHasWifiReporting;
6487 }
6488
6489 @Override
6490 public boolean hasModemActivityReporting() {
6491 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006492 }
6493
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006494 @Override
6495 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006496 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6497 }
6498
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006499 @Override
6500 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006501 return mFlashlightOnTimer.getCountLocked(which);
6502 }
6503
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006504 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006505 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6506 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6507 }
6508
6509 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006510 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6511 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6512 }
6513
6514 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006515 public long getNetworkActivityBytes(int type, int which) {
6516 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6517 return mNetworkByteActivityCounters[type].getCountLocked(which);
6518 } else {
6519 return 0;
6520 }
6521 }
6522
6523 @Override
6524 public long getNetworkActivityPackets(int type, int which) {
6525 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6526 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006527 } else {
6528 return 0;
6529 }
6530 }
6531
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006532 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006533 final long currentTime = System.currentTimeMillis();
6534 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006535 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6536 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006537 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006538 return mStartClockTime;
6539 }
6540
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006541 @Override public String getStartPlatformVersion() {
6542 return mStartPlatformVersion;
6543 }
6544
6545 @Override public String getEndPlatformVersion() {
6546 return mEndPlatformVersion;
6547 }
6548
6549 @Override public int getParcelVersion() {
6550 return VERSION;
6551 }
6552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006553 @Override public boolean getIsOnBattery() {
6554 return mOnBattery;
6555 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006557 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6558 return mUidStats;
6559 }
6560
Adam Lesinski5f056f62016-07-14 16:56:08 -07006561 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6562 if (timer != null) {
6563 timer.detach();
6564 }
6565 }
6566
6567 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6568 boolean detachIfReset) {
6569 if (timer != null) {
6570 return timer.reset(detachIfReset);
6571 }
6572 return true;
6573 }
6574
Bookatz867c0d72017-03-07 18:23:42 -08006575 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6576 if (timer != null) {
6577 return timer.reset(detachIfReset);
6578 }
6579 return true;
6580 }
6581
Adam Lesinski5f056f62016-07-14 16:56:08 -07006582 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6583 if (counter != null) {
6584 counter.detach();
6585 }
6586 }
6587
6588 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6589 boolean detachIfReset) {
6590 if (counter != null) {
6591 counter.reset(detachIfReset);
6592 }
6593 }
6594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 /**
6596 * The statistics associated with a particular uid.
6597 */
Joe Onoratoabded112016-02-08 16:49:39 -08006598 public static class Uid extends BatteryStats.Uid {
6599 /**
6600 * BatteryStatsImpl that we are associated with.
6601 */
6602 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006605
Bookatz867c0d72017-03-07 18:23:42 -08006606 /** TimeBase for when uid is in background and device is on battery. */
6607 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6608 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006609 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6610 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006611
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006612 boolean mWifiRunning;
6613 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006614
The Android Open Source Project10592532009-03-18 17:39:46 -07006615 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006616 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006617
Nick Pelly6ccaa542012-06-15 15:22:47 -07006618 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006619 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006620
Dianne Hackborn61659e52014-07-09 16:13:01 -07006621 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006622 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6623 StopwatchTimer[] mWifiBatchedScanTimer;
6624
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006625 boolean mWifiMulticastEnabled;
6626 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006627
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006628 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006629 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006630 StopwatchTimer mFlashlightTurnedOnTimer;
6631 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006632 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006633 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006634 /** Total time spent by the uid holding any partial wakelocks. */
6635 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006636 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006637 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006638 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006639 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006640
Dianne Hackborna8d10942015-11-19 17:55:19 -08006641 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006642 StopwatchTimer[] mProcessStateTimer;
6643
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006644 boolean mInForegroundService = false;
6645
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006646 BatchTimer mVibratorOnTimer;
6647
Dianne Hackborn617f8772009-03-31 15:04:46 -07006648 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006649
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006650 LongSamplingCounter[] mNetworkByteActivityCounters;
6651 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006652 LongSamplingCounter mMobileRadioActiveTime;
6653 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006656 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6657 */
6658 private LongSamplingCounter mMobileRadioApWakeupCount;
6659
6660 /**
6661 * How many times this UID woke up the Application Processor due to a Wifi packet.
6662 */
6663 private LongSamplingCounter mWifiRadioApWakeupCount;
6664
6665 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006666 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006667 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006668 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006669 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006670
6671 /**
6672 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006673 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006674 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006675 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6676
6677 /**
6678 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6679 * Can be null if the UID has had no such activity.
6680 */
6681 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006682
6683 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006684 * The CPU times we had at the last history details update.
6685 */
6686 long mLastStepUserTime;
6687 long mLastStepSystemTime;
6688 long mCurStepUserTime;
6689 long mCurStepSystemTime;
6690
Joe Onoratoabded112016-02-08 16:49:39 -08006691 LongSamplingCounter mUserCpuTime;
6692 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006693 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006694 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006695
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006696 LongSamplingCounterArray mCpuFreqTimeMs;
6697 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006698 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006699
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006700 LongSamplingCounterArray[] mProcStateTimeMs;
6701 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6702
6703 IntArray mChildUids;
6704
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006705 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 * The statistics we have collected for this uid's wake locks.
6707 */
Joe Onoratoabded112016-02-08 16:49:39 -08006708 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709
6710 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006711 * The statistics we have collected for this uid's syncs.
6712 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006713 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006714
6715 /**
6716 * The statistics we have collected for this uid's jobs.
6717 */
Bookatzaa4594a2017-03-24 12:39:56 -07006718 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006719
6720 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006721 * Count of the jobs that have completed and the reasons why they completed.
6722 */
6723 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6724
6725 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 * The statistics we have collected for this uid's sensor activations.
6727 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006728 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729
6730 /**
6731 * The statistics we have collected for this uid's processes.
6732 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006733 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734
6735 /**
6736 * The statistics we have collected for this uid's processes.
6737 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006738 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006739
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006740 /**
6741 * The transient wake stats we have collected for this uid's pids.
6742 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006743 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006744
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00006745 /**
6746 * The list of WorkChains associated with active bluetooth scans.
6747 *
6748 * NOTE: This is a hack and it only needs to exist because there's a "reset" API that is
6749 * supposed to stop and log all WorkChains that were currently active.
6750 */
6751 ArrayList<WorkChain> mAllBluetoothChains = null;
6752 ArrayList<WorkChain> mUnoptimizedBluetoothChains = null;
6753
Joe Onoratoabded112016-02-08 16:49:39 -08006754 public Uid(BatteryStatsImpl bsi, int uid) {
6755 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006756 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006757
Bookatz867c0d72017-03-07 18:23:42 -08006758 mOnBatteryBackgroundTimeBase = new TimeBase();
6759 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6760 mBsi.mClocks.elapsedRealtime() * 1000);
6761
Bookatzc8c44962017-05-11 12:12:54 -07006762 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6763 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6764 mBsi.mClocks.elapsedRealtime() * 1000);
6765
Joe Onoratoabded112016-02-08 16:49:39 -08006766 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6767 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006768 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6769 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006770
Dianne Hackborn657153b2016-07-29 14:54:14 -07006771 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006772 @Override public Wakelock instantiateObject() {
6773 return new Wakelock(mBsi, Uid.this);
6774 }
6775 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006776 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6777 @Override public DualTimer instantiateObject() {
6778 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6779 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006780 }
6781 };
Bookatzaa4594a2017-03-24 12:39:56 -07006782 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6783 @Override public DualTimer instantiateObject() {
6784 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6785 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006786 }
6787 };
6788
6789 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6790 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6791 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6792 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006793 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6794 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006795 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006796 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6797 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006798 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 }
6800
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006801 @VisibleForTesting
6802 public void setProcessStateForTest(int procState) {
6803 mProcessState = procState;
6804 }
6805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006806 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006807 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006808 return nullIfAllZeros(mCpuFreqTimeMs, which);
6809 }
6810
6811 @Override
6812 public long[] getScreenOffCpuFreqTimes(int which) {
6813 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6814 }
6815
6816 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006817 public long getCpuActiveTime() {
6818 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6819 }
6820
6821 @Override
6822 public long[] getCpuClusterTimes() {
6823 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6824 }
6825
6826
6827 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006828 public long[] getCpuFreqTimes(int which, int procState) {
6829 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006830 return null;
6831 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006832 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006833 return null;
6834 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006835 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6836 mProcStateTimeMs = null;
6837 return null;
6838 }
6839 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6840 }
6841
6842 @Override
6843 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6844 if (which < 0 || which >= NUM_PROCESS_STATE) {
6845 return null;
6846 }
6847 if (mProcStateScreenOffTimeMs == null) {
6848 return null;
6849 }
6850 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6851 mProcStateScreenOffTimeMs = null;
6852 return null;
6853 }
6854 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6855 }
6856
6857 public void addIsolatedUid(int isolatedUid) {
6858 if (mChildUids == null) {
6859 mChildUids = new IntArray();
6860 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6861 return;
6862 }
6863 mChildUids.add(isolatedUid);
6864 }
6865
6866 public void removeIsolatedUid(int isolatedUid) {
6867 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6868 if (idx < 0) {
6869 return;
6870 }
6871 mChildUids.remove(idx);
6872 }
6873
6874 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6875 if (cpuTimesMs == null) {
6876 return null;
6877 }
6878 final long[] counts = cpuTimesMs.getCountsLocked(which);
6879 if (counts == null) {
6880 return null;
6881 }
6882 // Return counts only if at least one of the elements is non-zero.
6883 for (int i = counts.length - 1; i >= 0; --i) {
6884 if (counts[i] != 0) {
6885 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006886 }
6887 }
6888 return null;
6889 }
6890
Sudheer Shankae544d162017-12-28 17:06:20 -08006891 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006892 if (mProcStateTimeMs == null) {
6893 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006894 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006895 if (mProcStateTimeMs[procState] == null
6896 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
6897 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6898 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006899 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006900 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006901 }
6902
Sudheer Shankae544d162017-12-28 17:06:20 -08006903 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6904 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006905 if (mProcStateScreenOffTimeMs == null) {
6906 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006907 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006908 if (mProcStateScreenOffTimeMs[procState] == null
6909 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
6910 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
6911 mBsi.mOnBatteryScreenOffTimeBase);
6912 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006913 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006914 }
6915
6916 @Override
Bookatzc8c44962017-05-11 12:12:54 -07006917 public Timer getAggregatedPartialWakelockTimer() {
6918 return mAggregatedPartialWakelockTimer;
6919 }
6920
6921 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006922 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006923 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006924 }
6925
6926 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07006927 public Timer getMulticastWakelockStats() {
6928 return mWifiMulticastTimer;
6929 }
6930
6931 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006932 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006933 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006934 }
6935
6936 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006937 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006938 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006939 }
6940
6941 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006942 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
6943 return mJobCompletions;
6944 }
6945
6946 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07006947 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 return mSensorStats;
6949 }
6950
6951 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006952 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006953 return mProcessStats;
6954 }
6955
6956 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006957 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 return mPackageStats;
6959 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006960
6961 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 public int getUid() {
6963 return mUid;
6964 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006965
6966 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006967 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006968 if (!mWifiRunning) {
6969 mWifiRunning = true;
6970 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006971 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
6972 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006973 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006974 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006975 }
6976 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006977
Dianne Hackborn617f8772009-03-31 15:04:46 -07006978 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006979 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006980 if (mWifiRunning) {
6981 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006982 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006983 }
6984 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006985
Dianne Hackborn617f8772009-03-31 15:04:46 -07006986 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006987 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006988 if (!mFullWifiLockOut) {
6989 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006990 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006991 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
6992 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006993 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006994 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006995 }
6996 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006997
The Android Open Source Project10592532009-03-18 17:39:46 -07006998 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006999 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007000 if (mFullWifiLockOut) {
7001 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007002 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007003 }
7004 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007005
The Android Open Source Project10592532009-03-18 17:39:46 -07007006 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007007 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007008 if (!mWifiScanStarted) {
7009 mWifiScanStarted = true;
7010 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007011 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7012 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
7013 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007014 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007015 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007016 }
7017 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007018
The Android Open Source Project10592532009-03-18 17:39:46 -07007019 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007020 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007021 if (mWifiScanStarted) {
7022 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007023 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007024 }
7025 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007026
7027 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007028 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007029 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007030 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007031 csph = csph >> 3;
7032 bin++;
7033 }
7034
7035 if (mWifiBatchedScanBinStarted == bin) return;
7036
7037 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7038 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007039 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007040 }
7041 mWifiBatchedScanBinStarted = bin;
7042 if (mWifiBatchedScanTimer[bin] == null) {
7043 makeWifiBatchedScanBin(bin, null);
7044 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007045 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007046 }
7047
7048 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007049 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007050 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7051 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007052 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007053 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7054 }
7055 }
7056
7057 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007058 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007059 if (!mWifiMulticastEnabled) {
7060 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007061 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007062 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7063 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007064 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007065 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007066 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007067 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7068 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007069 }
7070 }
7071
7072 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007073 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007074 if (mWifiMulticastEnabled) {
7075 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007076 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007077 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007078 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7079 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007080 }
7081 }
7082
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007083 @Override
7084 public ControllerActivityCounter getWifiControllerActivity() {
7085 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007086 }
7087
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007088 @Override
7089 public ControllerActivityCounter getBluetoothControllerActivity() {
7090 return mBluetoothControllerActivity;
7091 }
7092
7093 @Override
7094 public ControllerActivityCounter getModemControllerActivity() {
7095 return mModemControllerActivity;
7096 }
7097
7098 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7099 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007100 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007101 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007102 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007103 return mWifiControllerActivity;
7104 }
7105
7106 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7107 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007108 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007109 NUM_BT_TX_LEVELS);
7110 }
7111 return mBluetoothControllerActivity;
7112 }
7113
7114 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7115 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007116 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007117 ModemActivityInfo.TX_POWER_LEVELS);
7118 }
7119 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007120 }
7121
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007122 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7123 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007124 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7125 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007126 }
7127 return mAudioTurnedOnTimer;
7128 }
7129
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007130 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007131 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007132 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7133 StatsLog.AUDIO_STATE_CHANGED__STATE__ON);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007134 }
7135
7136 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7137 if (mAudioTurnedOnTimer != null) {
7138 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007139 if (!mAudioTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08007140 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7141 StatsLog.AUDIO_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007142 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007143 }
7144 }
7145
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007146 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7147 if (mAudioTurnedOnTimer != null) {
7148 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007149 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7150 StatsLog.AUDIO_STATE_CHANGED__STATE__OFF);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007151 }
7152 }
7153
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007154 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7155 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007156 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7157 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007158 }
7159 return mVideoTurnedOnTimer;
7160 }
7161
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007162 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007163 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007164 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
7165 StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__ON);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007166 }
7167
7168 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7169 if (mVideoTurnedOnTimer != null) {
7170 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007171 if (!mVideoTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007172 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(),
Bookatz90867622018-01-31 15:05:57 -08007173 null, StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007174 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007175 }
7176 }
7177
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007178 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7179 if (mVideoTurnedOnTimer != null) {
7180 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007181 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08007182 StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__OFF);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007183 }
7184 }
7185
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007186 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7187 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007188 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7189 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007190 }
7191 return mFlashlightTurnedOnTimer;
7192 }
7193
7194 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7195 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007196 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7197 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__ON);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007198 }
7199
7200 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7201 if (mFlashlightTurnedOnTimer != null) {
7202 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007203 if (!mFlashlightTurnedOnTimer.isRunningLocked()) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08007204 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08007205 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007206 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007207 }
7208 }
7209
7210 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7211 if (mFlashlightTurnedOnTimer != null) {
7212 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007213 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7214 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__OFF);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007215 }
7216 }
7217
7218 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7219 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007220 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7221 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007222 }
7223 return mCameraTurnedOnTimer;
7224 }
7225
7226 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7227 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007228 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7229 StatsLog.CAMERA_STATE_CHANGED__STATE__ON);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007230 }
7231
7232 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7233 if (mCameraTurnedOnTimer != null) {
7234 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007235 if (!mCameraTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08007236 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7237 StatsLog.CAMERA_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007238 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007239 }
7240 }
7241
7242 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7243 if (mCameraTurnedOnTimer != null) {
7244 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007245 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7246 StatsLog.CAMERA_STATE_CHANGED__STATE__OFF);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007247 }
7248 }
7249
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007250 public StopwatchTimer createForegroundActivityTimerLocked() {
7251 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007252 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7253 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007254 }
7255 return mForegroundActivityTimer;
7256 }
7257
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007258 public StopwatchTimer createForegroundServiceTimerLocked() {
7259 if (mForegroundServiceTimer == null) {
7260 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7261 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7262 }
7263 return mForegroundServiceTimer;
7264 }
7265
Bookatzc8c44962017-05-11 12:12:54 -07007266 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7267 if (mAggregatedPartialWakelockTimer == null) {
7268 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7269 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7270 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7271 }
7272 return mAggregatedPartialWakelockTimer;
7273 }
7274
Bookatz867c0d72017-03-07 18:23:42 -08007275 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007276 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007277 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7278 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7279 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007280 }
7281 return mBluetoothScanTimer;
7282 }
7283
Bookatzb1f04f32017-05-19 13:57:32 -07007284 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7285 if (mBluetoothUnoptimizedScanTimer == null) {
7286 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7287 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7288 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7289 }
7290 return mBluetoothUnoptimizedScanTimer;
7291 }
7292
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007293 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7294 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007295 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007296 if (isUnoptimized) {
7297 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7298 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007299 }
7300
Bookatz94c5a312017-07-11 16:49:17 -07007301 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007302 if (mBluetoothScanTimer != null) {
7303 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7304 }
Bookatz94c5a312017-07-11 16:49:17 -07007305 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007306 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7307 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007308 }
7309
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007310 public void addBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7311 if (mAllBluetoothChains == null) {
7312 mAllBluetoothChains = new ArrayList<WorkChain>(4);
7313 }
7314
7315 if (isUnoptimized && mUnoptimizedBluetoothChains == null) {
7316 mUnoptimizedBluetoothChains = new ArrayList<WorkChain>(4);
7317 }
7318
7319 mAllBluetoothChains.add(workChain);
7320 if (isUnoptimized) {
7321 mUnoptimizedBluetoothChains.add(workChain);
7322 }
7323 }
7324
7325 public void removeBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7326 if (mAllBluetoothChains != null) {
7327 mAllBluetoothChains.remove(workChain);
7328 }
7329
7330 if (isUnoptimized && mUnoptimizedBluetoothChains != null) {
7331 mUnoptimizedBluetoothChains.remove(workChain);
7332 }
7333 }
7334
7335 public List<WorkChain> getAllBluetoothWorkChains() {
7336 return mAllBluetoothChains;
7337 }
7338
7339 public List<WorkChain> getUnoptimizedBluetoothWorkChains() {
7340 return mUnoptimizedBluetoothChains;
7341 }
7342
7343
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007344 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7345 if (mBluetoothScanTimer != null) {
7346 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7347 }
Bookatzb1f04f32017-05-19 13:57:32 -07007348 if (mBluetoothUnoptimizedScanTimer != null) {
7349 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7350 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007351 }
7352
Bookatz956f36bf2017-04-28 09:48:17 -07007353 public Counter createBluetoothScanResultCounterLocked() {
7354 if (mBluetoothScanResultCounter == null) {
7355 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7356 }
7357 return mBluetoothScanResultCounter;
7358 }
7359
Bookatzb1f04f32017-05-19 13:57:32 -07007360 public Counter createBluetoothScanResultBgCounterLocked() {
7361 if (mBluetoothScanResultBgCounter == null) {
7362 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7363 }
7364 return mBluetoothScanResultBgCounter;
7365 }
7366
Bookatz4ebc0642017-05-11 12:21:19 -07007367 public void noteBluetoothScanResultsLocked(int numNewResults) {
7368 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007369 // Uses background timebase, so the count will only be incremented if uid in background.
7370 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007371 }
7372
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007373 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007374 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007375 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007376 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007377 }
7378
7379 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007380 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007381 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007382 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007383 }
7384 }
7385
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007386 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7387 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7388 }
7389
7390 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7391 if (mForegroundServiceTimer != null) {
7392 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7393 }
7394 }
7395
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007396 public BatchTimer createVibratorOnTimerLocked() {
7397 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007398 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7399 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007400 }
7401 return mVibratorOnTimer;
7402 }
7403
7404 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007405 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007406 }
7407
7408 public void noteVibratorOffLocked() {
7409 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007410 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007411 }
7412 }
7413
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007414 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007415 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007416 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007417 return 0;
7418 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007419 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007420 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007421
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007422 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007423 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007424 if (mFullWifiLockTimer == null) {
7425 return 0;
7426 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007427 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007428 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007429
7430 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007431 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007432 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007433 return 0;
7434 }
Bookatzaa4594a2017-03-24 12:39:56 -07007435 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007436 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007437
7438 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007439 public int getWifiScanCount(int which) {
7440 if (mWifiScanTimer == null) {
7441 return 0;
7442 }
Bookatzaa4594a2017-03-24 12:39:56 -07007443 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007444 }
7445
7446 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007447 public Timer getWifiScanTimer() {
7448 return mWifiScanTimer;
7449 }
7450
7451 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007452 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007453 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007454 return 0;
7455 }
7456 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7457 }
7458
7459 @Override
7460 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7461 if (mWifiScanTimer == null) {
7462 return 0;
7463 }
7464 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007465 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007466 }
7467
7468 @Override
7469 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007470 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007471 return 0;
7472 }
7473 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7474 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007475 }
7476
7477 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007478 public Timer getWifiScanBackgroundTimer() {
7479 if (mWifiScanTimer == null) {
7480 return null;
7481 }
7482 return mWifiScanTimer.getSubTimer();
7483 }
7484
7485 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007486 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007487 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7488 if (mWifiBatchedScanTimer[csphBin] == null) {
7489 return 0;
7490 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007491 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007492 }
7493
7494 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007495 public int getWifiBatchedScanCount(int csphBin, int which) {
7496 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7497 if (mWifiBatchedScanTimer[csphBin] == null) {
7498 return 0;
7499 }
7500 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7501 }
7502
7503 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007504 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007505 if (mWifiMulticastTimer == null) {
7506 return 0;
7507 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007508 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007509 }
7510
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007511 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007512 public Timer getAudioTurnedOnTimer() {
7513 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007514 }
7515
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007516 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007517 public Timer getVideoTurnedOnTimer() {
7518 return mVideoTurnedOnTimer;
7519 }
7520
7521 @Override
7522 public Timer getFlashlightTurnedOnTimer() {
7523 return mFlashlightTurnedOnTimer;
7524 }
7525
7526 @Override
7527 public Timer getCameraTurnedOnTimer() {
7528 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007529 }
7530
Dianne Hackborn617f8772009-03-31 15:04:46 -07007531 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007532 public Timer getForegroundActivityTimer() {
7533 return mForegroundActivityTimer;
7534 }
7535
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007536 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007537 public Timer getForegroundServiceTimer() {
7538 return mForegroundServiceTimer;
7539 }
7540
7541 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007542 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007543 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007544 }
7545
7546 @Override
7547 public Timer getBluetoothScanBackgroundTimer() {
7548 if (mBluetoothScanTimer == null) {
7549 return null;
7550 }
7551 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007552 }
7553
Bookatz956f36bf2017-04-28 09:48:17 -07007554 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007555 public Timer getBluetoothUnoptimizedScanTimer() {
7556 return mBluetoothUnoptimizedScanTimer;
7557 }
7558
7559 @Override
7560 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7561 if (mBluetoothUnoptimizedScanTimer == null) {
7562 return null;
7563 }
7564 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7565 }
7566
7567 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007568 public Counter getBluetoothScanResultCounter() {
7569 return mBluetoothScanResultCounter;
7570 }
7571
Bookatzb1f04f32017-05-19 13:57:32 -07007572 @Override
7573 public Counter getBluetoothScanResultBgCounter() {
7574 return mBluetoothScanResultBgCounter;
7575 }
7576
Dianne Hackborn61659e52014-07-09 16:13:01 -07007577 void makeProcessState(int i, Parcel in) {
7578 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7579
7580 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007581 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7582 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007583 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007584 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7585 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007586 }
7587 }
7588
7589 @Override
7590 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7591 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7592 if (mProcessStateTimer[state] == null) {
7593 return 0;
7594 }
7595 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7596 }
7597
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007598 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007599 public Timer getProcessStateTimer(int state) {
7600 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7601 return mProcessStateTimer[state];
7602 }
7603
7604 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007605 public Timer getVibratorOnTimer() {
7606 return mVibratorOnTimer;
7607 }
7608
7609 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007610 public void noteUserActivityLocked(int type) {
7611 if (mUserActivityCounters == null) {
7612 initUserActivityLocked();
7613 }
Jeff Browndf693de2012-07-27 12:03:38 -07007614 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7615 mUserActivityCounters[type].stepAtomic();
7616 } else {
7617 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7618 new Throwable());
7619 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007620 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007621
Dianne Hackborn617f8772009-03-31 15:04:46 -07007622 @Override
7623 public boolean hasUserActivity() {
7624 return mUserActivityCounters != null;
7625 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007626
Dianne Hackborn617f8772009-03-31 15:04:46 -07007627 @Override
7628 public int getUserActivityCount(int type, int which) {
7629 if (mUserActivityCounters == null) {
7630 return 0;
7631 }
Evan Millarc64edde2009-04-18 12:26:32 -07007632 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007633 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007634
Robert Greenwalta029ea12013-09-25 16:38:12 -07007635 void makeWifiBatchedScanBin(int i, Parcel in) {
7636 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7637
Joe Onoratoabded112016-02-08 16:49:39 -08007638 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007639 if (collected == null) {
7640 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007641 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007642 }
7643 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007644 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7645 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007646 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007647 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7648 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007649 }
7650 }
7651
7652
Dianne Hackborn617f8772009-03-31 15:04:46 -07007653 void initUserActivityLocked() {
7654 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7655 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007656 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007657 }
7658 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007659
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007660 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7661 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007662 initNetworkActivityLocked();
7663 }
7664 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007665 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7666 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007667 } else {
7668 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7669 new Throwable());
7670 }
7671 }
7672
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007673 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7674 if (mNetworkByteActivityCounters == null) {
7675 initNetworkActivityLocked();
7676 }
7677 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7678 mMobileRadioActiveCount.addCountLocked(1);
7679 }
7680
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007681 @Override
7682 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007683 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007684 }
7685
7686 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007687 public long getNetworkActivityBytes(int type, int which) {
7688 if (mNetworkByteActivityCounters != null && type >= 0
7689 && type < mNetworkByteActivityCounters.length) {
7690 return mNetworkByteActivityCounters[type].getCountLocked(which);
7691 } else {
7692 return 0;
7693 }
7694 }
7695
7696 @Override
7697 public long getNetworkActivityPackets(int type, int which) {
7698 if (mNetworkPacketActivityCounters != null && type >= 0
7699 && type < mNetworkPacketActivityCounters.length) {
7700 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007701 } else {
7702 return 0;
7703 }
7704 }
7705
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007706 @Override
7707 public long getMobileRadioActiveTime(int which) {
7708 return mMobileRadioActiveTime != null
7709 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7710 }
7711
7712 @Override
7713 public int getMobileRadioActiveCount(int which) {
7714 return mMobileRadioActiveCount != null
7715 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7716 }
7717
Adam Lesinskie08af192015-03-25 16:42:59 -07007718 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007719 public long getUserCpuTimeUs(int which) {
7720 return mUserCpuTime.getCountLocked(which);
7721 }
7722
7723 @Override
7724 public long getSystemCpuTimeUs(int which) {
7725 return mSystemCpuTime.getCountLocked(which);
7726 }
7727
7728 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007729 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007730 if (mCpuClusterSpeedTimesUs != null) {
7731 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7732 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7733 if (cpuSpeedTimesUs != null) {
7734 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7735 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007736 if (c != null) {
7737 return c.getCountLocked(which);
7738 }
7739 }
7740 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007741 }
7742 }
7743 return 0;
7744 }
7745
Adam Lesinski5f056f62016-07-14 16:56:08 -07007746 public void noteMobileRadioApWakeupLocked() {
7747 if (mMobileRadioApWakeupCount == null) {
7748 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7749 }
7750 mMobileRadioApWakeupCount.addCountLocked(1);
7751 }
7752
7753 @Override
7754 public long getMobileRadioApWakeupCount(int which) {
7755 if (mMobileRadioApWakeupCount != null) {
7756 return mMobileRadioApWakeupCount.getCountLocked(which);
7757 }
7758 return 0;
7759 }
7760
7761 public void noteWifiRadioApWakeupLocked() {
7762 if (mWifiRadioApWakeupCount == null) {
7763 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7764 }
7765 mWifiRadioApWakeupCount.addCountLocked(1);
7766 }
7767
7768 @Override
7769 public long getWifiRadioApWakeupCount(int which) {
7770 if (mWifiRadioApWakeupCount != null) {
7771 return mWifiRadioApWakeupCount.getCountLocked(which);
7772 }
7773 return 0;
7774 }
7775
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007776 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007777 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7778 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007779 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007780 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7781 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007782 }
Joe Onoratoabded112016-02-08 16:49:39 -08007783 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7784 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007786
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007787 /**
7788 * Clear all stats for this uid. Returns true if the uid is completely
7789 * inactive so can be dropped.
7790 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007791 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007792 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007793 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007794
Bookatz993a0be2017-07-21 09:03:23 -07007795 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7796 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7797
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007798 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007799 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007800 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007801 }
7802 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007803 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007804 active |= mFullWifiLockOut;
7805 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007806 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007807 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007808 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007809 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007810 if (mWifiBatchedScanTimer != null) {
7811 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7812 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007813 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007814 }
7815 }
7816 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7817 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007818 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007819 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007820 active |= mWifiMulticastEnabled;
7821 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007822
7823 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7824 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7825 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7826 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7827 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007828 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007829 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007830 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007831 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007832 if (mBluetoothScanResultCounter != null) {
7833 mBluetoothScanResultCounter.reset(false);
7834 }
Bookatzb1f04f32017-05-19 13:57:32 -07007835 if (mBluetoothScanResultBgCounter != null) {
7836 mBluetoothScanResultBgCounter.reset(false);
7837 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007838
Dianne Hackborn61659e52014-07-09 16:13:01 -07007839 if (mProcessStateTimer != null) {
7840 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7841 if (mProcessStateTimer[i] != null) {
7842 active |= !mProcessStateTimer[i].reset(false);
7843 }
7844 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007845 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007846 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007847 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007848 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007849 mVibratorOnTimer.detach();
7850 mVibratorOnTimer = null;
7851 } else {
7852 active = true;
7853 }
7854 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007855
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007856 if (mUserActivityCounters != null) {
7857 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7858 mUserActivityCounters[i].reset(false);
7859 }
7860 }
7861
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007862 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007863 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007864 mNetworkByteActivityCounters[i].reset(false);
7865 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007866 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007867 mMobileRadioActiveTime.reset(false);
7868 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007869 }
7870
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007871 if (mWifiControllerActivity != null) {
7872 mWifiControllerActivity.reset(false);
7873 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007874
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007875 if (mBluetoothControllerActivity != null) {
7876 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007877 }
7878
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007879 if (mModemControllerActivity != null) {
7880 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007881 }
7882
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007883 mUserCpuTime.reset(false);
7884 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007885
Sudheer Shankaaf857412017-07-21 00:14:24 -07007886 if (mCpuClusterSpeedTimesUs != null) {
7887 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007888 if (speeds != null) {
7889 for (LongSamplingCounter speed : speeds) {
7890 if (speed != null) {
7891 speed.reset(false);
7892 }
7893 }
7894 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007895 }
7896 }
7897
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007898 if (mCpuFreqTimeMs != null) {
7899 mCpuFreqTimeMs.reset(false);
7900 }
7901 if (mScreenOffCpuFreqTimeMs != null) {
7902 mScreenOffCpuFreqTimeMs.reset(false);
7903 }
7904
Mike Ma3d422c32017-10-25 11:08:57 -07007905 mCpuActiveTimeMs.reset(false);
7906 mCpuClusterTimesMs.reset(false);
7907
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007908 if (mProcStateTimeMs != null) {
7909 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7910 if (counters != null) {
7911 counters.reset(false);
7912 }
7913 }
7914 }
7915 if (mProcStateScreenOffTimeMs != null) {
7916 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7917 if (counters != null) {
7918 counters.reset(false);
7919 }
7920 }
7921 }
7922
Adam Lesinski5f056f62016-07-14 16:56:08 -07007923 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
7924 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
7925
Dianne Hackbornd953c532014-08-16 18:17:38 -07007926 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7927 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
7928 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007929 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007930 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007931 } else {
7932 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007933 }
7934 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007935 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07007936 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007937 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07007938 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007939 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007940 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007941 timer.detach();
7942 } else {
7943 active = true;
7944 }
7945 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007946 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07007947 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007948 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07007949 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007950 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007951 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007952 timer.detach();
7953 } else {
7954 active = true;
7955 }
7956 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007957 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007958 mJobCompletions.clear();
Dianne Hackborn61659e52014-07-09 16:13:01 -07007959 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
7960 Sensor s = mSensorStats.valueAt(ise);
7961 if (s.reset()) {
7962 mSensorStats.removeAt(ise);
7963 } else {
7964 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007965 }
7966 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07007967 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
7968 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08007969 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007970 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007971 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007972 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007973 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007974 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007975 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007976 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007977 } else {
7978 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007979 }
7980 }
7981 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007982 if (mPackageStats.size() > 0) {
7983 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
7984 while (it.hasNext()) {
7985 Map.Entry<String, Pkg> pkgEntry = it.next();
7986 Pkg p = pkgEntry.getValue();
7987 p.detach();
7988 if (p.mServiceStats.size() > 0) {
7989 Iterator<Map.Entry<String, Pkg.Serv>> it2
7990 = p.mServiceStats.entrySet().iterator();
7991 while (it2.hasNext()) {
7992 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
7993 servEntry.getValue().detach();
7994 }
7995 }
7996 }
7997 mPackageStats.clear();
7998 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007999
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008000 mLastStepUserTime = mLastStepSystemTime = 0;
8001 mCurStepUserTime = mCurStepSystemTime = 0;
8002
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008003 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008004 if (mWifiRunningTimer != null) {
8005 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008006 }
8007 if (mFullWifiLockTimer != null) {
8008 mFullWifiLockTimer.detach();
8009 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008010 if (mWifiScanTimer != null) {
8011 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008012 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008013 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8014 if (mWifiBatchedScanTimer[i] != null) {
8015 mWifiBatchedScanTimer[i].detach();
8016 }
8017 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008018 if (mWifiMulticastTimer != null) {
8019 mWifiMulticastTimer.detach();
8020 }
8021 if (mAudioTurnedOnTimer != null) {
8022 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008023 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008024 }
8025 if (mVideoTurnedOnTimer != null) {
8026 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008027 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008028 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008029 if (mFlashlightTurnedOnTimer != null) {
8030 mFlashlightTurnedOnTimer.detach();
8031 mFlashlightTurnedOnTimer = null;
8032 }
8033 if (mCameraTurnedOnTimer != null) {
8034 mCameraTurnedOnTimer.detach();
8035 mCameraTurnedOnTimer = null;
8036 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008037 if (mForegroundActivityTimer != null) {
8038 mForegroundActivityTimer.detach();
8039 mForegroundActivityTimer = null;
8040 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008041 if (mForegroundServiceTimer != null) {
8042 mForegroundServiceTimer.detach();
8043 mForegroundServiceTimer = null;
8044 }
Bookatzc8c44962017-05-11 12:12:54 -07008045 if (mAggregatedPartialWakelockTimer != null) {
8046 mAggregatedPartialWakelockTimer.detach();
8047 mAggregatedPartialWakelockTimer = null;
8048 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008049 if (mBluetoothScanTimer != null) {
8050 mBluetoothScanTimer.detach();
8051 mBluetoothScanTimer = null;
8052 }
Bookatzb1f04f32017-05-19 13:57:32 -07008053 if (mBluetoothUnoptimizedScanTimer != null) {
8054 mBluetoothUnoptimizedScanTimer.detach();
8055 mBluetoothUnoptimizedScanTimer = null;
8056 }
Bookatz956f36bf2017-04-28 09:48:17 -07008057 if (mBluetoothScanResultCounter != null) {
8058 mBluetoothScanResultCounter.detach();
8059 mBluetoothScanResultCounter = null;
8060 }
Bookatzb1f04f32017-05-19 13:57:32 -07008061 if (mBluetoothScanResultBgCounter != null) {
8062 mBluetoothScanResultBgCounter.detach();
8063 mBluetoothScanResultBgCounter = null;
8064 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008065 if (mUserActivityCounters != null) {
8066 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8067 mUserActivityCounters[i].detach();
8068 }
8069 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008070 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008071 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008072 mNetworkByteActivityCounters[i].detach();
8073 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008074 }
8075 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008076
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008077 if (mWifiControllerActivity != null) {
8078 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008079 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008080
8081 if (mBluetoothControllerActivity != null) {
8082 mBluetoothControllerActivity.detach();
8083 }
8084
8085 if (mModemControllerActivity != null) {
8086 mModemControllerActivity.detach();
8087 }
8088
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008089 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008090
8091 mUserCpuTime.detach();
8092 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008093
Sudheer Shankaaf857412017-07-21 00:14:24 -07008094 if (mCpuClusterSpeedTimesUs != null) {
8095 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008096 if (cpuSpeeds != null) {
8097 for (LongSamplingCounter c : cpuSpeeds) {
8098 if (c != null) {
8099 c.detach();
8100 }
8101 }
8102 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008103 }
8104 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008105
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008106 if (mCpuFreqTimeMs != null) {
8107 mCpuFreqTimeMs.detach();
8108 }
8109 if (mScreenOffCpuFreqTimeMs != null) {
8110 mScreenOffCpuFreqTimeMs.detach();
8111 }
Mike Ma3d422c32017-10-25 11:08:57 -07008112 mCpuActiveTimeMs.detach();
8113 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008114
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008115 if (mProcStateTimeMs != null) {
8116 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8117 if (counters != null) {
8118 counters.detach();
8119 }
8120 }
8121 }
8122 if (mProcStateScreenOffTimeMs != null) {
8123 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8124 if (counters != null) {
8125 counters.detach();
8126 }
8127 }
8128 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008129 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8130 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008131 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008132
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008133 return !active;
8134 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008135
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008136 void writeJobCompletionsToParcelLocked(Parcel out) {
8137 int NJC = mJobCompletions.size();
8138 out.writeInt(NJC);
8139 for (int ijc=0; ijc<NJC; ijc++) {
8140 out.writeString(mJobCompletions.keyAt(ijc));
8141 SparseIntArray types = mJobCompletions.valueAt(ijc);
8142 int NT = types.size();
8143 out.writeInt(NT);
8144 for (int it=0; it<NT; it++) {
8145 out.writeInt(types.keyAt(it));
8146 out.writeInt(types.valueAt(it));
8147 }
8148 }
8149 }
8150
Bookatz867c0d72017-03-07 18:23:42 -08008151 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8152 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008153 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008154
Dianne Hackbornd953c532014-08-16 18:17:38 -07008155 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8156 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008157 out.writeInt(NW);
8158 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008159 out.writeString(wakeStats.keyAt(iw));
8160 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008161 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 }
8163
Bookatz2bffb5b2017-04-13 11:59:33 -07008164 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008165 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008166 out.writeInt(NS);
8167 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008168 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008169 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008170 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8171 }
8172
Bookatzaa4594a2017-03-24 12:39:56 -07008173 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008174 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008175 out.writeInt(NJ);
8176 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008177 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008178 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008179 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8180 }
8181
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008182 writeJobCompletionsToParcelLocked(out);
8183
Dianne Hackborn61659e52014-07-09 16:13:01 -07008184 int NSE = mSensorStats.size();
8185 out.writeInt(NSE);
8186 for (int ise=0; ise<NSE; ise++) {
8187 out.writeInt(mSensorStats.keyAt(ise));
8188 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008189 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190 }
8191
Dianne Hackborn61659e52014-07-09 16:13:01 -07008192 int NP = mProcessStats.size();
8193 out.writeInt(NP);
8194 for (int ip=0; ip<NP; ip++) {
8195 out.writeString(mProcessStats.keyAt(ip));
8196 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008197 proc.writeToParcelLocked(out);
8198 }
8199
8200 out.writeInt(mPackageStats.size());
8201 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8202 out.writeString(pkgEntry.getKey());
8203 Uid.Pkg pkg = pkgEntry.getValue();
8204 pkg.writeToParcelLocked(out);
8205 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008206
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008207 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008208 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008209 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008210 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008211 out.writeInt(0);
8212 }
8213 if (mFullWifiLockTimer != null) {
8214 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008215 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008216 } else {
8217 out.writeInt(0);
8218 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008219 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008220 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008221 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008222 } else {
8223 out.writeInt(0);
8224 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008225 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8226 if (mWifiBatchedScanTimer[i] != null) {
8227 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008228 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008229 } else {
8230 out.writeInt(0);
8231 }
8232 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008233 if (mWifiMulticastTimer != null) {
8234 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008235 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008236 } else {
8237 out.writeInt(0);
8238 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008239
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008240 if (mAudioTurnedOnTimer != null) {
8241 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008242 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008243 } else {
8244 out.writeInt(0);
8245 }
8246 if (mVideoTurnedOnTimer != null) {
8247 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008248 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008249 } else {
8250 out.writeInt(0);
8251 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008252 if (mFlashlightTurnedOnTimer != null) {
8253 out.writeInt(1);
8254 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8255 } else {
8256 out.writeInt(0);
8257 }
8258 if (mCameraTurnedOnTimer != null) {
8259 out.writeInt(1);
8260 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8261 } else {
8262 out.writeInt(0);
8263 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008264 if (mForegroundActivityTimer != null) {
8265 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008266 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008267 } else {
8268 out.writeInt(0);
8269 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008270 if (mForegroundServiceTimer != null) {
8271 out.writeInt(1);
8272 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8273 } else {
8274 out.writeInt(0);
8275 }
Bookatzc8c44962017-05-11 12:12:54 -07008276 if (mAggregatedPartialWakelockTimer != null) {
8277 out.writeInt(1);
8278 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8279 } else {
8280 out.writeInt(0);
8281 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008282 if (mBluetoothScanTimer != null) {
8283 out.writeInt(1);
8284 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8285 } else {
8286 out.writeInt(0);
8287 }
Bookatzb1f04f32017-05-19 13:57:32 -07008288 if (mBluetoothUnoptimizedScanTimer != null) {
8289 out.writeInt(1);
8290 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8291 } else {
8292 out.writeInt(0);
8293 }
Bookatz956f36bf2017-04-28 09:48:17 -07008294 if (mBluetoothScanResultCounter != null) {
8295 out.writeInt(1);
8296 mBluetoothScanResultCounter.writeToParcel(out);
8297 } else {
8298 out.writeInt(0);
8299 }
Bookatzb1f04f32017-05-19 13:57:32 -07008300 if (mBluetoothScanResultBgCounter != null) {
8301 out.writeInt(1);
8302 mBluetoothScanResultBgCounter.writeToParcel(out);
8303 } else {
8304 out.writeInt(0);
8305 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008306 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8307 if (mProcessStateTimer[i] != null) {
8308 out.writeInt(1);
8309 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8310 } else {
8311 out.writeInt(0);
8312 }
8313 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008314 if (mVibratorOnTimer != null) {
8315 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008316 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008317 } else {
8318 out.writeInt(0);
8319 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008320 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008321 out.writeInt(1);
8322 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8323 mUserActivityCounters[i].writeToParcel(out);
8324 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008325 } else {
8326 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008327 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008328 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008329 out.writeInt(1);
8330 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008331 mNetworkByteActivityCounters[i].writeToParcel(out);
8332 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008333 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008334 mMobileRadioActiveTime.writeToParcel(out);
8335 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008336 } else {
8337 out.writeInt(0);
8338 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008339
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008340 if (mWifiControllerActivity != null) {
8341 out.writeInt(1);
8342 mWifiControllerActivity.writeToParcel(out, 0);
8343 } else {
8344 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008345 }
8346
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008347 if (mBluetoothControllerActivity != null) {
8348 out.writeInt(1);
8349 mBluetoothControllerActivity.writeToParcel(out, 0);
8350 } else {
8351 out.writeInt(0);
8352 }
8353
8354 if (mModemControllerActivity != null) {
8355 out.writeInt(1);
8356 mModemControllerActivity.writeToParcel(out, 0);
8357 } else {
8358 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008359 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008360
8361 mUserCpuTime.writeToParcel(out);
8362 mSystemCpuTime.writeToParcel(out);
8363
Sudheer Shankaaf857412017-07-21 00:14:24 -07008364 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008365 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008366 out.writeInt(mCpuClusterSpeedTimesUs.length);
8367 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008368 if (cpuSpeeds != null) {
8369 out.writeInt(1);
8370 out.writeInt(cpuSpeeds.length);
8371 for (LongSamplingCounter c : cpuSpeeds) {
8372 if (c != null) {
8373 out.writeInt(1);
8374 c.writeToParcel(out);
8375 } else {
8376 out.writeInt(0);
8377 }
8378 }
8379 } else {
8380 out.writeInt(0);
8381 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008382 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008383 } else {
8384 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008385 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008386
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008387 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8388 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008389
8390 mCpuActiveTimeMs.writeToParcel(out);
8391 mCpuClusterTimesMs.writeToParcel(out);
8392
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008393 if (mProcStateTimeMs != null) {
8394 out.writeInt(mProcStateTimeMs.length);
8395 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8396 LongSamplingCounterArray.writeToParcel(out, counters);
8397 }
8398 } else {
8399 out.writeInt(0);
8400 }
8401 if (mProcStateScreenOffTimeMs != null) {
8402 out.writeInt(mProcStateScreenOffTimeMs.length);
8403 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8404 LongSamplingCounterArray.writeToParcel(out, counters);
8405 }
8406 } else {
8407 out.writeInt(0);
8408 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008409
Adam Lesinski5f056f62016-07-14 16:56:08 -07008410 if (mMobileRadioApWakeupCount != null) {
8411 out.writeInt(1);
8412 mMobileRadioApWakeupCount.writeToParcel(out);
8413 } else {
8414 out.writeInt(0);
8415 }
8416
8417 if (mWifiRadioApWakeupCount != null) {
8418 out.writeInt(1);
8419 mWifiRadioApWakeupCount.writeToParcel(out);
8420 } else {
8421 out.writeInt(0);
8422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008423 }
8424
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008425 void readJobCompletionsFromParcelLocked(Parcel in) {
8426 int numJobCompletions = in.readInt();
8427 mJobCompletions.clear();
8428 for (int j = 0; j < numJobCompletions; j++) {
8429 String jobName = in.readString();
8430 int numTypes = in.readInt();
8431 if (numTypes > 0) {
8432 SparseIntArray types = new SparseIntArray();
8433 for (int k = 0; k < numTypes; k++) {
8434 int type = in.readInt();
8435 int count = in.readInt();
8436 types.put(type, count);
8437 }
8438 mJobCompletions.put(jobName, types);
8439 }
8440 }
8441 }
8442
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008443 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008444 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008445 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008447 int numWakelocks = in.readInt();
8448 mWakelockStats.clear();
8449 for (int j = 0; j < numWakelocks; j++) {
8450 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008451 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008452 wakelock.readFromParcelLocked(
8453 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008454 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008455 }
8456
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008457 int numSyncs = in.readInt();
8458 mSyncStats.clear();
8459 for (int j = 0; j < numSyncs; j++) {
8460 String syncName = in.readString();
8461 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008462 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8463 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008464 }
8465 }
8466
8467 int numJobs = in.readInt();
8468 mJobStats.clear();
8469 for (int j = 0; j < numJobs; j++) {
8470 String jobName = in.readString();
8471 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008472 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8473 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008474 }
8475 }
8476
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008477 readJobCompletionsFromParcelLocked(in);
8478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008479 int numSensors = in.readInt();
8480 mSensorStats.clear();
8481 for (int k = 0; k < numSensors; k++) {
8482 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008483 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008484 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8485 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008486 mSensorStats.put(sensorNumber, sensor);
8487 }
8488
8489 int numProcs = in.readInt();
8490 mProcessStats.clear();
8491 for (int k = 0; k < numProcs; k++) {
8492 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008493 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 proc.readFromParcelLocked(in);
8495 mProcessStats.put(processName, proc);
8496 }
8497
8498 int numPkgs = in.readInt();
8499 mPackageStats.clear();
8500 for (int l = 0; l < numPkgs; l++) {
8501 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008502 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 pkg.readFromParcelLocked(in);
8504 mPackageStats.put(packageName, pkg);
8505 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008506
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008507 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008508 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008509 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8510 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008511 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008512 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008513 }
8514 mFullWifiLockOut = false;
8515 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008516 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8517 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008518 } else {
8519 mFullWifiLockTimer = null;
8520 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008521 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008522 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008523 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8524 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8525 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008526 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008527 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008528 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008529 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8530 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8531 if (in.readInt() != 0) {
8532 makeWifiBatchedScanBin(i, in);
8533 } else {
8534 mWifiBatchedScanTimer[i] = null;
8535 }
8536 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008537 mWifiMulticastEnabled = false;
8538 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008539 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8540 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008541 } else {
8542 mWifiMulticastTimer = null;
8543 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008544 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008545 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8546 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008547 } else {
8548 mAudioTurnedOnTimer = null;
8549 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008550 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008551 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8552 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008553 } else {
8554 mVideoTurnedOnTimer = null;
8555 }
8556 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008557 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8558 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008559 } else {
8560 mFlashlightTurnedOnTimer = null;
8561 }
8562 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008563 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8564 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008565 } else {
8566 mCameraTurnedOnTimer = null;
8567 }
8568 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008569 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8570 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008571 } else {
8572 mForegroundActivityTimer = null;
8573 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008574 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008575 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8576 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8577 } else {
8578 mForegroundServiceTimer = null;
8579 }
8580 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008581 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8582 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8583 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8584 in);
8585 } else {
8586 mAggregatedPartialWakelockTimer = null;
8587 }
8588 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008589 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8590 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8591 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008592 } else {
8593 mBluetoothScanTimer = null;
8594 }
Bookatz956f36bf2017-04-28 09:48:17 -07008595 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008596 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8597 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8598 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8599 } else {
8600 mBluetoothUnoptimizedScanTimer = null;
8601 }
8602 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008603 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8604 } else {
8605 mBluetoothScanResultCounter = null;
8606 }
Bookatzb1f04f32017-05-19 13:57:32 -07008607 if (in.readInt() != 0) {
8608 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8609 } else {
8610 mBluetoothScanResultBgCounter = null;
8611 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008612 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008613 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8614 if (in.readInt() != 0) {
8615 makeProcessState(i, in);
8616 } else {
8617 mProcessStateTimer[i] = null;
8618 }
8619 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008620 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008621 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8622 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008623 } else {
8624 mVibratorOnTimer = null;
8625 }
8626 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008627 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8628 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008629 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008630 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008631 } else {
8632 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008633 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008634 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008635 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8636 mNetworkPacketActivityCounters
8637 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008638 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008639 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008640 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008641 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008642 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008643 }
Joe Onoratoabded112016-02-08 16:49:39 -08008644 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8645 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008646 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008647 mNetworkByteActivityCounters = null;
8648 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008649 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008650
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008651 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008652 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008653 NUM_WIFI_TX_LEVELS, in);
8654 } else {
8655 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008656 }
8657
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008658 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008659 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008660 NUM_BT_TX_LEVELS, in);
8661 } else {
8662 mBluetoothControllerActivity = null;
8663 }
8664
8665 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008666 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008667 ModemActivityInfo.TX_POWER_LEVELS, in);
8668 } else {
8669 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008670 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008671
Joe Onoratoabded112016-02-08 16:49:39 -08008672 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8673 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008674
Adam Lesinski6832f392015-09-05 18:05:40 -07008675 if (in.readInt() != 0) {
8676 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008677 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008678 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008679 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008680
Sudheer Shankaaf857412017-07-21 00:14:24 -07008681 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008682 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8683 if (in.readInt() != 0) {
8684 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008685 if (mBsi.mPowerProfile != null &&
8686 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008687 throw new ParcelFormatException("Incompatible number of cpu speeds");
8688 }
8689
8690 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008691 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008692 for (int speed = 0; speed < numSpeeds; speed++) {
8693 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008694 cpuSpeeds[speed] = new LongSamplingCounter(
8695 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008696 }
8697 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008698 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008699 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008700 }
8701 }
8702 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008703 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008704 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008705
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008706 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8707 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8708 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008709
Mike Ma3d422c32017-10-25 11:08:57 -07008710 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8711 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8712
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008713 int length = in.readInt();
8714 if (length == NUM_PROCESS_STATE) {
8715 mProcStateTimeMs = new LongSamplingCounterArray[length];
8716 for (int procState = 0; procState < length; ++procState) {
8717 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8718 in, mBsi.mOnBatteryTimeBase);
8719 }
8720 } else {
8721 mProcStateTimeMs = null;
8722 }
8723 length = in.readInt();
8724 if (length == NUM_PROCESS_STATE) {
8725 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8726 for (int procState = 0; procState < length; ++procState) {
8727 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8728 in, mBsi.mOnBatteryScreenOffTimeBase);
8729 }
8730 } else {
8731 mProcStateScreenOffTimeMs = null;
8732 }
8733
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008734 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008735 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8736 } else {
8737 mMobileRadioApWakeupCount = null;
8738 }
8739
8740 if (in.readInt() != 0) {
8741 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8742 } else {
8743 mWifiRadioApWakeupCount = null;
8744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008745 }
8746
8747 /**
8748 * The statistics associated with a particular wake lock.
8749 */
Joe Onoratoabded112016-02-08 16:49:39 -08008750 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8751 /**
8752 * BatteryStatsImpl that we are associated with.
8753 */
8754 protected BatteryStatsImpl mBsi;
8755
8756 /**
8757 * BatteryStatsImpl that we are associated with.
8758 */
8759 protected Uid mUid;
8760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 /**
8762 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008763 * 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 -08008764 */
Bookatz5b5ec322017-05-26 09:40:38 -07008765 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766
8767 /**
8768 * How long (in ms) this uid has been keeping the device fully awake.
8769 */
Evan Millarc64edde2009-04-18 12:26:32 -07008770 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771
8772 /**
8773 * How long (in ms) this uid has had a window keeping the device awake.
8774 */
Evan Millarc64edde2009-04-18 12:26:32 -07008775 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776
8777 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008778 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008779 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008780 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008781
Joe Onoratoabded112016-02-08 16:49:39 -08008782 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8783 mBsi = bsi;
8784 mUid = uid;
8785 }
8786
Adam Lesinski9425fe22015-06-19 12:02:13 -07008787 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8789 * proper timer pool from the given BatteryStatsImpl object.
8790 *
8791 * @param in the Parcel to be read from.
8792 * return a new Timer, or null.
8793 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008794 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8795 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008796 if (in.readInt() == 0) {
8797 return null;
8798 }
8799
Joe Onoratoabded112016-02-08 16:49:39 -08008800 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008801 }
8802
Joe Onorato92fd23f2016-07-25 11:18:42 -07008803 /**
8804 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8805 * proper timer pool from the given BatteryStatsImpl object.
8806 *
8807 * @param in the Parcel to be read from.
8808 * return a new Timer, or null.
8809 */
Bookatz5b5ec322017-05-26 09:40:38 -07008810 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8811 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008812 if (in.readInt() == 0) {
8813 return null;
8814 }
8815
Bookatz5b5ec322017-05-26 09:40:38 -07008816 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008817 }
8818
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008819 boolean reset() {
8820 boolean wlactive = false;
8821 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008822 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008823 }
8824 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008825 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008826 }
8827 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008828 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008829 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008830 if (mTimerDraw != null) {
8831 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008832 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008833 if (!wlactive) {
8834 if (mTimerFull != null) {
8835 mTimerFull.detach();
8836 mTimerFull = null;
8837 }
8838 if (mTimerPartial != null) {
8839 mTimerPartial.detach();
8840 mTimerPartial = null;
8841 }
8842 if (mTimerWindow != null) {
8843 mTimerWindow.detach();
8844 mTimerWindow = null;
8845 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008846 if (mTimerDraw != null) {
8847 mTimerDraw.detach();
8848 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008849 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008850 }
8851 return !wlactive;
8852 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008853
Bookatz5b5ec322017-05-26 09:40:38 -07008854 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
8855 TimeBase screenOffBgTimeBase, Parcel in) {
8856 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
8857 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008858 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
8859 mBsi.mFullTimers, timeBase, in);
8860 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
8861 mBsi.mWindowTimers, timeBase, in);
8862 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
8863 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 }
8865
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008866 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
8867 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
8868 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
8869 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008870 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008871 }
8872
8873 @Override
8874 public Timer getWakeTime(int type) {
8875 switch (type) {
8876 case WAKE_TYPE_FULL: return mTimerFull;
8877 case WAKE_TYPE_PARTIAL: return mTimerPartial;
8878 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008879 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008880 default: throw new IllegalArgumentException("type = " + type);
8881 }
8882 }
8883 }
8884
Joe Onoratoabded112016-02-08 16:49:39 -08008885 public static class Sensor extends BatteryStats.Uid.Sensor {
8886 /**
8887 * BatteryStatsImpl that we are associated with.
8888 */
8889 protected BatteryStatsImpl mBsi;
8890
8891 /**
Bookatz867c0d72017-03-07 18:23:42 -08008892 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08008893 */
8894 protected Uid mUid;
8895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008896 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08008897 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008898
Joe Onoratoabded112016-02-08 16:49:39 -08008899 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
8900 mBsi = bsi;
8901 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008902 mHandle = handle;
8903 }
8904
Bookatz867c0d72017-03-07 18:23:42 -08008905 private DualTimer readTimersFromParcel(
8906 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 if (in.readInt() == 0) {
8908 return null;
8909 }
8910
Joe Onoratoabded112016-02-08 16:49:39 -08008911 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008912 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07008913 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08008914 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 }
Bookatz867c0d72017-03-07 18:23:42 -08008916 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008917 }
8918
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008919 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008920 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008921 mTimer = null;
8922 return true;
8923 }
8924 return false;
8925 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008926
Bookatz867c0d72017-03-07 18:23:42 -08008927 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
8928 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008929 }
8930
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008931 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07008932 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933 }
8934
8935 @Override
8936 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07008937 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008938 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008939
8940 @Override
Bookatz867c0d72017-03-07 18:23:42 -08008941 public Timer getSensorBackgroundTime() {
8942 if (mTimer == null) {
8943 return null;
8944 }
8945 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008946 }
8947
8948 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 public int getHandle() {
8950 return mHandle;
8951 }
8952 }
8953
8954 /**
8955 * The statistics associated with a particular process.
8956 */
Joe Onoratoabded112016-02-08 16:49:39 -08008957 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
8958 /**
8959 * BatteryStatsImpl that we are associated with.
8960 */
8961 protected BatteryStatsImpl mBsi;
8962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008963 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008964 * The name of this process.
8965 */
8966 final String mName;
8967
8968 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08008969 * Remains true until removed from the stats.
8970 */
8971 boolean mActive = true;
8972
8973 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008974 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008975 */
8976 long mUserTime;
8977
8978 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008979 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008980 */
8981 long mSystemTime;
8982
8983 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008984 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008985 */
8986 long mForegroundTime;
8987
8988 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008989 * Number of times the process has been started.
8990 */
8991 int mStarts;
8992
8993 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008994 * Number of times the process has crashed.
8995 */
8996 int mNumCrashes;
8997
8998 /**
8999 * Number of times the process has had an ANR.
9000 */
9001 int mNumAnrs;
9002
9003 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009004 * The amount of user time loaded from a previous save.
9005 */
9006 long mLoadedUserTime;
9007
9008 /**
9009 * The amount of system time loaded from a previous save.
9010 */
9011 long mLoadedSystemTime;
9012
9013 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009014 * The amount of foreground time loaded from a previous save.
9015 */
9016 long mLoadedForegroundTime;
9017
9018 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009019 * The number of times the process has started from a previous save.
9020 */
9021 int mLoadedStarts;
9022
9023 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009024 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009026 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027
9028 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009029 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009030 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009031 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009032
9033 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009034 * The amount of user time when last unplugged.
9035 */
9036 long mUnpluggedUserTime;
9037
9038 /**
9039 * The amount of system time when last unplugged.
9040 */
9041 long mUnpluggedSystemTime;
9042
9043 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009044 * The amount of foreground time since unplugged.
9045 */
9046 long mUnpluggedForegroundTime;
9047
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009048 /**
9049 * The number of times the process has started before unplugged.
9050 */
9051 int mUnpluggedStarts;
9052
Dianne Hackborn61659e52014-07-09 16:13:01 -07009053 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009054 * Number of times the process has crashed before unplugged.
9055 */
9056 int mUnpluggedNumCrashes;
9057
9058 /**
9059 * Number of times the process has had an ANR before unplugged.
9060 */
9061 int mUnpluggedNumAnrs;
9062
Dianne Hackborn287952c2010-09-22 22:34:31 -07009063 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009064
Joe Onoratoabded112016-02-08 16:49:39 -08009065 public Proc(BatteryStatsImpl bsi, String name) {
9066 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009067 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08009068 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009069 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009070
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009071 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009072 mUnpluggedUserTime = mUserTime;
9073 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009074 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009075 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009076 mUnpluggedNumCrashes = mNumCrashes;
9077 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078 }
9079
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009080 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009081 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009082
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009083 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009084 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009085 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009086 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009087
Dianne Hackborn287952c2010-09-22 22:34:31 -07009088 public int countExcessivePowers() {
9089 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009090 }
9091
Dianne Hackborn287952c2010-09-22 22:34:31 -07009092 public ExcessivePower getExcessivePower(int i) {
9093 if (mExcessivePower != null) {
9094 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009095 }
9096 return null;
9097 }
9098
Dianne Hackborn287952c2010-09-22 22:34:31 -07009099 public void addExcessiveCpu(long overTime, long usedTime) {
9100 if (mExcessivePower == null) {
9101 mExcessivePower = new ArrayList<ExcessivePower>();
9102 }
9103 ExcessivePower ew = new ExcessivePower();
9104 ew.type = ExcessivePower.TYPE_CPU;
9105 ew.overTime = overTime;
9106 ew.usedTime = usedTime;
9107 mExcessivePower.add(ew);
9108 }
9109
9110 void writeExcessivePowerToParcelLocked(Parcel out) {
9111 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009112 out.writeInt(0);
9113 return;
9114 }
9115
Dianne Hackborn287952c2010-09-22 22:34:31 -07009116 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009117 out.writeInt(N);
9118 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009119 ExcessivePower ew = mExcessivePower.get(i);
9120 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009121 out.writeLong(ew.overTime);
9122 out.writeLong(ew.usedTime);
9123 }
9124 }
9125
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009126 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009127 final int N = in.readInt();
9128 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009129 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009130 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009131 }
9132
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009133 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009134 throw new ParcelFormatException(
9135 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009136 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009137
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009138 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009139 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009140 ExcessivePower ew = new ExcessivePower();
9141 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009142 ew.overTime = in.readLong();
9143 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009144 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009145 }
9146 }
9147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009148 void writeToParcelLocked(Parcel out) {
9149 out.writeLong(mUserTime);
9150 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009151 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009152 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009153 out.writeInt(mNumCrashes);
9154 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009155 out.writeLong(mLoadedUserTime);
9156 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009157 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009158 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009159 out.writeInt(mLoadedNumCrashes);
9160 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009161 out.writeLong(mUnpluggedUserTime);
9162 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009163 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009164 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009165 out.writeInt(mUnpluggedNumCrashes);
9166 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009167 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009168 }
9169
9170 void readFromParcelLocked(Parcel in) {
9171 mUserTime = in.readLong();
9172 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009173 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009174 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009175 mNumCrashes = in.readInt();
9176 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009177 mLoadedUserTime = in.readLong();
9178 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009179 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009180 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009181 mLoadedNumCrashes = in.readInt();
9182 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009183 mUnpluggedUserTime = in.readLong();
9184 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009185 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009186 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009187 mUnpluggedNumCrashes = in.readInt();
9188 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009189 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009190 }
9191
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009192 public void addCpuTimeLocked(int utime, int stime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 mUserTime += utime;
9194 mSystemTime += stime;
9195 }
9196
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009197 public void addForegroundTimeLocked(long ttime) {
9198 mForegroundTime += ttime;
9199 }
9200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009201 public void incStartsLocked() {
9202 mStarts++;
9203 }
9204
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009205 public void incNumCrashesLocked() {
9206 mNumCrashes++;
9207 }
9208
9209 public void incNumAnrsLocked() {
9210 mNumAnrs++;
9211 }
9212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009213 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009214 public boolean isActive() {
9215 return mActive;
9216 }
9217
9218 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009219 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009220 long val = mUserTime;
9221 if (which == STATS_CURRENT) {
9222 val -= mLoadedUserTime;
9223 } else if (which == STATS_SINCE_UNPLUGGED) {
9224 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009225 }
9226 return val;
9227 }
9228
9229 @Override
9230 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009231 long val = mSystemTime;
9232 if (which == STATS_CURRENT) {
9233 val -= mLoadedSystemTime;
9234 } else if (which == STATS_SINCE_UNPLUGGED) {
9235 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009236 }
9237 return val;
9238 }
9239
9240 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009241 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009242 long val = mForegroundTime;
9243 if (which == STATS_CURRENT) {
9244 val -= mLoadedForegroundTime;
9245 } else if (which == STATS_SINCE_UNPLUGGED) {
9246 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009247 }
9248 return val;
9249 }
9250
9251 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009252 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009253 int val = mStarts;
9254 if (which == STATS_CURRENT) {
9255 val -= mLoadedStarts;
9256 } else if (which == STATS_SINCE_UNPLUGGED) {
9257 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009258 }
9259 return val;
9260 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009261
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009262 @Override
9263 public int getNumCrashes(int which) {
9264 int val = mNumCrashes;
9265 if (which == STATS_CURRENT) {
9266 val -= mLoadedNumCrashes;
9267 } else if (which == STATS_SINCE_UNPLUGGED) {
9268 val -= mUnpluggedNumCrashes;
9269 }
9270 return val;
9271 }
9272
9273 @Override
9274 public int getNumAnrs(int which) {
9275 int val = mNumAnrs;
9276 if (which == STATS_CURRENT) {
9277 val -= mLoadedNumAnrs;
9278 } else if (which == STATS_SINCE_UNPLUGGED) {
9279 val -= mUnpluggedNumAnrs;
9280 }
9281 return val;
9282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009283 }
9284
9285 /**
9286 * The statistics associated with a particular package.
9287 */
Joe Onoratoabded112016-02-08 16:49:39 -08009288 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9289 /**
9290 * BatteryStatsImpl that we are associated with.
9291 */
9292 protected BatteryStatsImpl mBsi;
9293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009294 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009295 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009296 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009298 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009299
9300 /**
9301 * The statics we have collected for this package's services.
9302 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009303 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009304
Joe Onoratoabded112016-02-08 16:49:39 -08009305 public Pkg(BatteryStatsImpl bsi) {
9306 mBsi = bsi;
9307 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009308 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009309
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009310 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009311 }
9312
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009313 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009314 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009315
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009316 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009317 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009318 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009320 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009321 int numWA = in.readInt();
9322 mWakeupAlarms.clear();
9323 for (int i=0; i<numWA; i++) {
9324 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009325 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009327
9328 int numServs = in.readInt();
9329 mServiceStats.clear();
9330 for (int m = 0; m < numServs; m++) {
9331 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009332 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009333 mServiceStats.put(serviceName, serv);
9334
9335 serv.readFromParcelLocked(in);
9336 }
9337 }
9338
9339 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009340 int numWA = mWakeupAlarms.size();
9341 out.writeInt(numWA);
9342 for (int i=0; i<numWA; i++) {
9343 out.writeString(mWakeupAlarms.keyAt(i));
9344 mWakeupAlarms.valueAt(i).writeToParcel(out);
9345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009347 final int NS = mServiceStats.size();
9348 out.writeInt(NS);
9349 for (int i=0; i<NS; i++) {
9350 out.writeString(mServiceStats.keyAt(i));
9351 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 serv.writeToParcelLocked(out);
9353 }
9354 }
9355
9356 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009357 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9358 return mWakeupAlarms;
9359 }
9360
9361 public void noteWakeupAlarmLocked(String tag) {
9362 Counter c = mWakeupAlarms.get(tag);
9363 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009364 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009365 mWakeupAlarms.put(tag, c);
9366 }
9367 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009368 }
9369
9370 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009371 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9372 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009373 }
9374
9375 /**
9376 * The statistics associated with a particular service.
9377 */
Joe Onoratoabded112016-02-08 16:49:39 -08009378 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9379 /**
9380 * BatteryStatsImpl that we are associated with.
9381 */
9382 protected BatteryStatsImpl mBsi;
9383
9384 /**
9385 * The android package in which this service resides.
9386 */
9387 protected Pkg mPkg;
9388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009389 /**
9390 * Total time (ms in battery uptime) the service has been left started.
9391 */
Joe Onoratoabded112016-02-08 16:49:39 -08009392 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009393
9394 /**
9395 * If service has been started and not yet stopped, this is
9396 * when it was started.
9397 */
Joe Onoratoabded112016-02-08 16:49:39 -08009398 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009399
9400 /**
9401 * True if we are currently running.
9402 */
Joe Onoratoabded112016-02-08 16:49:39 -08009403 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009404
9405 /**
9406 * Total number of times startService() has been called.
9407 */
Joe Onoratoabded112016-02-08 16:49:39 -08009408 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009409
9410 /**
9411 * Total time (ms in battery uptime) the service has been left launched.
9412 */
Joe Onoratoabded112016-02-08 16:49:39 -08009413 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009414
9415 /**
9416 * If service has been launched and not yet exited, this is
9417 * when it was launched (ms in battery uptime).
9418 */
Joe Onoratoabded112016-02-08 16:49:39 -08009419 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009420
9421 /**
9422 * True if we are currently launched.
9423 */
Joe Onoratoabded112016-02-08 16:49:39 -08009424 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009425
9426 /**
9427 * Total number times the service has been launched.
9428 */
Joe Onoratoabded112016-02-08 16:49:39 -08009429 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009430
9431 /**
9432 * The amount of time spent started loaded from a previous save
9433 * (ms in battery uptime).
9434 */
Joe Onoratoabded112016-02-08 16:49:39 -08009435 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436
9437 /**
9438 * The number of starts loaded from a previous save.
9439 */
Joe Onoratoabded112016-02-08 16:49:39 -08009440 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009441
9442 /**
9443 * The number of launches loaded from a previous save.
9444 */
Joe Onoratoabded112016-02-08 16:49:39 -08009445 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009446
9447 /**
9448 * The amount of time spent started as of the last run (ms
9449 * in battery uptime).
9450 */
Joe Onoratoabded112016-02-08 16:49:39 -08009451 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009452
9453 /**
9454 * The number of starts as of the last run.
9455 */
Joe Onoratoabded112016-02-08 16:49:39 -08009456 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009457
9458 /**
9459 * The number of launches as of the last run.
9460 */
Joe Onoratoabded112016-02-08 16:49:39 -08009461 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009462
9463 /**
9464 * The amount of time spent started when last unplugged (ms
9465 * in battery uptime).
9466 */
Joe Onoratoabded112016-02-08 16:49:39 -08009467 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009468
9469 /**
9470 * The number of starts when last unplugged.
9471 */
Joe Onoratoabded112016-02-08 16:49:39 -08009472 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009473
9474 /**
9475 * The number of launches when last unplugged.
9476 */
Joe Onoratoabded112016-02-08 16:49:39 -08009477 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009478
Joe Onoratoabded112016-02-08 16:49:39 -08009479 /**
9480 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9481 */
9482 public Serv(BatteryStatsImpl bsi) {
9483 mBsi = bsi;
9484 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009485 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009486
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009487 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9488 long baseRealtime) {
9489 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009490 mUnpluggedStarts = mStarts;
9491 mUnpluggedLaunches = mLaunches;
9492 }
9493
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009494 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9495 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009496 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009497
Joe Onoratoabded112016-02-08 16:49:39 -08009498 /**
9499 * Remove this Serv as a listener from the time base.
9500 */
9501 public void detach() {
9502 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009503 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009504
Joe Onoratoabded112016-02-08 16:49:39 -08009505 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009506 mStartTime = in.readLong();
9507 mRunningSince = in.readLong();
9508 mRunning = in.readInt() != 0;
9509 mStarts = in.readInt();
9510 mLaunchedTime = in.readLong();
9511 mLaunchedSince = in.readLong();
9512 mLaunched = in.readInt() != 0;
9513 mLaunches = in.readInt();
9514 mLoadedStartTime = in.readLong();
9515 mLoadedStarts = in.readInt();
9516 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009517 mLastStartTime = 0;
9518 mLastStarts = 0;
9519 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009520 mUnpluggedStartTime = in.readLong();
9521 mUnpluggedStarts = in.readInt();
9522 mUnpluggedLaunches = in.readInt();
9523 }
9524
Joe Onoratoabded112016-02-08 16:49:39 -08009525 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009526 out.writeLong(mStartTime);
9527 out.writeLong(mRunningSince);
9528 out.writeInt(mRunning ? 1 : 0);
9529 out.writeInt(mStarts);
9530 out.writeLong(mLaunchedTime);
9531 out.writeLong(mLaunchedSince);
9532 out.writeInt(mLaunched ? 1 : 0);
9533 out.writeInt(mLaunches);
9534 out.writeLong(mLoadedStartTime);
9535 out.writeInt(mLoadedStarts);
9536 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009537 out.writeLong(mUnpluggedStartTime);
9538 out.writeInt(mUnpluggedStarts);
9539 out.writeInt(mUnpluggedLaunches);
9540 }
9541
Joe Onoratoabded112016-02-08 16:49:39 -08009542 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009543 if (!mLaunched) return mLaunchedTime;
9544 return mLaunchedTime + batteryUptime - mLaunchedSince;
9545 }
9546
Joe Onoratoabded112016-02-08 16:49:39 -08009547 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009548 if (!mRunning) return mStartTime;
9549 return mStartTime + batteryUptime - mRunningSince;
9550 }
9551
9552 public void startLaunchedLocked() {
9553 if (!mLaunched) {
9554 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009555 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009556 mLaunched = true;
9557 }
9558 }
9559
9560 public void stopLaunchedLocked() {
9561 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009562 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009563 if (time > 0) {
9564 mLaunchedTime += time;
9565 } else {
9566 mLaunches--;
9567 }
9568 mLaunched = false;
9569 }
9570 }
9571
9572 public void startRunningLocked() {
9573 if (!mRunning) {
9574 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009575 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009576 mRunning = true;
9577 }
9578 }
9579
9580 public void stopRunningLocked() {
9581 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009582 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009583 if (time > 0) {
9584 mStartTime += time;
9585 } else {
9586 mStarts--;
9587 }
9588 mRunning = false;
9589 }
9590 }
9591
9592 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009593 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009594 }
9595
9596 @Override
9597 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009598 int val = mLaunches;
9599 if (which == STATS_CURRENT) {
9600 val -= mLoadedLaunches;
9601 } else if (which == STATS_SINCE_UNPLUGGED) {
9602 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009604 return val;
9605 }
9606
9607 @Override
9608 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009609 long val = getStartTimeToNowLocked(now);
9610 if (which == STATS_CURRENT) {
9611 val -= mLoadedStartTime;
9612 } else if (which == STATS_SINCE_UNPLUGGED) {
9613 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009615 return val;
9616 }
9617
9618 @Override
9619 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009620 int val = mStarts;
9621 if (which == STATS_CURRENT) {
9622 val -= mLoadedStarts;
9623 } else if (which == STATS_SINCE_UNPLUGGED) {
9624 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009625 }
9626
9627 return val;
9628 }
9629 }
9630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009631 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009632 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009633 }
9634 }
9635
9636 /**
9637 * Retrieve the statistics object for a particular process, creating
9638 * if needed.
9639 */
9640 public Proc getProcessStatsLocked(String name) {
9641 Proc ps = mProcessStats.get(name);
9642 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009643 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009644 mProcessStats.put(name, ps);
9645 }
9646
9647 return ps;
9648 }
9649
Dianne Hackborna8d10942015-11-19 17:55:19 -08009650 public void updateUidProcessStateLocked(int procState) {
9651 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009652 // Make special note of Foreground Services
9653 final boolean userAwareService =
9654 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009655 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009656
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009657 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9658 return;
9659 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009660
Bookatz867c0d72017-03-07 18:23:42 -08009661 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009662 if (mProcessState != uidRunningState) {
9663 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009664
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009665 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9666 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009667
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009668 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009669 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009670 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9671 mBsi.mOnBatteryTimeBase.isRunning(),
9672 mBsi.mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009673 }
9674 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9675 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9676 mBsi.mPendingUids.put(mUid, mProcessState);
9677 }
9678 } else {
9679 mBsi.mPendingUids.clear();
9680 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009681 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009682 mProcessState = uidRunningState;
9683 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9684 if (mProcessStateTimer[uidRunningState] == null) {
9685 makeProcessState(uidRunningState, null);
9686 }
9687 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9688 }
9689
9690 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9691 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009692 }
Bookatz867c0d72017-03-07 18:23:42 -08009693
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009694 if (userAwareService != mInForegroundService) {
9695 if (userAwareService) {
9696 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9697 } else {
9698 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9699 }
9700 mInForegroundService = userAwareService;
9701 }
Bookatz867c0d72017-03-07 18:23:42 -08009702 }
9703
Bookatzc8c44962017-05-11 12:12:54 -07009704 /** Whether to consider Uid to be in the background for background timebase purposes. */
9705 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009706 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9707 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009708 return mProcessState >= PROCESS_STATE_BACKGROUND;
9709 }
9710
9711 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9712 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9713 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9714 }
9715
9716 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9717 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9718 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009719 }
9720
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009721 public SparseArray<? extends Pid> getPidStats() {
9722 return mPids;
9723 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009724
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009725 public Pid getPidStatsLocked(int pid) {
9726 Pid p = mPids.get(pid);
9727 if (p == null) {
9728 p = new Pid();
9729 mPids.put(pid, p);
9730 }
9731 return p;
9732 }
9733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009734 /**
9735 * Retrieve the statistics object for a particular service, creating
9736 * if needed.
9737 */
9738 public Pkg getPackageStatsLocked(String name) {
9739 Pkg ps = mPackageStats.get(name);
9740 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009741 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009742 mPackageStats.put(name, ps);
9743 }
9744
9745 return ps;
9746 }
9747
9748 /**
9749 * Retrieve the statistics object for a particular service, creating
9750 * if needed.
9751 */
9752 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9753 Pkg ps = getPackageStatsLocked(pkg);
9754 Pkg.Serv ss = ps.mServiceStats.get(serv);
9755 if (ss == null) {
9756 ss = ps.newServiceStatsLocked();
9757 ps.mServiceStats.put(serv, ss);
9758 }
9759
9760 return ss;
9761 }
9762
Dianne Hackbornd953c532014-08-16 18:17:38 -07009763 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009764 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009765 timer.readSummaryFromParcelLocked(in);
9766 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009767 }
9768
Dianne Hackbornd953c532014-08-16 18:17:38 -07009769 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009770 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009771 timer.readSummaryFromParcelLocked(in);
9772 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009773 }
9774
Dianne Hackbornd953c532014-08-16 18:17:38 -07009775 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009776 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009777 mWakelockStats.add(wlName, wl);
9778 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009779 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009780 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009781 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009782 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009783 }
9784 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009785 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009786 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009787 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009788 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009790 }
9791
Bookatz867c0d72017-03-07 18:23:42 -08009792 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009793 Sensor se = mSensorStats.get(sensor);
9794 if (se == null) {
9795 if (!create) {
9796 return null;
9797 }
Joe Onoratoabded112016-02-08 16:49:39 -08009798 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009799 mSensorStats.put(sensor, se);
9800 }
Bookatz867c0d72017-03-07 18:23:42 -08009801 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009802 if (t != null) {
9803 return t;
9804 }
Joe Onoratoabded112016-02-08 16:49:39 -08009805 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009806 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009807 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009808 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009809 }
Bookatz867c0d72017-03-07 18:23:42 -08009810 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9811 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009812 se.mTimer = t;
9813 return t;
9814 }
9815
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009816 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009817 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009818 if (t != null) {
9819 t.startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08009820 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name,
9821 StatsLog.SYNC_STATE_CHANGED__STATE__ON);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009822 }
9823 }
9824
9825 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009826 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009827 if (t != null) {
9828 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009829 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08009830 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name,
9831 StatsLog.SYNC_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07009832 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009833 }
9834 }
9835
9836 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009837 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009838 if (t != null) {
9839 t.startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08009840 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08009841 name, StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__STARTED);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009842 }
9843 }
9844
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009845 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07009846 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009847 if (t != null) {
9848 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009849 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08009850 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08009851 name, StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__FINISHED);
Bookatzc1a050a2017-10-10 15:49:28 -07009852 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009853 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009854 if (mBsi.mOnBatteryTimeBase.isRunning()) {
9855 SparseIntArray types = mJobCompletions.get(name);
9856 if (types == null) {
9857 types = new SparseIntArray();
9858 mJobCompletions.put(name, types);
9859 }
9860 int last = types.get(stopReason, 0);
9861 types.put(stopReason, last + 1);
9862 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009863 }
9864
Bookatz5b5ec322017-05-26 09:40:38 -07009865 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
9866 if (wl == null) {
9867 return null;
9868 }
9869 switch (type) {
9870 case WAKE_TYPE_PARTIAL: {
9871 DualTimer t = wl.mTimerPartial;
9872 if (t == null) {
9873 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
9874 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
9875 mOnBatteryScreenOffBackgroundTimeBase);
9876 wl.mTimerPartial = t;
9877 }
9878 return t;
9879 }
9880 case WAKE_TYPE_FULL: {
9881 StopwatchTimer t = wl.mTimerFull;
9882 if (t == null) {
9883 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
9884 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
9885 wl.mTimerFull = t;
9886 }
9887 return t;
9888 }
9889 case WAKE_TYPE_WINDOW: {
9890 StopwatchTimer t = wl.mTimerWindow;
9891 if (t == null) {
9892 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
9893 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
9894 wl.mTimerWindow = t;
9895 }
9896 return t;
9897 }
9898 case WAKE_TYPE_DRAW: {
9899 StopwatchTimer t = wl.mTimerDraw;
9900 if (t == null) {
9901 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
9902 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
9903 wl.mTimerDraw = t;
9904 }
9905 return t;
9906 }
9907 default:
9908 throw new IllegalArgumentException("type=" + type);
9909 }
9910 }
9911
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009912 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009913 Wakelock wl = mWakelockStats.startObject(name);
9914 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07009915 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009916 }
Bookatzc8c44962017-05-11 12:12:54 -07009917 if (type == WAKE_TYPE_PARTIAL) {
9918 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
9919 if (pid >= 0) {
9920 Pid p = getPidStatsLocked(pid);
9921 if (p.mWakeNesting++ == 0) {
9922 p.mWakeStartMs = elapsedRealtimeMs;
9923 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -07009924 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009926 }
9927
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009928 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009929 Wakelock wl = mWakelockStats.stopObject(name);
9930 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -07009931 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
9932 wlt.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009933 }
Bookatzc8c44962017-05-11 12:12:54 -07009934 if (type == WAKE_TYPE_PARTIAL) {
9935 if (mAggregatedPartialWakelockTimer != null) {
9936 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
9937 }
9938 if (pid >= 0) {
9939 Pid p = mPids.get(pid);
9940 if (p != null && p.mWakeNesting > 0) {
9941 if (p.mWakeNesting-- == 1) {
9942 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
9943 p.mWakeStartMs = 0;
9944 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08009945 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009946 }
9947 }
9948 }
9949
Dianne Hackborn287952c2010-09-22 22:34:31 -07009950 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
9951 Proc p = getProcessStatsLocked(proc);
9952 if (p != null) {
9953 p.addExcessiveCpu(overTime, usedTime);
9954 }
9955 }
9956
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009957 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009958 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -08009959 t.startRunningLocked(elapsedRealtimeMs);
Narayan Kamath32684dd2018-01-08 17:32:51 +00009960 if (sensor != Sensor.GPS) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08009961 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null, sensor,
Bookatz90867622018-01-31 15:05:57 -08009962 StatsLog.SENSOR_STATE_CHANGED__STATE__ON);
Bookatzc1a050a2017-10-10 15:49:28 -07009963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009964 }
9965
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009966 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009967 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -08009968 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009969 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009970 t.stopRunningLocked(elapsedRealtimeMs);
Narayan Kamath32684dd2018-01-08 17:32:51 +00009971 if (sensor != Sensor.GPS) {
9972 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08009973 sensor, StatsLog.SENSOR_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07009974 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009976 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009977
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009978 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009979 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009980 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009981
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009982 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009983 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009984 }
9985
9986 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009987 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009988 }
9989 }
9990
Sudheer Shanka9b735c52017-05-09 18:26:18 -07009991 public long[] getCpuFreqs() {
9992 return mCpuFreqs;
9993 }
9994
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009995 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
9996 UserInfoProvider userInfoProvider) {
9997 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009998 }
9999
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010000 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
10001 PlatformIdleStateCallback cb,
10002 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -080010003 init(clocks);
10004
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010005 if (systemDir != null) {
10006 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
10007 new File(systemDir, "batterystats.bin.tmp"));
10008 } else {
10009 mFile = null;
10010 }
10011 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010012 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -080010013 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010014 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010015 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -080010016 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010017 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010018 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010019 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010020 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010021 }
Joe Onoratoabded112016-02-08 16:49:39 -080010022 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
10023 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
10024 mOnBatteryTimeBase);
10025 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
10026 mOnBatteryTimeBase);
10027 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
10028 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
10029 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
10030 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
10031 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10032 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
10033 mOnBatteryTimeBase);
10034 }
10035 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
10036 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010037 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010038 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010039 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010040 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010041 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010042 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
10043 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010044 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010045 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
10046 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10047 NUM_BT_TX_LEVELS);
10048 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10049 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -080010050 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
10051 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
10052 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010053 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010054 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
10055 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010056 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
10057 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -080010058 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
10059 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010060 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010061 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -070010062 mOnBatteryTimeBase);
10063 }
Joe Onoratoabded112016-02-08 16:49:39 -080010064 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10065 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
10066 mOnBatteryTimeBase);
10067 }
10068 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10069 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
10070 mOnBatteryTimeBase);
10071 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010072 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010073 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10074 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10075 mOnBatteryTimeBase);
10076 }
Joe Onoratoabded112016-02-08 16:49:39 -080010077 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10078 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10079 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10080 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10081 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010082 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010083 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010084 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10085 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010086 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010087 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010088 long uptime = mClocks.uptimeMillis() * 1000;
10089 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010090 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010091 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010092 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010093 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010094 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010095 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010096 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010097 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010098 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010099 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010100 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010101 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010102 }
10103
10104 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010105 this(new SystemClocks(), p);
10106 }
10107
10108 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10109 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010110 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010111 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010112 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010113 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010114 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010115 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010116 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010117 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010118 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010119 }
10120
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010121 public void setPowerProfileLocked(PowerProfile profile) {
10122 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010123
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010124 // We need to initialize the KernelCpuSpeedReaders to read from
10125 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10126 // information.
10127 final int numClusters = mPowerProfile.getNumCpuClusters();
10128 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10129 int firstCpuOfCluster = 0;
10130 for (int i = 0; i < numClusters; i++) {
10131 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10132 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10133 numSpeedSteps);
10134 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10135 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010136
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010137 if (mEstimatedBatteryCapacity == -1) {
10138 // Initialize the estimated battery capacity to a known preset one.
10139 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010140 }
10141 }
10142
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010143 public void setCallback(BatteryCallback cb) {
10144 mCallback = cb;
10145 }
10146
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010147 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010148 if (mPhoneSignalScanningTimer != null) {
10149 mPhoneSignalScanningTimer.setTimeout(timeout);
10150 }
10151 }
10152
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010153 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10154 mExternalSync = sync;
10155 }
10156
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010157 public void updateDailyDeadlineLocked() {
10158 // Get the current time.
10159 long currentTime = mDailyStartTime = System.currentTimeMillis();
10160 Calendar calDeadline = Calendar.getInstance();
10161 calDeadline.setTimeInMillis(currentTime);
10162
10163 // Move time up to the next day, ranging from 1am to 3pm.
10164 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10165 calDeadline.set(Calendar.MILLISECOND, 0);
10166 calDeadline.set(Calendar.SECOND, 0);
10167 calDeadline.set(Calendar.MINUTE, 0);
10168 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10169 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10170 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10171 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10172 }
10173
10174 public void recordDailyStatsIfNeededLocked(boolean settled) {
10175 long currentTime = System.currentTimeMillis();
10176 if (currentTime >= mNextMaxDailyDeadline) {
10177 recordDailyStatsLocked();
10178 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10179 recordDailyStatsLocked();
10180 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10181 recordDailyStatsLocked();
10182 }
10183 }
10184
10185 public void recordDailyStatsLocked() {
10186 DailyItem item = new DailyItem();
10187 item.mStartTime = mDailyStartTime;
10188 item.mEndTime = System.currentTimeMillis();
10189 boolean hasData = false;
10190 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10191 hasData = true;
10192 item.mDischargeSteps = new LevelStepTracker(
10193 mDailyDischargeStepTracker.mNumStepDurations,
10194 mDailyDischargeStepTracker.mStepDurations);
10195 }
10196 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10197 hasData = true;
10198 item.mChargeSteps = new LevelStepTracker(
10199 mDailyChargeStepTracker.mNumStepDurations,
10200 mDailyChargeStepTracker.mStepDurations);
10201 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010202 if (mDailyPackageChanges != null) {
10203 hasData = true;
10204 item.mPackageChanges = mDailyPackageChanges;
10205 mDailyPackageChanges = null;
10206 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010207 mDailyDischargeStepTracker.init();
10208 mDailyChargeStepTracker.init();
10209 updateDailyDeadlineLocked();
10210
10211 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010212 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010213 mDailyItems.add(item);
10214 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10215 mDailyItems.remove(0);
10216 }
10217 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10218 try {
10219 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010220 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010221 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010222 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010223 BackgroundThread.getHandler().post(new Runnable() {
10224 @Override
10225 public void run() {
10226 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010227 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010228 FileOutputStream stream = null;
10229 try {
10230 stream = mDailyFile.startWrite();
10231 memStream.writeTo(stream);
10232 stream.flush();
10233 FileUtils.sync(stream);
10234 stream.close();
10235 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010236 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
10237 "batterystats-daily",
10238 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010239 } catch (IOException e) {
10240 Slog.w("BatteryStats",
10241 "Error writing battery daily items", e);
10242 mDailyFile.failWrite(stream);
10243 }
10244 }
10245 }
10246 });
10247 } catch (IOException e) {
10248 }
10249 }
10250 }
10251
10252 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10253 StringBuilder sb = new StringBuilder(64);
10254 out.startDocument(null, true);
10255 out.startTag(null, "daily-items");
10256 for (int i=0; i<mDailyItems.size(); i++) {
10257 final DailyItem dit = mDailyItems.get(i);
10258 out.startTag(null, "item");
10259 out.attribute(null, "start", Long.toString(dit.mStartTime));
10260 out.attribute(null, "end", Long.toString(dit.mEndTime));
10261 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10262 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010263 if (dit.mPackageChanges != null) {
10264 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10265 PackageChange pc = dit.mPackageChanges.get(j);
10266 if (pc.mUpdate) {
10267 out.startTag(null, "upd");
10268 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010269 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010270 out.endTag(null, "upd");
10271 } else {
10272 out.startTag(null, "rem");
10273 out.attribute(null, "pkg", pc.mPackageName);
10274 out.endTag(null, "rem");
10275 }
10276 }
10277 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010278 out.endTag(null, "item");
10279 }
10280 out.endTag(null, "daily-items");
10281 out.endDocument();
10282 }
10283
10284 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10285 StringBuilder tmpBuilder) throws IOException {
10286 if (steps != null) {
10287 out.startTag(null, tag);
10288 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10289 for (int i=0; i<steps.mNumStepDurations; i++) {
10290 out.startTag(null, "s");
10291 tmpBuilder.setLength(0);
10292 steps.encodeEntryAt(i, tmpBuilder);
10293 out.attribute(null, "v", tmpBuilder.toString());
10294 out.endTag(null, "s");
10295 }
10296 out.endTag(null, tag);
10297 }
10298 }
10299
10300 public void readDailyStatsLocked() {
10301 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10302 mDailyItems.clear();
10303 FileInputStream stream;
10304 try {
10305 stream = mDailyFile.openRead();
10306 } catch (FileNotFoundException e) {
10307 return;
10308 }
10309 try {
10310 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010311 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010312 readDailyItemsLocked(parser);
10313 } catch (XmlPullParserException e) {
10314 } finally {
10315 try {
10316 stream.close();
10317 } catch (IOException e) {
10318 }
10319 }
10320 }
10321
10322 private void readDailyItemsLocked(XmlPullParser parser) {
10323 try {
10324 int type;
10325 while ((type = parser.next()) != XmlPullParser.START_TAG
10326 && type != XmlPullParser.END_DOCUMENT) {
10327 ;
10328 }
10329
10330 if (type != XmlPullParser.START_TAG) {
10331 throw new IllegalStateException("no start tag found");
10332 }
10333
10334 int outerDepth = parser.getDepth();
10335 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10336 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10337 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10338 continue;
10339 }
10340
10341 String tagName = parser.getName();
10342 if (tagName.equals("item")) {
10343 readDailyItemTagLocked(parser);
10344 } else {
10345 Slog.w(TAG, "Unknown element under <daily-items>: "
10346 + parser.getName());
10347 XmlUtils.skipCurrentTag(parser);
10348 }
10349 }
10350
10351 } catch (IllegalStateException e) {
10352 Slog.w(TAG, "Failed parsing daily " + e);
10353 } catch (NullPointerException e) {
10354 Slog.w(TAG, "Failed parsing daily " + e);
10355 } catch (NumberFormatException e) {
10356 Slog.w(TAG, "Failed parsing daily " + e);
10357 } catch (XmlPullParserException e) {
10358 Slog.w(TAG, "Failed parsing daily " + e);
10359 } catch (IOException e) {
10360 Slog.w(TAG, "Failed parsing daily " + e);
10361 } catch (IndexOutOfBoundsException e) {
10362 Slog.w(TAG, "Failed parsing daily " + e);
10363 }
10364 }
10365
10366 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10367 XmlPullParserException, IOException {
10368 DailyItem dit = new DailyItem();
10369 String attr = parser.getAttributeValue(null, "start");
10370 if (attr != null) {
10371 dit.mStartTime = Long.parseLong(attr);
10372 }
10373 attr = parser.getAttributeValue(null, "end");
10374 if (attr != null) {
10375 dit.mEndTime = Long.parseLong(attr);
10376 }
10377 int outerDepth = parser.getDepth();
10378 int type;
10379 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10380 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10381 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10382 continue;
10383 }
10384
10385 String tagName = parser.getName();
10386 if (tagName.equals("dis")) {
10387 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10388 } else if (tagName.equals("chg")) {
10389 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010390 } else if (tagName.equals("upd")) {
10391 if (dit.mPackageChanges == null) {
10392 dit.mPackageChanges = new ArrayList<>();
10393 }
10394 PackageChange pc = new PackageChange();
10395 pc.mUpdate = true;
10396 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10397 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010398 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010399 dit.mPackageChanges.add(pc);
10400 XmlUtils.skipCurrentTag(parser);
10401 } else if (tagName.equals("rem")) {
10402 if (dit.mPackageChanges == null) {
10403 dit.mPackageChanges = new ArrayList<>();
10404 }
10405 PackageChange pc = new PackageChange();
10406 pc.mUpdate = false;
10407 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10408 dit.mPackageChanges.add(pc);
10409 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010410 } else {
10411 Slog.w(TAG, "Unknown element under <item>: "
10412 + parser.getName());
10413 XmlUtils.skipCurrentTag(parser);
10414 }
10415 }
10416 mDailyItems.add(dit);
10417 }
10418
10419 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10420 String tag)
10421 throws NumberFormatException, XmlPullParserException, IOException {
10422 final String numAttr = parser.getAttributeValue(null, "n");
10423 if (numAttr == null) {
10424 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10425 XmlUtils.skipCurrentTag(parser);
10426 return;
10427 }
10428 final int num = Integer.parseInt(numAttr);
10429 LevelStepTracker steps = new LevelStepTracker(num);
10430 if (isCharge) {
10431 dit.mChargeSteps = steps;
10432 } else {
10433 dit.mDischargeSteps = steps;
10434 }
10435 int i = 0;
10436 int outerDepth = parser.getDepth();
10437 int type;
10438 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10439 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10440 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10441 continue;
10442 }
10443
10444 String tagName = parser.getName();
10445 if ("s".equals(tagName)) {
10446 if (i < num) {
10447 String valueAttr = parser.getAttributeValue(null, "v");
10448 if (valueAttr != null) {
10449 steps.decodeEntryAt(i, valueAttr);
10450 i++;
10451 }
10452 }
10453 } else {
10454 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10455 + parser.getName());
10456 XmlUtils.skipCurrentTag(parser);
10457 }
10458 }
10459 steps.mNumStepDurations = i;
10460 }
10461
10462 @Override
10463 public DailyItem getDailyItemLocked(int daysAgo) {
10464 int index = mDailyItems.size()-1-daysAgo;
10465 return index >= 0 ? mDailyItems.get(index) : null;
10466 }
10467
10468 @Override
10469 public long getCurrentDailyStartTime() {
10470 return mDailyStartTime;
10471 }
10472
10473 @Override
10474 public long getNextMinDailyDeadline() {
10475 return mNextMinDailyDeadline;
10476 }
10477
10478 @Override
10479 public long getNextMaxDailyDeadline() {
10480 return mNextMaxDailyDeadline;
10481 }
10482
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010483 @Override
10484 public boolean startIteratingOldHistoryLocked() {
10485 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10486 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010487 if ((mHistoryIterator = mHistory) == null) {
10488 return false;
10489 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010490 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010491 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010492 mReadOverflow = false;
10493 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010494 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010495 }
10496
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010497 @Override
10498 public boolean getNextOldHistoryLocked(HistoryItem out) {
10499 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10500 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010501 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010502 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010503 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010504 HistoryItem cur = mHistoryIterator;
10505 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010506 if (!mReadOverflow && !end) {
10507 Slog.w(TAG, "Old history ends before new history!");
10508 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010509 return false;
10510 }
10511 out.setTo(cur);
10512 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010513 if (!mReadOverflow) {
10514 if (end) {
10515 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010516 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010517 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010518 pw.println("Histories differ!");
10519 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010520 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010521 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010522 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10523 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010524 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010525 }
10526 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010527 return true;
10528 }
10529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010530 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010531 public void finishIteratingOldHistoryLocked() {
10532 mIteratingHistory = false;
10533 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010534 mHistoryIterator = null;
10535 }
10536
10537 public int getHistoryTotalSize() {
10538 return MAX_HISTORY_BUFFER;
10539 }
10540
10541 public int getHistoryUsedSize() {
10542 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010543 }
10544
10545 @Override
10546 public boolean startIteratingHistoryLocked() {
10547 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10548 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010549 if (mHistoryBuffer.dataSize() <= 0) {
10550 return false;
10551 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010552 mHistoryBuffer.setDataPosition(0);
10553 mReadOverflow = false;
10554 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010555 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10556 mReadHistoryUids = new int[mHistoryTagPool.size()];
10557 mReadHistoryChars = 0;
10558 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10559 final HistoryTag tag = ent.getKey();
10560 final int idx = ent.getValue();
10561 mReadHistoryStrings[idx] = tag.string;
10562 mReadHistoryUids[idx] = tag.uid;
10563 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010564 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010565 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010566 }
10567
10568 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010569 public int getHistoryStringPoolSize() {
10570 return mReadHistoryStrings.length;
10571 }
10572
10573 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010574 public int getHistoryStringPoolBytes() {
10575 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10576 // Each string character is 2 bytes.
10577 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10578 }
10579
10580 @Override
10581 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010582 return mReadHistoryStrings[index];
10583 }
10584
10585 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010586 public int getHistoryTagPoolUid(int index) {
10587 return mReadHistoryUids[index];
10588 }
10589
10590 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010591 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010592 final int pos = mHistoryBuffer.dataPosition();
10593 if (pos == 0) {
10594 out.clear();
10595 }
10596 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010597 if (end) {
10598 return false;
10599 }
10600
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010601 final long lastRealtime = out.time;
10602 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010603 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010604 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10605 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010606 out.currentTime = lastWalltime + (out.time - lastRealtime);
10607 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010608 return true;
10609 }
10610
10611 @Override
10612 public void finishIteratingHistoryLocked() {
10613 mIteratingHistory = false;
10614 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010615 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010616 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010617
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010618 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010619 public long getHistoryBaseTime() {
10620 return mHistoryBaseTime;
10621 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010622
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010623 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010624 public int getStartCount() {
10625 return mStartCount;
10626 }
10627
10628 public boolean isOnBattery() {
10629 return mOnBattery;
10630 }
10631
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010632 public boolean isCharging() {
10633 return mCharging;
10634 }
10635
Mike Mac2f518a2017-09-19 16:06:03 -070010636 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010637 return state == Display.STATE_ON || state == Display.STATE_VR
10638 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010639 }
10640
10641 public boolean isScreenOff(int state) {
10642 return state == Display.STATE_OFF;
10643 }
10644
10645 public boolean isScreenDoze(int state) {
10646 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010647 }
10648
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010649 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010650 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010651 mOnBatteryTimeBase.init(uptime, realtime);
10652 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010653 mRealtime = 0;
10654 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010655 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010656 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010657 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010658
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010659 void initDischarge() {
10660 mLowDischargeAmountSinceCharge = 0;
10661 mHighDischargeAmountSinceCharge = 0;
10662 mDischargeAmountScreenOn = 0;
10663 mDischargeAmountScreenOnSinceCharge = 0;
10664 mDischargeAmountScreenOff = 0;
10665 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010666 mDischargeAmountScreenDoze = 0;
10667 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010668 mDischargeStepTracker.init();
10669 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010670 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010671 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010672 mDischargeLightDozeCounter.reset(false);
10673 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010674 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010675 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010676
10677 public void resetAllStatsCmdLocked() {
10678 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010679 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010680 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010681 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010682 long realtime = mSecRealtime * 1000;
10683 mDischargeStartLevel = mHistoryCur.batteryLevel;
10684 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010685 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010686 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10687 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010688 mOnBatteryTimeBase.reset(uptime, realtime);
10689 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10690 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010691 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010692 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010693 mDischargeScreenDozeUnplugLevel = 0;
10694 mDischargeScreenOffUnplugLevel = 0;
10695 } else if (isScreenDoze(mScreenState)) {
10696 mDischargeScreenOnUnplugLevel = 0;
10697 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010698 mDischargeScreenOffUnplugLevel = 0;
10699 } else {
10700 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010701 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010702 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10703 }
10704 mDischargeAmountScreenOn = 0;
10705 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010706 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010707 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010708 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010709 }
10710
10711 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010712 final long uptimeMillis = mClocks.uptimeMillis();
10713 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010714 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010715 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010716 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010717 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010718 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010719 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010720 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010721
10722 if (mPowerProfile != null) {
10723 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10724 } else {
10725 mEstimatedBatteryCapacity = -1;
10726 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010727 mMinLearnedBatteryCapacity = -1;
10728 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010729 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010730 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010731 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010732 mLongestLightIdleTime = 0;
10733 mLongestFullIdleTime = 0;
10734 mDeviceIdleModeLightTimer.reset(false);
10735 mDeviceIdleModeFullTimer.reset(false);
10736 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010737 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010738 mPhoneOnTimer.reset(false);
10739 mAudioOnTimer.reset(false);
10740 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010741 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010742 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010743 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010744 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010745 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010746 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010747 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010748 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010749 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010750 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010751 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010752 mNetworkByteActivityCounters[i].reset(false);
10753 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010754 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010755 mMobileRadioActiveTimer.reset(false);
10756 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010757 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010758 mMobileRadioActiveUnknownTime.reset(false);
10759 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010760 mWifiOnTimer.reset(false);
10761 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010762 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010763 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010764 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010765 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10766 mWifiSupplStateTimer[i].reset(false);
10767 }
10768 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10769 mWifiSignalStrengthsTimer[i].reset(false);
10770 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010771 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010772 mWifiActiveTimer.reset(false);
10773 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010774 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10775 mGpsSignalQualityTimer[i].reset(false);
10776 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010777 mBluetoothActivity.reset(false);
10778 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010779 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010780
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010781 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010782 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010783 mUidStats.remove(mUidStats.keyAt(i));
10784 i--;
10785 }
10786 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010787
Bookatz50df7112017-08-04 14:53:26 -070010788 if (mRpmStats.size() > 0) {
10789 for (SamplingTimer timer : mRpmStats.values()) {
10790 mOnBatteryTimeBase.remove(timer);
10791 }
10792 mRpmStats.clear();
10793 }
10794 if (mScreenOffRpmStats.size() > 0) {
10795 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10796 mOnBatteryScreenOffTimeBase.remove(timer);
10797 }
10798 mScreenOffRpmStats.clear();
10799 }
10800
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010801 if (mKernelWakelockStats.size() > 0) {
10802 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010803 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010804 }
10805 mKernelWakelockStats.clear();
10806 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010807
James Carr3a226052016-07-01 14:49:52 -070010808 if (mKernelMemoryStats.size() > 0) {
10809 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10810 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10811 }
10812 mKernelMemoryStats.clear();
10813 }
10814
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010815 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010816 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10817 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010818 }
10819 mWakeupReasonStats.clear();
10820 }
10821
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010822 mLastHistoryStepDetails = null;
10823 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10824 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10825 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10826 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10827 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10828 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10829 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
10830 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
10831 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
10832 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
10833
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010834 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010835
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010836 clearHistoryLocked();
10837 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010838
Dianne Hackborn40c87252014-03-19 16:55:40 -070010839 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010840 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010841 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
10842 // Not recording process starts/stops.
10843 continue;
10844 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010845 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010846 if (active == null) {
10847 continue;
10848 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010849 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
10850 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010851 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070010852 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
10853 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010854 }
10855 }
10856 }
10857 }
10858
Mike Mac2f518a2017-09-19 16:06:03 -070010859 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
10860 updateOldDischargeScreenLevelLocked(oldState);
10861 updateNewDischargeScreenLevelLocked(newState);
10862 }
10863
10864 private void updateOldDischargeScreenLevelLocked(int state) {
10865 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010866 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
10867 if (diff > 0) {
10868 mDischargeAmountScreenOn += diff;
10869 mDischargeAmountScreenOnSinceCharge += diff;
10870 }
Mike Mac2f518a2017-09-19 16:06:03 -070010871 } else if (isScreenDoze(state)) {
10872 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
10873 if (diff > 0) {
10874 mDischargeAmountScreenDoze += diff;
10875 mDischargeAmountScreenDozeSinceCharge += diff;
10876 }
10877 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010878 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
10879 if (diff > 0) {
10880 mDischargeAmountScreenOff += diff;
10881 mDischargeAmountScreenOffSinceCharge += diff;
10882 }
10883 }
Mike Mac2f518a2017-09-19 16:06:03 -070010884 }
10885
10886 private void updateNewDischargeScreenLevelLocked(int state) {
10887 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010888 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
10889 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010890 mDischargeScreenDozeUnplugLevel = 0;
10891 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010892 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010893 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
10894 mDischargeScreenOffUnplugLevel = 0;
10895 } else if (isScreenOff(state)) {
10896 mDischargeScreenOnUnplugLevel = 0;
10897 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010898 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
10899 }
10900 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010901
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010902 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010903 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070010904 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010905 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010906 }
10907
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010908 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
10909 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
10910
10911 private final Object mWifiNetworkLock = new Object();
10912
10913 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010914 private String[] mWifiIfaces = EmptyArray.STRING;
10915
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010916 @GuardedBy("mWifiNetworkLock")
10917 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010918
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010919 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010920
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010921 @GuardedBy("mModemNetworkLock")
10922 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010923
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010924 @GuardedBy("mModemNetworkLock")
10925 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
10926
10927 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
10928 try {
10929 if (!ArrayUtils.isEmpty(ifaces)) {
10930 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
10931 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
10932 }
10933 } catch (IOException e) {
10934 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010935 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010936 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010937 }
10938
Chenjie Yu89083392018-01-11 14:53:31 -080010939 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010940 * Distribute WiFi energy info and network traffic to apps.
10941 * @param info The energy information from the WiFi controller.
10942 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010943 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010944 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010945 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010946 }
10947
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010948 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070010949 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010950 synchronized (mWifiNetworkLock) {
10951 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
10952 if (latestStats != null) {
10953 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
10954 mNetworkStatsPool.acquire());
10955 mNetworkStatsPool.release(mLastWifiNetworkStats);
10956 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070010957 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010958 }
10959
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010960 synchronized (this) {
10961 if (!mOnBatteryInternal) {
10962 if (delta != null) {
10963 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010964 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010965 return;
10966 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010967
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010968 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
10969 SparseLongArray rxPackets = new SparseLongArray();
10970 SparseLongArray txPackets = new SparseLongArray();
10971 long totalTxPackets = 0;
10972 long totalRxPackets = 0;
10973 if (delta != null) {
10974 NetworkStats.Entry entry = new NetworkStats.Entry();
10975 final int size = delta.size();
10976 for (int i = 0; i < size; i++) {
10977 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010978
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010979 if (DEBUG_ENERGY) {
10980 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
10981 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
10982 + " txPackets=" + entry.txPackets);
10983 }
10984
10985 if (entry.rxBytes == 0 && entry.txBytes == 0) {
10986 // Skip the lookup below since there is no work to do.
10987 continue;
10988 }
10989
10990 final Uid u = getUidStatsLocked(mapUid(entry.uid));
10991 if (entry.rxBytes != 0) {
10992 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080010993 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010994 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10995 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
10996 entry.rxPackets);
10997 }
10998 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
10999 entry.rxBytes);
11000 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11001 entry.rxPackets);
11002
11003 rxPackets.put(u.getUid(), entry.rxPackets);
11004
11005 // Sum the total number of packets so that the Rx Power can
11006 // be evenly distributed amongst the apps.
11007 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011008 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011009
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011010 if (entry.txBytes != 0) {
11011 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011012 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011013 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11014 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
11015 entry.txPackets);
11016 }
11017 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11018 entry.txBytes);
11019 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11020 entry.txPackets);
11021
11022 txPackets.put(u.getUid(), entry.txPackets);
11023
11024 // Sum the total number of packets so that the Tx Power can
11025 // be evenly distributed amongst the apps.
11026 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011027 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080011028 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011029 mNetworkStatsPool.release(delta);
11030 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070011031 }
11032
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011033 if (info != null) {
11034 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070011035
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011036 // Measured in mAms
11037 final long txTimeMs = info.getControllerTxTimeMillis();
11038 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080011039 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011040 final long idleTimeMs = info.getControllerIdleTimeMillis();
11041 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011042
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011043 long leftOverRxTimeMs = rxTimeMs;
11044 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011045
Adam Lesinskie08af192015-03-25 16:42:59 -070011046 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011047 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
11048 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11049 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11050 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
11051 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080011052 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011053 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011054
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011055 long totalWifiLockTimeMs = 0;
11056 long totalScanTimeMs = 0;
11057
11058 // On the first pass, collect some totals so that we can normalize power
11059 // calculations if we need to.
11060 final int uidStatsSize = mUidStats.size();
11061 for (int i = 0; i < uidStatsSize; i++) {
11062 final Uid uid = mUidStats.valueAt(i);
11063
11064 // Sum the total scan power for all apps.
11065 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
11066 elapsedRealtimeMs * 1000) / 1000;
11067
11068 // Sum the total time holding wifi lock for all apps.
11069 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11070 elapsedRealtimeMs * 1000) / 1000;
11071 }
11072
11073 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
11074 Slog.d(TAG,
11075 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
11076 + rxTimeMs + " ms). Normalizing scan time.");
11077 }
11078 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11079 Slog.d(TAG,
11080 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11081 + txTimeMs + " ms). Normalizing scan time.");
11082 }
11083
11084 // Actually assign and distribute power usage to apps.
11085 for (int i = 0; i < uidStatsSize; i++) {
11086 final Uid uid = mUidStats.valueAt(i);
11087
11088 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11089 elapsedRealtimeMs * 1000) / 1000;
11090 if (scanTimeSinceMarkMs > 0) {
11091 // Set the new mark so that next time we get new data since this point.
11092 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11093
11094 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11095 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11096
11097 // Our total scan time is more than the reported Tx/Rx time.
11098 // This is possible because the cost of a scan is approximate.
11099 // Let's normalize the result so that we evenly blame each app
11100 // scanning.
11101 //
11102 // This means that we may have apps that transmitted/received packets not be
11103 // blamed for this, but this is fine as scans are relatively more expensive.
11104 if (totalScanTimeMs > rxTimeMs) {
11105 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11106 totalScanTimeMs;
11107 }
11108 if (totalScanTimeMs > txTimeMs) {
11109 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11110 totalScanTimeMs;
11111 }
11112
11113 if (DEBUG_ENERGY) {
11114 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11115 + scanRxTimeSinceMarkMs + " ms Tx:"
11116 + scanTxTimeSinceMarkMs + " ms)");
11117 }
11118
11119 ControllerActivityCounterImpl activityCounter =
11120 uid.getOrCreateWifiControllerActivityLocked();
11121 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11122 activityCounter.getTxTimeCounters()[0].addCountLocked(
11123 scanTxTimeSinceMarkMs);
11124 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11125 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11126 }
11127
11128 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11129 // lock.
11130 final long wifiLockTimeSinceMarkMs =
11131 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11132 elapsedRealtimeMs * 1000) / 1000;
11133 if (wifiLockTimeSinceMarkMs > 0) {
11134 // Set the new mark so that next time we get new data since this point.
11135 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11136
11137 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11138 / totalWifiLockTimeMs;
11139 if (DEBUG_ENERGY) {
11140 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11141 + myIdleTimeMs + " ms");
11142 }
11143 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11144 .addCountLocked(myIdleTimeMs);
11145 }
11146 }
11147
Adam Lesinskie08af192015-03-25 16:42:59 -070011148 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011149 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11150 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011151 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011152
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011153 // Distribute the remaining Tx power appropriately between all apps that transmitted
11154 // packets.
11155 for (int i = 0; i < txPackets.size(); i++) {
11156 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11157 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11158 / totalTxPackets;
11159 if (DEBUG_ENERGY) {
11160 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11161 }
11162 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11163 .addCountLocked(myTxTimeMs);
11164 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011165
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011166 // Distribute the remaining Rx power appropriately between all apps that received
11167 // packets.
11168 for (int i = 0; i < rxPackets.size(); i++) {
11169 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11170 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11171 / totalRxPackets;
11172 if (DEBUG_ENERGY) {
11173 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11174 }
11175 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11176 .addCountLocked(myRxTimeMs);
11177 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011178
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011179 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11180
11181
11182 // Update WiFi controller stats.
11183 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11184 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11185 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011186 mWifiActivity.getScanTimeCounter().addCountLocked(
11187 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011188 mWifiActivity.getIdleTimeCounter().addCountLocked(
11189 info.getControllerIdleTimeMillis());
11190
11191 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11192 final double opVolt = mPowerProfile.getAveragePower(
11193 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11194 if (opVolt != 0) {
11195 // We store the power drain as mAms.
11196 mWifiActivity.getPowerCounter().addCountLocked(
11197 (long) (info.getControllerEnergyUsed() / opVolt));
11198 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011199 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011200 }
11201 }
11202
Chenjie Yu89083392018-01-11 14:53:31 -080011203 private ModemActivityInfo mLastModemActivityInfo =
11204 new ModemActivityInfo(0, 0, 0, new int[0], 0, 0);
11205
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011206 /**
11207 * Distribute Cell radio energy info and network traffic to apps.
11208 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011209 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011210 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011211 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011212 }
11213
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011214 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011215 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011216 synchronized (mModemNetworkLock) {
11217 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11218 if (latestStats != null) {
11219 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11220 mNetworkStatsPool.acquire());
11221 mNetworkStatsPool.release(mLastModemNetworkStats);
11222 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011223 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011224 }
11225
Chenjie Yu89083392018-01-11 14:53:31 -080011226 int rxTimeMs = 0;
11227 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
11228 int idleTimeMs = 0;
11229 int sleepTimeMs = 0;
11230 if (activityInfo != null) {
11231 rxTimeMs = activityInfo.getRxTimeMillis() - mLastModemActivityInfo.getRxTimeMillis();
11232 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
11233 txTimeMs[i] = activityInfo.getTxTimeMillis()[i]
11234 - mLastModemActivityInfo.getTxTimeMillis()[i];
11235 }
11236 idleTimeMs =
11237 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis();
11238 sleepTimeMs =
11239 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis();
11240 }
11241
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011242 synchronized (this) {
11243 if (!mOnBatteryInternal) {
11244 if (delta != null) {
11245 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011246 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011247 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011248 }
11249
Siddharth Ray2038af82018-01-17 17:40:26 -080011250 if (activityInfo != null) {
11251 mHasModemReporting = true;
11252 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yu89083392018-01-11 14:53:31 -080011253 idleTimeMs);
11254 mModemActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
Siddharth Ray2038af82018-01-17 17:40:26 -080011255 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11256 mModemActivity.getTxTimeCounters()[lvl]
Chenjie Yu89083392018-01-11 14:53:31 -080011257 .addCountLocked(txTimeMs[lvl]);
Siddharth Ray2038af82018-01-17 17:40:26 -080011258 }
11259
11260 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11261 final double opVolt = mPowerProfile.getAveragePower(
11262 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11263 if (opVolt != 0) {
11264 double energyUsed =
Chenjie Yu89083392018-01-11 14:53:31 -080011265 sleepTimeMs *
Siddharth Ray2038af82018-01-17 17:40:26 -080011266 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yu89083392018-01-11 14:53:31 -080011267 + idleTimeMs *
Siddharth Ray2038af82018-01-17 17:40:26 -080011268 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chenjie Yu89083392018-01-11 14:53:31 -080011269 + rxTimeMs *
Siddharth Ray2038af82018-01-17 17:40:26 -080011270 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chenjie Yu89083392018-01-11 14:53:31 -080011271 for (int i = 0; i < Math.min(txTimeMs.length,
Siddharth Ray2038af82018-01-17 17:40:26 -080011272 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chenjie Yu89083392018-01-11 14:53:31 -080011273 energyUsed += txTimeMs[i] * mPowerProfile.getAveragePower(
Siddharth Ray2038af82018-01-17 17:40:26 -080011274 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
11275 }
11276
11277 // We store the power drain as mAms.
11278 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11279 }
11280 }
11281
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011282 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011283 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11284 elapsedRealtimeMs * 1000);
11285 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11286
11287 long totalRxPackets = 0;
11288 long totalTxPackets = 0;
11289 if (delta != null) {
11290 NetworkStats.Entry entry = new NetworkStats.Entry();
11291 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011292 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011293 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011294 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11295 continue;
11296 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011297
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011298 if (DEBUG_ENERGY) {
11299 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11300 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11301 + " txPackets=" + entry.txPackets);
11302 }
11303
11304 totalRxPackets += entry.rxPackets;
11305 totalTxPackets += entry.txPackets;
11306
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011307 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011308 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11309 entry.rxPackets);
11310 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11311 entry.txPackets);
11312 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11313 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11314 entry.rxBytes, entry.rxPackets);
11315 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11316 entry.txBytes, entry.txPackets);
11317 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011318
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011319 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11320 entry.rxBytes);
11321 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11322 entry.txBytes);
11323 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11324 entry.rxPackets);
11325 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11326 entry.txPackets);
11327 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011328
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011329 // Now distribute proportional blame to the apps that did networking.
11330 long totalPackets = totalRxPackets + totalTxPackets;
11331 if (totalPackets > 0) {
11332 for (int i = 0; i < size; i++) {
11333 entry = delta.getValues(i, entry);
11334 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11335 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011336 }
11337
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011338 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11339
11340 // Distribute total radio active time in to this app.
11341 final long appPackets = entry.rxPackets + entry.txPackets;
11342 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11343 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11344
11345 // Remove this app from the totals, so that we don't lose any time
11346 // due to rounding.
11347 radioTime -= appRadioTime;
11348 totalPackets -= appPackets;
11349
11350 if (activityInfo != null) {
11351 ControllerActivityCounterImpl activityCounter =
11352 u.getOrCreateModemControllerActivityLocked();
11353 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chenjie Yu89083392018-01-11 14:53:31 -080011354 final long rxMs = (entry.rxPackets * rxTimeMs)
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011355 / totalRxPackets;
11356 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11357 }
11358
11359 if (totalTxPackets > 0 && entry.txPackets > 0) {
11360 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11361 long txMs =
Chenjie Yu89083392018-01-11 14:53:31 -080011362 entry.txPackets * txTimeMs[lvl];
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011363 txMs /= totalTxPackets;
11364 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11365 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011366 }
11367 }
11368 }
11369 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011370
11371 if (radioTime > 0) {
11372 // Whoops, there is some radio time we can't blame on an app!
11373 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11374 mMobileRadioActiveUnknownCount.addCountLocked(1);
11375 }
11376
11377 mNetworkStatsPool.release(delta);
11378 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011379 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011380 }
11381 }
11382
Chenjie Yu89083392018-01-11 14:53:31 -080011383 // Cache last value for comparison.
11384 private BluetoothActivityEnergyInfo mLastBluetoothActivityEnergyInfo =
11385 new BluetoothActivityEnergyInfo(0, 0, 0, 0, 0, 0);
11386
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011387 /**
11388 * Distribute Bluetooth energy info and network traffic to apps.
11389 * @param info The energy information from the bluetooth controller.
11390 */
11391 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011392 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011393 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011394 }
11395
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011396 if (info == null || !mOnBatteryInternal) {
11397 return;
11398 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011399
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011400 mHasBluetoothReporting = true;
11401
Bookatz867c0d72017-03-07 18:23:42 -080011402 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Chenjie Yu89083392018-01-11 14:53:31 -080011403 final long rxTimeMs = info.getControllerRxTimeMillis() -
11404 mLastBluetoothActivityEnergyInfo.getControllerRxTimeMillis();
11405 final long txTimeMs = info.getControllerTxTimeMillis() -
11406 mLastBluetoothActivityEnergyInfo.getControllerTxTimeMillis();
11407 final long idleTimeMs = info.getControllerIdleTimeMillis() -
11408 mLastBluetoothActivityEnergyInfo.getControllerIdleTimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011409 if (DEBUG_ENERGY) {
11410 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11411 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11412 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011413 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011414 }
11415
11416 long totalScanTimeMs = 0;
11417
11418 final int uidCount = mUidStats.size();
11419 for (int i = 0; i < uidCount; i++) {
11420 final Uid u = mUidStats.valueAt(i);
11421 if (u.mBluetoothScanTimer == null) {
11422 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011423 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011424
Bookatzaa4594a2017-03-24 12:39:56 -070011425 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011426 elapsedRealtimeMs * 1000) / 1000;
11427 }
11428
11429 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11430 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11431
11432 if (DEBUG_ENERGY) {
11433 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11434 + " TX=" + normalizeScanTxTime);
11435 }
11436
11437 long leftOverRxTimeMs = rxTimeMs;
11438 long leftOverTxTimeMs = txTimeMs;
11439
11440 for (int i = 0; i < uidCount; i++) {
11441 final Uid u = mUidStats.valueAt(i);
11442 if (u.mBluetoothScanTimer == null) {
11443 continue;
11444 }
11445
Bookatzaa4594a2017-03-24 12:39:56 -070011446 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011447 elapsedRealtimeMs * 1000) / 1000;
11448 if (scanTimeSinceMarkMs > 0) {
11449 // Set the new mark so that next time we get new data since this point.
11450 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11451
11452 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11453 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11454
11455 if (normalizeScanRxTime) {
11456 // Scan time is longer than the total rx time in the controller,
11457 // so distribute the scan time proportionately. This means regular traffic
11458 // will not blamed, but scans are more expensive anyways.
11459 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11460 }
11461
11462 if (normalizeScanTxTime) {
11463 // Scan time is longer than the total tx time in the controller,
11464 // so distribute the scan time proportionately. This means regular traffic
11465 // will not blamed, but scans are more expensive anyways.
11466 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11467 }
11468
11469 final ControllerActivityCounterImpl counter =
11470 u.getOrCreateBluetoothControllerActivityLocked();
11471 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11472 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11473
11474 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11475 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11476 }
11477 }
11478
11479 if (DEBUG_ENERGY) {
11480 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs
11481 + " TX=" + leftOverTxTimeMs);
11482 }
11483
11484 //
11485 // Now distribute blame to apps that did bluetooth traffic.
11486 //
11487
11488 long totalTxBytes = 0;
11489 long totalRxBytes = 0;
11490
11491 final UidTraffic[] uidTraffic = info.getUidTraffic();
Chenjie Yu89083392018-01-11 14:53:31 -080011492 final UidTraffic[] lastUidTraffic = mLastBluetoothActivityEnergyInfo.getUidTraffic();
11493 final ArrayList<UidTraffic> deltaTraffic = new ArrayList<>();
11494 int m = 0, n = 0;
11495 for (; m < uidTraffic.length && n < lastUidTraffic.length; m++) {
11496 final UidTraffic traffic = uidTraffic[m];
11497 final UidTraffic lastTraffic = lastUidTraffic[n];
11498 if (traffic.getUid() == lastTraffic.getUid()) {
11499 deltaTraffic.add(new UidTraffic(traffic.getUid(),
11500 traffic.getRxBytes() - lastTraffic.getRxBytes(),
11501 traffic.getTxBytes() - lastTraffic.getTxBytes()));
11502 n++;
11503 }
11504 }
11505 for (; m < uidTraffic.length; m ++) {
11506 deltaTraffic.add(uidTraffic[m]);
11507 }
11508
11509 for (int i = 0, j = 0; i < deltaTraffic.size(); i++) {
11510 final UidTraffic traffic = deltaTraffic.get(i);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011511
11512 // Add to the global counters.
11513 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(
11514 traffic.getRxBytes());
11515 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(
11516 traffic.getTxBytes());
11517
11518 // Add to the UID counters.
11519 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
11520 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, traffic.getRxBytes(), 0);
11521 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, traffic.getTxBytes(), 0);
11522
11523 // Calculate the total traffic.
11524 totalTxBytes += traffic.getTxBytes();
11525 totalRxBytes += traffic.getRxBytes();
11526 }
11527
11528 if ((totalTxBytes != 0 || totalRxBytes != 0) &&
11529 (leftOverRxTimeMs != 0 || leftOverTxTimeMs != 0)) {
Chenjie Yu89083392018-01-11 14:53:31 -080011530 for (int i = 0; i < deltaTraffic.size(); i++) {
11531 final UidTraffic traffic = deltaTraffic.get(i);
Adam Lesinski50e47602015-12-04 17:04:54 -080011532
Adam Lesinski50e47602015-12-04 17:04:54 -080011533 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011534 final ControllerActivityCounterImpl counter =
11535 u.getOrCreateBluetoothControllerActivityLocked();
11536
11537 if (totalRxBytes > 0 && traffic.getRxBytes() > 0) {
11538 final long timeRxMs = (leftOverRxTimeMs * traffic.getRxBytes()) / totalRxBytes;
11539
11540 if (DEBUG_ENERGY) {
11541 Slog.d(TAG, "UID=" + traffic.getUid() + " rx_bytes=" + traffic.getRxBytes()
11542 + " rx_time=" + timeRxMs);
11543 }
11544 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11545 leftOverRxTimeMs -= timeRxMs;
11546 }
11547
11548 if (totalTxBytes > 0 && traffic.getTxBytes() > 0) {
11549 final long timeTxMs = (leftOverTxTimeMs * traffic.getTxBytes()) / totalTxBytes;
11550
11551 if (DEBUG_ENERGY) {
11552 Slog.d(TAG, "UID=" + traffic.getUid() + " tx_bytes=" + traffic.getTxBytes()
11553 + " tx_time=" + timeTxMs);
11554 }
11555
11556 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11557 leftOverTxTimeMs -= timeTxMs;
11558 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011559 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011560 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011561
Chenjie Yu89083392018-01-11 14:53:31 -080011562 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11563 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11564 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011565
11566 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11567 final double opVolt = mPowerProfile.getAveragePower(
11568 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11569 if (opVolt != 0) {
11570 // We store the power drain as mAms.
11571 mBluetoothActivity.getPowerCounter().addCountLocked(
Chenjie Yu89083392018-01-11 14:53:31 -080011572 (long) ((info.getControllerEnergyUsed() -
11573 mLastBluetoothActivityEnergyInfo.getControllerEnergyUsed() )/ opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011574 }
Chenjie Yu89083392018-01-11 14:53:31 -080011575 mLastBluetoothActivityEnergyInfo = info;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011576 }
11577
11578 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011579 * Read and record Resource Power Manager (RPM) state and voter times.
11580 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11581 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011582 */
11583 public void updateRpmStatsLocked() {
11584 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011585 long now = SystemClock.elapsedRealtime();
11586 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11587 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11588 mLastRpmStatsUpdateTimeMs = now;
11589 }
Bookatz50df7112017-08-04 14:53:26 -070011590
11591 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11592 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11593
11594 // Update values for this platform state.
11595 final String pName = pstate.getKey();
11596 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11597 final int pCount = pstate.getValue().mCount;
11598 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011599 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11600 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11601 }
Bookatz50df7112017-08-04 14:53:26 -070011602
11603 // Update values for each voter of this platform state.
11604 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11605 : pstate.getValue().mVoters.entrySet()) {
11606 final String vName = pName + "." + voter.getKey();
11607 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11608 final int vCount = voter.getValue().mCount;
11609 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011610 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11611 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11612 }
Bookatz50df7112017-08-04 14:53:26 -070011613 }
11614 }
11615
11616 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11617 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11618
11619 final String subsysName = subsys.getKey();
11620 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11621 : subsys.getValue().mStates.entrySet()) {
11622 final String name = subsysName + "." + sstate.getKey();
11623 final long timeUs = sstate.getValue().mTimeMs * 1000;
11624 final int count = sstate.getValue().mCount;
11625 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011626 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11627 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11628 }
Bookatz50df7112017-08-04 14:53:26 -070011629 }
11630 }
11631 }
11632
11633 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011634 * Read and distribute kernel wake lock use across apps.
11635 */
11636 public void updateKernelWakelocksLocked() {
11637 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11638 mTmpWakelockStats);
11639 if (wakelockStats == null) {
11640 // Not crashing might make board bringup easier.
11641 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11642 return;
11643 }
11644
11645 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11646 String name = ent.getKey();
11647 KernelWakelockStats.Entry kws = ent.getValue();
11648
11649 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11650 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011651 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011652 mKernelWakelockStats.put(name, kwlt);
11653 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011654
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011655 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011656 kwlt.setUpdateVersion(kws.mVersion);
11657 }
11658
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011659 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011660 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11661 // this time.
11662 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11663 SamplingTimer st = ent.getValue();
11664 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11665 st.endSample();
11666 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011667 }
11668 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011669
Adam Lesinskid84ad302016-05-17 18:31:02 -070011670 // Record whether we've seen a non-zero time (for debugging b/22716723).
11671 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011672 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11673 }
11674
11675 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11676 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11677 wakelockStats.kernelWakelockVersion);
11678 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011679 }
11680
Adam Lesinski72478f02015-06-17 15:39:43 -070011681 // We use an anonymous class to access these variables,
11682 // so they can't live on the stack or they'd have to be
11683 // final MutableLong objects (more allocations).
11684 // Used in updateCpuTimeLocked().
11685 long mTempTotalCpuUserTimeUs;
11686 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011687 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011688
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011689 /**
James Carr3a226052016-07-01 14:49:52 -070011690 * Reads the newest memory stats from the kernel.
11691 */
11692 public void updateKernelMemoryBandwidthLocked() {
11693 mKernelMemoryBandwidthStats.updateStats();
11694 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11695 final int bandwidthEntryCount = bandwidthEntries.size();
11696 int index;
11697 for (int i = 0; i < bandwidthEntryCount; i++) {
11698 SamplingTimer timer;
11699 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11700 timer = mKernelMemoryStats.valueAt(index);
11701 } else {
11702 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11703 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11704 }
11705 timer.update(bandwidthEntries.valueAt(i), 1);
11706 if (DEBUG_MEMORY) {
11707 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11708 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11709 mKernelMemoryStats.get(
11710 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11711 mKernelMemoryStats.size()));
11712 }
11713 }
11714 }
11715
11716 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011717 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11718 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11719 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011720 */
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011721 public void updateCpuTimeLocked() {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011722 if (mPowerProfile == null) {
11723 return;
11724 }
11725
Adam Lesinski72478f02015-06-17 15:39:43 -070011726 if (DEBUG_ENERGY_CPU) {
11727 Slog.d(TAG, "!Cpu updating!");
11728 }
11729
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011730 if (mCpuFreqs == null) {
11731 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11732 }
11733
Sudheer Shanka38383232017-07-25 09:55:03 -070011734 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11735 // usually holding the wakelock on behalf of an app.
11736 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11737 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Adam Lesinski72478f02015-06-17 15:39:43 -070011738 if (mOnBatteryScreenOffTimeBase.isRunning()) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011739 partialTimersToConsider = new ArrayList<>();
11740 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011741 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011742 // Since the collection and blaming of wakelocks can be scheduled to run after
11743 // some delay, the mPartialTimers list may have new entries. We can't blame
11744 // the newly added timer for past cpu time, so we only consider timers that
11745 // were present for one round of collection. Once a timer has gone through
11746 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011747 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011748 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011749 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011750 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011751 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011752 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011753
Sudheer Shanka38383232017-07-25 09:55:03 -070011754 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11755 // need to take the snapshots.
11756 if (!mOnBatteryInternal) {
11757 mKernelUidCpuTimeReader.readDelta(null);
11758 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Mafae87da2018-01-19 20:07:20 -080011759 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11760 mKernelUidCpuActiveTimeReader.readDelta(null);
11761 mKernelUidCpuClusterTimeReader.readDelta(null);
11762 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011763 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
11764 mKernelCpuSpeedReaders[cluster].readDelta();
11765 }
11766 return;
11767 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011768
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011769 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011770 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
11771 ? null : new SparseLongArray();
Sudheer Shanka38383232017-07-25 09:55:03 -070011772 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011773 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
11774 // freqs, so no need to approximate these values.
11775 if (updatedUids != null) {
11776 updateClusterSpeedTimes(updatedUids);
Sudheer Shanka671985f2017-05-19 11:33:42 -070011777 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011778 readKernelUidCpuFreqTimesLocked(partialTimersToConsider);
Mike Mafae87da2018-01-19 20:07:20 -080011779 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11780 readKernelUidCpuActiveTimesLocked();
11781 readKernelUidCpuClusterTimesLocked();
11782 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011783 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011784
Sudheer Shanka38383232017-07-25 09:55:03 -070011785 /**
11786 * Mark the current partial timers as gone through a collection so that they will be
11787 * considered in the next cpu times distribution to wakelock holders.
11788 */
11789 @VisibleForTesting
11790 public void markPartialTimersAsEligible() {
11791 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
11792 // No difference, so each timer is now considered for the next collection.
11793 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
11794 mPartialTimers.get(i).mInList = true;
11795 }
11796 } else {
11797 // The lists are different, meaning we added (or removed a timer) since the last
11798 // collection.
11799 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
11800 mLastPartialTimers.get(i).mInList = false;
11801 }
11802 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070011803
Sudheer Shanka38383232017-07-25 09:55:03 -070011804 // Mark the current timers as gone through a collection.
11805 final int numPartialTimers = mPartialTimers.size();
11806 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011807 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011808 timer.mInList = true;
11809 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070011810 }
11811 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011812 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011813
Sudheer Shanka38383232017-07-25 09:55:03 -070011814 /**
11815 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
11816 * calculate cpu times spent by each uid at different frequencies.
11817 *
11818 * @param updatedUids The uids for which times spent at different frequencies are calculated.
11819 */
11820 @VisibleForTesting
11821 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011822 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011823 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070011824 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011825 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011826 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
11827 if (clusterSpeedTimesMs[cluster] != null) {
11828 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
11829 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011830 }
11831 }
11832 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011833 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011834 // We have cpu times per freq aggregated over all uids but we need the times per uid.
11835 // So, we distribute total time spent by an uid to different cpu freqs based on the
11836 // amount of time cpu was running at that freq.
11837 final int updatedUidsCount = updatedUids.size();
11838 for (int i = 0; i < updatedUidsCount; ++i) {
11839 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070011840 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011841 // Add the cpu speeds to this UID.
11842 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070011843 if (u.mCpuClusterSpeedTimesUs == null ||
11844 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011845 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011846 }
11847
Sudheer Shankaaf857412017-07-21 00:14:24 -070011848 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
11849 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
11850 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
11851 u.mCpuClusterSpeedTimesUs[cluster].length) {
11852 u.mCpuClusterSpeedTimesUs[cluster]
11853 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011854 }
11855
Sudheer Shankaaf857412017-07-21 00:14:24 -070011856 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011857 for (int speed = 0; speed < speedsInCluster; speed++) {
11858 if (cpuSpeeds[speed] == null) {
11859 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11860 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011861 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
11862 * clusterSpeedTimesMs[cluster][speed]
11863 / totalCpuClustersTimeMs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011864 }
11865 }
11866 }
11867 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011868 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011869
Sudheer Shanka38383232017-07-25 09:55:03 -070011870 /**
11871 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
11872 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
11873 * wakelock holders.
11874 *
11875 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
11876 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
11877 */
11878 @VisibleForTesting
11879 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
11880 @Nullable SparseLongArray updatedUids) {
11881 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
11882 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11883 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070011884
Sudheer Shanka38383232017-07-25 09:55:03 -070011885 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
11886 uid = mapUid(uid);
11887 if (Process.isIsolated(uid)) {
11888 // This could happen if the isolated uid mapping was removed before that process
11889 // was actually killed.
11890 mKernelUidCpuTimeReader.removeUid(uid);
11891 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
11892 return;
11893 }
11894 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11895 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
11896 mKernelUidCpuTimeReader.removeUid(uid);
11897 return;
11898 }
11899 final Uid u = getUidStatsLocked(uid);
11900
11901 // Accumulate the total system and user time.
11902 mTempTotalCpuUserTimeUs += userTimeUs;
11903 mTempTotalCpuSystemTimeUs += systemTimeUs;
11904
11905 StringBuilder sb = null;
11906 if (DEBUG_ENERGY_CPU) {
11907 sb = new StringBuilder();
11908 sb.append(" got time for uid=").append(u.mUid).append(": u=");
11909 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11910 sb.append(" s=");
11911 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11912 sb.append("\n");
11913 }
11914
11915 if (numWakelocks > 0) {
11916 // We have wakelocks being held, so only give a portion of the
11917 // time to the process. The rest will be distributed among wakelock
11918 // holders.
11919 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
11920 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
11921 }
11922
11923 if (sb != null) {
11924 sb.append(" adding to uid=").append(u.mUid).append(": u=");
11925 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11926 sb.append(" s=");
11927 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11928 Slog.d(TAG, sb.toString());
11929 }
11930
11931 u.mUserCpuTime.addCountLocked(userTimeUs);
11932 u.mSystemCpuTime.addCountLocked(systemTimeUs);
11933 if (updatedUids != null) {
11934 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
11935 }
11936 });
11937
11938 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11939 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11940 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
11941 }
11942
11943 if (numWakelocks > 0) {
11944 // Distribute a portion of the total cpu time to wakelock holders.
11945 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11946 mTempTotalCpuSystemTimeUs =
11947 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11948
11949 for (int i = 0; i < numWakelocks; ++i) {
11950 final StopwatchTimer timer = partialTimers.get(i);
11951 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
11952 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
11953
11954 if (DEBUG_ENERGY_CPU) {
11955 final StringBuilder sb = new StringBuilder();
11956 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
11957 .append(": u=");
11958 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11959 sb.append(" s=");
11960 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11961 Slog.d(TAG, sb.toString());
11962 }
11963
11964 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs);
11965 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs);
11966 if (updatedUids != null) {
11967 final int uid = timer.mUid.getUid();
11968 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
11969 }
11970
11971 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
11972 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000);
11973
11974 mTempTotalCpuUserTimeUs -= userTimeUs;
11975 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011976 }
11977 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011978 }
11979
Sudheer Shanka38383232017-07-25 09:55:03 -070011980 /**
11981 * Take a snapshot of the cpu times spent by each uid in each freq and update the
11982 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011983 *
11984 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070011985 */
11986 @VisibleForTesting
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011987 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers) {
11988 final boolean perClusterTimesAvailable =
11989 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
11990 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11991 final int numClusters = mPowerProfile.getNumCpuClusters();
11992 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080011993 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011994 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
11995 uid = mapUid(uid);
11996 if (Process.isIsolated(uid)) {
11997 mKernelUidCpuFreqTimeReader.removeUid(uid);
11998 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
11999 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070012000 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012001 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12002 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
12003 mKernelUidCpuFreqTimeReader.removeUid(uid);
12004 return;
12005 }
12006 final Uid u = getUidStatsLocked(uid);
12007 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12008 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
12009 }
12010 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
12011 if (u.mScreenOffCpuFreqTimeMs == null ||
12012 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12013 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
12014 mOnBatteryScreenOffTimeBase);
12015 }
12016 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012017
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012018 if (perClusterTimesAvailable) {
12019 if (u.mCpuClusterSpeedTimesUs == null ||
12020 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12021 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012022 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012023 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
12024 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012025 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012026
12027 int freqIndex = 0;
12028 for (int cluster = 0; cluster < numClusters; ++cluster) {
12029 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12030 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12031 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12032 u.mCpuClusterSpeedTimesUs[cluster]
12033 = new LongSamplingCounter[speedsInCluster];
12034 }
12035 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
12036 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
12037 }
12038 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
12039 for (int speed = 0; speed < speedsInCluster; ++speed) {
12040 if (cpuTimesUs[speed] == null) {
12041 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12042 }
12043 final long appAllocationUs;
12044 if (mWakeLockAllocationsUs != null) {
12045 appAllocationUs =
12046 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
12047 mWakeLockAllocationsUs[cluster][speed] +=
12048 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
12049 } else {
12050 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
12051 }
12052 cpuTimesUs[speed].addCountLocked(appAllocationUs);
12053 freqIndex++;
12054 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012055 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012056 }
12057 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012058
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012059 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12060 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12061 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
12062 }
12063
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012064 if (mWakeLockAllocationsUs != null) {
12065 for (int i = 0; i < numWakelocks; ++i) {
12066 final Uid u = partialTimers.get(i).mUid;
12067 if (u.mCpuClusterSpeedTimesUs == null ||
12068 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12069 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
12070 }
12071
12072 for (int cluster = 0; cluster < numClusters; ++cluster) {
12073 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12074 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12075 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12076 u.mCpuClusterSpeedTimesUs[cluster]
12077 = new LongSamplingCounter[speedsInCluster];
12078 }
12079 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
12080 for (int speed = 0; speed < speedsInCluster; ++speed) {
12081 if (cpuTimeUs[speed] == null) {
12082 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12083 }
12084 final long allocationUs =
12085 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
12086 cpuTimeUs[speed].addCountLocked(allocationUs);
12087 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
12088 }
12089 }
12090 }
12091 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012092 }
12093
Mike Ma3d422c32017-10-25 11:08:57 -070012094 /**
12095 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
12096 * counters.
12097 */
12098 @VisibleForTesting
12099 public void readKernelUidCpuActiveTimesLocked() {
12100 final long startTimeMs = mClocks.uptimeMillis();
12101 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesUs) -> {
12102 uid = mapUid(uid);
12103 if (Process.isIsolated(uid)) {
12104 mKernelUidCpuActiveTimeReader.removeUid(uid);
12105 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
12106 return;
12107 }
12108 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12109 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
12110 mKernelUidCpuActiveTimeReader.removeUid(uid);
12111 return;
12112 }
12113 final Uid u = getUidStatsLocked(uid);
12114 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesUs);
12115 });
12116
12117 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12118 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12119 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12120 }
12121 }
12122
12123 /**
12124 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12125 * counters.
12126 */
12127 @VisibleForTesting
12128 public void readKernelUidCpuClusterTimesLocked() {
12129 final long startTimeMs = mClocks.uptimeMillis();
12130 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesUs) -> {
12131 uid = mapUid(uid);
12132 if (Process.isIsolated(uid)) {
12133 mKernelUidCpuClusterTimeReader.removeUid(uid);
12134 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12135 return;
12136 }
12137 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12138 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12139 mKernelUidCpuClusterTimeReader.removeUid(uid);
12140 return;
12141 }
12142 final Uid u = getUidStatsLocked(uid);
12143 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesUs);
12144 });
12145
12146 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12147 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12148 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12149 }
12150 }
12151
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012152 boolean setChargingLocked(boolean charging) {
12153 if (mCharging != charging) {
12154 mCharging = charging;
12155 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012156 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012157 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012158 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012159 }
12160 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12161 return true;
12162 }
12163 return false;
12164 }
12165
Mike Mac2f518a2017-09-19 16:06:03 -070012166 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12167 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012168 boolean doWrite = false;
12169 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12170 m.arg1 = onBattery ? 1 : 0;
12171 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012172
Dianne Hackborn40c87252014-03-19 16:55:40 -070012173 final long uptime = mSecUptime * 1000;
12174 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012175 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012176 if (onBattery) {
12177 // We will reset our status if we are unplugging after the
12178 // battery was last full, or the level is at 100, or
12179 // we have gone through a significant charge (from a very low
12180 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012181 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012182 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012183 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012184 || (mDischargeCurrentLevel < 20 && level >= 80)
12185 || (getHighDischargeAmountSinceCharge() >= 200
12186 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012187 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012188 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012189 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12190 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012191 // Before we write, collect a snapshot of the final aggregated
12192 // stats to be reported in the next checkin. Only do this if we have
12193 // a sufficient amount of data to make it interesting.
12194 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012195 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012196 final Parcel parcel = Parcel.obtain();
12197 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012198 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012199 BackgroundThread.getHandler().post(new Runnable() {
12200 @Override public void run() {
12201 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012202 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012203 FileOutputStream stream = null;
12204 try {
12205 stream = mCheckinFile.startWrite();
12206 stream.write(parcel.marshall());
12207 stream.flush();
12208 FileUtils.sync(stream);
12209 stream.close();
12210 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012211 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12212 "batterystats-checkin",
12213 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012214 } catch (IOException e) {
12215 Slog.w("BatteryStats",
12216 "Error writing checkin battery statistics", e);
12217 mCheckinFile.failWrite(stream);
12218 } finally {
12219 parcel.recycle();
12220 }
12221 }
12222 }
12223 });
12224 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012225 doWrite = true;
12226 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012227 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012228 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012229 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012230 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012231 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012232 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012233 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012234 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012235 if (mCharging) {
12236 setChargingLocked(false);
12237 }
12238 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012239 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012240 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012241 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012242 mDischargeStepTracker.clearTime();
12243 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012244 mInitStepMode = mCurStepMode;
12245 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012246 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012247 mHistoryCur.batteryLevel = (byte)level;
12248 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12249 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12250 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012251 if (reset) {
12252 mRecordingHistory = true;
12253 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12254 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012255 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012256 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012257 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012258 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012259 mDischargeScreenDozeUnplugLevel = 0;
12260 mDischargeScreenOffUnplugLevel = 0;
12261 } else if (isScreenDoze(screenState)) {
12262 mDischargeScreenOnUnplugLevel = 0;
12263 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012264 mDischargeScreenOffUnplugLevel = 0;
12265 } else {
12266 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012267 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012268 mDischargeScreenOffUnplugLevel = level;
12269 }
12270 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012271 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012272 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012273 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012274 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012275 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012276 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012277 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012278 mHistoryCur.batteryLevel = (byte)level;
12279 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12280 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12281 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012282 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012283 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012284 if (level < mDischargeUnplugLevel) {
12285 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12286 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12287 }
Mike Mac2f518a2017-09-19 16:06:03 -070012288 updateDischargeScreenLevelsLocked(screenState, screenState);
12289 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012290 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012291 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012292 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012293 mInitStepMode = mCurStepMode;
12294 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012295 }
12296 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12297 if (mFile != null) {
12298 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012299 }
12300 }
12301 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012302
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012303 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12304 boolean reset) {
12305 mRecordingHistory = true;
12306 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012307 addHistoryBufferLocked(elapsedRealtimeMs,
Dianne Hackborn37de0982014-05-09 09:32:18 -070012308 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012309 mHistoryCur);
12310 mHistoryCur.currentTime = 0;
12311 if (reset) {
12312 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12313 }
12314 }
12315
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012316 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12317 final long uptimeMs) {
12318 if (mRecordingHistory) {
12319 mHistoryCur.currentTime = currentTime;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012320 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_CURRENT_TIME, mHistoryCur);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012321 mHistoryCur.currentTime = 0;
12322 }
12323 }
12324
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012325 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12326 if (mRecordingHistory) {
12327 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012328 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_SHUTDOWN, mHistoryCur);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012329 mHistoryCur.currentTime = 0;
12330 }
12331 }
12332
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012333 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012334 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012335 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012336 }
12337 }
12338
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012339 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012340 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012341
Bookatz8c6571b2017-10-24 15:04:41 -070012342 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12343 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12344 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012345 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12346 temp = Math.max(0, temp);
12347
Bookatz8c6571b2017-10-24 15:04:41 -070012348 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
12349 status, plugType, level, temp);
12350
Todd Poynor1acf06a2017-12-07 19:19:35 -080012351 final boolean onBattery =
12352 plugType == BATTERY_PLUGGED_NONE &&
12353 status != BatteryManager.BATTERY_STATUS_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080012354 final long uptime = mClocks.uptimeMillis();
12355 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012356 if (!mHaveBatteryLevel) {
12357 mHaveBatteryLevel = true;
12358 // We start out assuming that the device is plugged in (not
12359 // on battery). If our first report is now that we are indeed
12360 // plugged in, then twiddle our state to correctly reflect that
12361 // since we won't be going through the full setOnBattery().
12362 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012363 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012364 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012365 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012366 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012367 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012368 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012369 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012370 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012371 mHistoryCur.batteryStatus = (byte)status;
12372 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012373 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012374 mMaxChargeStepLevel = mMinDischargeStepLevel =
12375 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012376 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012377 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12378 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12379 }
12380 int oldStatus = mHistoryCur.batteryStatus;
12381 if (onBattery) {
12382 mDischargeCurrentLevel = level;
12383 if (!mRecordingHistory) {
12384 mRecordingHistory = true;
12385 startRecordingHistory(elapsedRealtime, uptime, true);
12386 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012387 } else if (level < 96 &&
12388 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012389 if (!mRecordingHistory) {
12390 mRecordingHistory = true;
12391 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012392 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012393 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012394 mCurrentBatteryLevel = level;
12395 if (mDischargePlugLevel < 0) {
12396 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012397 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012398
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012399 if (onBattery != mOnBattery) {
12400 mHistoryCur.batteryLevel = (byte)level;
12401 mHistoryCur.batteryStatus = (byte)status;
12402 mHistoryCur.batteryHealth = (byte)health;
12403 mHistoryCur.batteryPlugType = (byte)plugType;
12404 mHistoryCur.batteryTemperature = (short)temp;
12405 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012406 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12407 // Only record discharges
12408 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12409 mDischargeCounter.addCountLocked(chargeDiff);
12410 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012411 if (isScreenDoze(mScreenState)) {
12412 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12413 }
Mike Ma15313c92017-11-15 17:58:21 -080012414 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12415 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12416 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12417 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12418 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012419 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012420 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012421 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012422 } else {
12423 boolean changed = false;
12424 if (mHistoryCur.batteryLevel != level) {
12425 mHistoryCur.batteryLevel = (byte)level;
12426 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012427
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012428 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12429 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012430 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070012431 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012432 if (mHistoryCur.batteryStatus != status) {
12433 mHistoryCur.batteryStatus = (byte)status;
12434 changed = true;
12435 }
12436 if (mHistoryCur.batteryHealth != health) {
12437 mHistoryCur.batteryHealth = (byte)health;
12438 changed = true;
12439 }
12440 if (mHistoryCur.batteryPlugType != plugType) {
12441 mHistoryCur.batteryPlugType = (byte)plugType;
12442 changed = true;
12443 }
12444 if (temp >= (mHistoryCur.batteryTemperature+10)
12445 || temp <= (mHistoryCur.batteryTemperature-10)) {
12446 mHistoryCur.batteryTemperature = (short)temp;
12447 changed = true;
12448 }
12449 if (volt > (mHistoryCur.batteryVoltage+20)
12450 || volt < (mHistoryCur.batteryVoltage-20)) {
12451 mHistoryCur.batteryVoltage = (char)volt;
12452 changed = true;
12453 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012454 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12455 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012456 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12457 // Only record discharges
12458 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12459 mDischargeCounter.addCountLocked(chargeDiff);
12460 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012461 if (isScreenDoze(mScreenState)) {
12462 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12463 }
Mike Ma15313c92017-11-15 17:58:21 -080012464 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12465 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12466 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12467 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12468 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012469 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012470 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012471 changed = true;
12472 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012473 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12474 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12475 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12476 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012477 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012478 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12479 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12480 modeBits, elapsedRealtime);
12481 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12482 modeBits, elapsedRealtime);
12483 mLastDischargeStepLevel = level;
12484 mMinDischargeStepLevel = level;
12485 mInitStepMode = mCurStepMode;
12486 mModStepMode = 0;
12487 }
12488 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012489 if (level >= 90) {
12490 // If the battery level is at least 90%, always consider the device to be
12491 // charging even if it happens to go down a level.
12492 changed |= setChargingLocked(true);
12493 mLastChargeStepLevel = level;
12494 } if (!mCharging) {
12495 if (mLastChargeStepLevel < level) {
12496 // We have not reporting that we are charging, but the level has now
12497 // gone up, so consider the state to be charging.
12498 changed |= setChargingLocked(true);
12499 mLastChargeStepLevel = level;
12500 }
12501 } else {
12502 if (mLastChargeStepLevel > level) {
12503 // We had reported that the device was charging, but here we are with
12504 // power connected and the level going down. Looks like the current
12505 // power supplied isn't enough, so consider the device to now be
12506 // discharging.
12507 changed |= setChargingLocked(false);
12508 mLastChargeStepLevel = level;
12509 }
12510 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012511 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12512 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12513 modeBits, elapsedRealtime);
12514 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12515 modeBits, elapsedRealtime);
12516 mLastChargeStepLevel = level;
12517 mMaxChargeStepLevel = level;
12518 mInitStepMode = mCurStepMode;
12519 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012520 }
12521 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012522 if (changed) {
12523 addHistoryRecordLocked(elapsedRealtime, uptime);
12524 }
Evan Millarc64edde2009-04-18 12:26:32 -070012525 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012526 if (!onBattery &&
12527 (status == BatteryManager.BATTERY_STATUS_FULL ||
12528 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12529 // We don't record history while we are plugged in and fully charged
12530 // (or when battery is not present). The next time we are
12531 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012532 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012533 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012534
Jocelyn Dangc627d102017-04-14 13:15:14 -070012535 if (mMinLearnedBatteryCapacity == -1) {
12536 mMinLearnedBatteryCapacity = chargeFullUAh;
12537 } else {
12538 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012539 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012540 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012541 }
12542
Bookatz8c6571b2017-10-24 15:04:41 -070012543 // Inform StatsLog of setBatteryState changes.
12544 // If this is the first reporting, pass in recentPast == null.
12545 private void reportChangesToStatsLog(HistoryItem recentPast,
12546 final int status, final int plugType, final int level, final int temp) {
12547
12548 if (recentPast == null || recentPast.batteryStatus != status) {
12549 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12550 }
12551 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12552 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12553 }
12554 if (recentPast == null || recentPast.batteryLevel != level) {
12555 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12556 }
12557 // Let's just always print the temperature, regardless of whether it changed.
12558 StatsLog.write(StatsLog.DEVICE_TEMPERATURE_REPORTED, temp);
12559 }
12560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012561 public long getAwakeTimeBattery() {
12562 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12563 }
12564
12565 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012566 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012567 }
12568
12569 @Override
12570 public long computeUptime(long curTime, int which) {
12571 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012572 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012573 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012574 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012575 }
12576 return 0;
12577 }
12578
12579 @Override
12580 public long computeRealtime(long curTime, int which) {
12581 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012582 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012583 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012584 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585 }
12586 return 0;
12587 }
12588
12589 @Override
12590 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012591 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012592 }
12593
12594 @Override
12595 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012596 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012597 }
12598
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012599 @Override
12600 public long computeBatteryScreenOffUptime(long curTime, int which) {
12601 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12602 }
12603
12604 @Override
12605 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12606 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012607 }
12608
Dianne Hackborn260c5022014-04-29 11:23:16 -070012609 private long computeTimePerLevel(long[] steps, int numSteps) {
12610 // For now we'll do a simple average across all steps.
12611 if (numSteps <= 0) {
12612 return -1;
12613 }
12614 long total = 0;
12615 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012616 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012617 }
12618 return total / numSteps;
12619 /*
12620 long[] buckets = new long[numSteps];
12621 int numBuckets = 0;
12622 int numToAverage = 4;
12623 int i = 0;
12624 while (i < numSteps) {
12625 long totalTime = 0;
12626 int num = 0;
12627 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012628 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012629 num++;
12630 }
12631 buckets[numBuckets] = totalTime / num;
12632 numBuckets++;
12633 numToAverage *= 2;
12634 i += num;
12635 }
12636 if (numBuckets < 1) {
12637 return -1;
12638 }
12639 long averageTime = buckets[numBuckets-1];
12640 for (i=numBuckets-2; i>=0; i--) {
12641 averageTime = (averageTime + buckets[i]) / 2;
12642 }
12643 return averageTime;
12644 */
12645 }
12646
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012647 @Override
12648 public long computeBatteryTimeRemaining(long curTime) {
12649 if (!mOnBattery) {
12650 return -1;
12651 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012652 /* Simple implementation just looks at the average discharge per level across the
12653 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012654 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12655 if (discharge < 2) {
12656 return -1;
12657 }
12658 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12659 if (duration < 1000*1000) {
12660 return -1;
12661 }
12662 long usPerLevel = duration/discharge;
12663 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012664 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012665 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012666 return -1;
12667 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012668 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012669 if (msPerLevel <= 0) {
12670 return -1;
12671 }
12672 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012673 }
12674
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012675 @Override
12676 public LevelStepTracker getDischargeLevelStepTracker() {
12677 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012678 }
12679
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012680 @Override
12681 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12682 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012683 }
12684
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012685 @Override
12686 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012687 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012688 // Not yet working.
12689 return -1;
12690 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012691 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012692 int curLevel = mCurrentBatteryLevel;
12693 int plugLevel = mDischargePlugLevel;
12694 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12695 return -1;
12696 }
12697 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12698 if (duration < 1000*1000) {
12699 return -1;
12700 }
12701 long usPerLevel = duration/(curLevel-plugLevel);
12702 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012703 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012704 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012705 return -1;
12706 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012707 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012708 if (msPerLevel <= 0) {
12709 return -1;
12710 }
12711 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012712 }
12713
Siddharth Raya1fd0572017-11-13 14:20:47 -080012714 /*@hide */
12715 public CellularBatteryStats getCellularBatteryStats() {
12716 CellularBatteryStats s = new CellularBatteryStats();
12717 final int which = STATS_SINCE_CHARGED;
12718 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12719 final ControllerActivityCounter counter = getModemControllerActivity();
12720 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12721 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12722 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12723 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12724 for (int i = 0; i < timeInRatMs.length; i++) {
12725 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12726 }
12727 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12728 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12729 timeInRxSignalStrengthLevelMs[i]
12730 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12731 }
12732 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12733 counter.getTxTimeCounters().length)];
12734 long totalTxTimeMs = 0;
12735 for (int i = 0; i < txTimeMs.length; i++) {
12736 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12737 totalTxTimeMs += txTimeMs[i];
12738 }
12739 final long totalControllerActivityTimeMs
12740 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12741 final long sleepTimeMs
12742 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + totalTxTimeMs);
12743 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12744 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12745 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12746 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12747 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12748 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
12749 s.setSleepTimeMs(sleepTimeMs);
12750 s.setIdleTimeMs(idleTimeMs);
12751 s.setRxTimeMs(rxTimeMs);
12752 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12753 s.setTimeInRatMs(timeInRatMs);
12754 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
12755 s.setTxTimeMs(txTimeMs);
12756 return s;
12757 }
12758
Siddharth Rayb50a6842017-12-14 15:15:28 -080012759 /*@hide */
12760 public WifiBatteryStats getWifiBatteryStats() {
12761 WifiBatteryStats s = new WifiBatteryStats();
12762 final int which = STATS_SINCE_CHARGED;
12763 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12764 final ControllerActivityCounter counter = getWifiControllerActivity();
12765 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12766 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
12767 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12768 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
12769 final long totalControllerActivityTimeMs
12770 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12771 final long sleepTimeMs
12772 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
12773 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12774 long numAppScanRequest = 0;
12775 for (int i = 0; i < mUidStats.size(); i++) {
12776 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
12777 }
12778 long[] timeInStateMs = new long[NUM_WIFI_STATES];
12779 for (int i=0; i<NUM_WIFI_STATES; i++) {
12780 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
12781 }
12782 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
12783 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12784 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
12785 }
12786 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
12787 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12788 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
12789 }
12790 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12791 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
12792 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
12793 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
12794 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
12795 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
12796 s.setSleepTimeMs(sleepTimeMs);
12797 s.setIdleTimeMs(idleTimeMs);
12798 s.setRxTimeMs(rxTimeMs);
12799 s.setTxTimeMs(txTimeMs);
12800 s.setScanTimeMs(scanTimeMs);
12801 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12802 s.setNumAppScanRequest(numAppScanRequest);
12803 s.setTimeInStateMs(timeInStateMs);
12804 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
12805 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
12806 return s;
12807 }
12808
Siddharth Ray78ccaf52017-12-23 16:16:21 -080012809 /*@hide */
12810 public GpsBatteryStats getGpsBatteryStats() {
12811 GpsBatteryStats s = new GpsBatteryStats();
12812 final int which = STATS_SINCE_CHARGED;
12813 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12814 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12815 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
12816 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
12817 for (int i=0; i<time.length; i++) {
12818 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
12819 }
12820 s.setTimeInGpsSignalQualityLevel(time);
12821 return s;
12822 }
12823
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012824 @Override
12825 public LevelStepTracker getChargeLevelStepTracker() {
12826 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012827 }
12828
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012829 @Override
12830 public LevelStepTracker getDailyChargeLevelStepTracker() {
12831 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012832 }
12833
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012834 @Override
12835 public ArrayList<PackageChange> getDailyPackageChanges() {
12836 return mDailyPackageChanges;
12837 }
12838
Joe Onoratoe1acd632016-02-23 13:25:10 -080012839 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012840 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012841 }
12842
12843 @Override
12844 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012845 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012846 }
12847
12848 @Override
12849 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012850 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012851 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070012852
The Android Open Source Project10592532009-03-18 17:39:46 -070012853 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012854 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012855 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012856 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012857 }
12858 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012859
Evan Millar633a1742009-04-02 16:36:33 -070012860 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012861 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012862 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012863
The Android Open Source Project10592532009-03-18 17:39:46 -070012864 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012865 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012866 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012867 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012868 }
12869 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012870
Evan Millar633a1742009-04-02 16:36:33 -070012871 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012872 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012874
Amith Yamasanie43530a2009-08-21 13:11:37 -070012875 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012876 public int getLowDischargeAmountSinceCharge() {
12877 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012878 int val = mLowDischargeAmountSinceCharge;
12879 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12880 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
12881 }
12882 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012883 }
12884 }
12885
12886 @Override
12887 public int getHighDischargeAmountSinceCharge() {
12888 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012889 int val = mHighDischargeAmountSinceCharge;
12890 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12891 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
12892 }
12893 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012894 }
12895 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012896
12897 @Override
12898 public int getDischargeAmount(int which) {
12899 int dischargeAmount = which == STATS_SINCE_CHARGED
12900 ? getHighDischargeAmountSinceCharge()
12901 : (getDischargeStartLevel() - getDischargeCurrentLevel());
12902 if (dischargeAmount < 0) {
12903 dischargeAmount = 0;
12904 }
12905 return dischargeAmount;
12906 }
12907
Mike Mac2f518a2017-09-19 16:06:03 -070012908 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012909 public int getDischargeAmountScreenOn() {
12910 synchronized(this) {
12911 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070012912 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012913 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12914 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12915 }
12916 return val;
12917 }
12918 }
12919
Mike Mac2f518a2017-09-19 16:06:03 -070012920 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012921 public int getDischargeAmountScreenOnSinceCharge() {
12922 synchronized(this) {
12923 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070012924 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012925 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12926 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12927 }
12928 return val;
12929 }
12930 }
12931
Mike Mac2f518a2017-09-19 16:06:03 -070012932 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012933 public int getDischargeAmountScreenOff() {
12934 synchronized(this) {
12935 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070012936 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012937 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12938 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12939 }
Mike Mac2f518a2017-09-19 16:06:03 -070012940 // For backward compatibility, doze discharge is counted into screen off.
12941 return val + getDischargeAmountScreenDoze();
12942 }
12943 }
12944
12945 @Override
12946 public int getDischargeAmountScreenOffSinceCharge() {
12947 synchronized(this) {
12948 int val = mDischargeAmountScreenOffSinceCharge;
12949 if (mOnBattery && isScreenOff(mScreenState)
12950 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12951 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12952 }
12953 // For backward compatibility, doze discharge is counted into screen off.
12954 return val + getDischargeAmountScreenDozeSinceCharge();
12955 }
12956 }
12957
12958 @Override
12959 public int getDischargeAmountScreenDoze() {
12960 synchronized(this) {
12961 int val = mDischargeAmountScreenDoze;
12962 if (mOnBattery && isScreenDoze(mScreenState)
12963 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
12964 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
12965 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012966 return val;
12967 }
12968 }
12969
Mike Mac2f518a2017-09-19 16:06:03 -070012970 @Override
12971 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012972 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070012973 int val = mDischargeAmountScreenDozeSinceCharge;
12974 if (mOnBattery && isScreenDoze(mScreenState)
12975 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
12976 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012977 }
12978 return val;
12979 }
12980 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012982 /**
12983 * Retrieve the statistics object for a particular uid, creating if needed.
12984 */
12985 public Uid getUidStatsLocked(int uid) {
12986 Uid u = mUidStats.get(uid);
12987 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080012988 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012989 mUidStats.put(uid, u);
12990 }
12991 return u;
12992 }
12993
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012994 /**
12995 * Retrieve the statistics object for a particular uid. Returns null if the object is not
12996 * available.
12997 */
12998 public Uid getAvailableUidStatsLocked(int uid) {
12999 Uid u = mUidStats.get(uid);
13000 return u;
13001 }
13002
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013003 public void onCleanupUserLocked(int userId) {
13004 final int firstUidForUser = UserHandle.getUid(userId, 0);
13005 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13006 mKernelUidCpuFreqTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
13007 mKernelUidCpuTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013008 if (mKernelSingleUidTimeReader != null) {
13009 mKernelSingleUidTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
13010 }
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013011 }
13012
13013 public void onUserRemovedLocked(int userId) {
13014 final int firstUidForUser = UserHandle.getUid(userId, 0);
13015 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13016 mUidStats.put(firstUidForUser, null);
13017 mUidStats.put(lastUidForUser, null);
13018 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
13019 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
13020 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
13021 }
13022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013023 /**
13024 * Remove the statistics object for a particular uid.
13025 */
13026 public void removeUidStatsLocked(int uid) {
Adam Lesinskib83ffee2015-05-12 14:43:47 -070013027 mKernelUidCpuTimeReader.removeUid(uid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -070013028 mKernelUidCpuFreqTimeReader.removeUid(uid);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013029 if (mKernelSingleUidTimeReader != null) {
13030 mKernelSingleUidTimeReader.removeUid(uid);
13031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013032 mUidStats.remove(uid);
13033 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070013034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013035 /**
13036 * Retrieve the statistics object for a particular process, creating
13037 * if needed.
13038 */
13039 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013040 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013041 Uid u = getUidStatsLocked(uid);
13042 return u.getProcessStatsLocked(name);
13043 }
13044
13045 /**
13046 * Retrieve the statistics object for a particular process, creating
13047 * if needed.
13048 */
13049 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013050 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013051 Uid u = getUidStatsLocked(uid);
13052 return u.getPackageStatsLocked(pkg);
13053 }
13054
13055 /**
13056 * Retrieve the statistics object for a particular service, creating
13057 * if needed.
13058 */
13059 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013060 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013061 Uid u = getUidStatsLocked(uid);
13062 return u.getServiceStatsLocked(pkg, name);
13063 }
13064
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013065 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013066 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013067 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013068 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013069 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013070
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013071 public boolean trackPerProcStateCpuTimes() {
13072 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
13073 }
13074
13075 public void systemServicesReady(Context context) {
13076 mConstants.startObserving(context.getContentResolver());
13077 }
13078
13079 @VisibleForTesting
13080 public final class Constants extends ContentObserver {
13081 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
13082 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080013083 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
13084 = "track_cpu_active_cluster_time";
13085 public static final String KEY_READ_BINARY_CPU_TIME
13086 = "read_binary_cpu_time";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013087
13088 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080013089 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
13090 private static final boolean DEFAULT_READ_BINARY_CPU_TIME = false;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013091
13092 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013093 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
13094 // Not used right now.
13095 public boolean READ_BINARY_CPU_TIME = DEFAULT_READ_BINARY_CPU_TIME;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013096
13097 private ContentResolver mResolver;
13098 private final KeyValueListParser mParser = new KeyValueListParser(',');
13099
13100 public Constants(Handler handler) {
13101 super(handler);
13102 }
13103
13104 public void startObserving(ContentResolver resolver) {
13105 mResolver = resolver;
13106 mResolver.registerContentObserver(
13107 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13108 false /* notifyForDescendants */, this);
13109 updateConstants();
13110 }
13111
13112 @Override
13113 public void onChange(boolean selfChange, Uri uri) {
13114 updateConstants();
13115 }
13116
13117 private void updateConstants() {
13118 synchronized (BatteryStatsImpl.this) {
13119 try {
13120 mParser.setString(Settings.Global.getString(mResolver,
13121 Settings.Global.BATTERY_STATS_CONSTANTS));
13122 } catch (IllegalArgumentException e) {
13123 // Failed to parse the settings string, log this and move on
13124 // with defaults.
13125 Slog.e(TAG, "Bad batterystats settings", e);
13126 }
13127
13128 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13129 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13130 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013131 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13132 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
13133 READ_BINARY_CPU_TIME = mParser.getBoolean(
13134 KEY_READ_BINARY_CPU_TIME, DEFAULT_READ_BINARY_CPU_TIME);
13135
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013136 }
13137 }
13138
13139 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13140 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13141 if (isEnabled && !wasEnabled) {
13142 mKernelSingleUidTimeReader.markDataAsStale(true);
13143 mExternalSync.scheduleCpuSyncDueToSettingChange();
13144 }
13145 }
13146
13147 public void dumpLocked(PrintWriter pw) {
13148 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13149 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013150 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13151 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
13152 pw.print(KEY_READ_BINARY_CPU_TIME); pw.print("=");
13153 pw.println(READ_BINARY_CPU_TIME);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013154 }
13155 }
13156
13157 public void dumpConstantsLocked(PrintWriter pw) {
13158 mConstants.dumpLocked(pw);
13159 }
13160
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013161 Parcel mPendingWrite = null;
13162 final ReentrantLock mWriteLock = new ReentrantLock();
13163
13164 public void writeAsyncLocked() {
13165 writeLocked(false);
13166 }
13167
13168 public void writeSyncLocked() {
13169 writeLocked(true);
13170 }
13171
13172 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013173 if (mFile == null) {
13174 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013175 return;
13176 }
13177
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013178 if (mShuttingDown) {
13179 return;
13180 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013181
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013182 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013183 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013184 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013185
13186 if (mPendingWrite != null) {
13187 mPendingWrite.recycle();
13188 }
13189 mPendingWrite = out;
13190
13191 if (sync) {
13192 commitPendingDataToDisk();
13193 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013194 BackgroundThread.getHandler().post(new Runnable() {
13195 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013196 commitPendingDataToDisk();
13197 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013198 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013199 }
13200 }
13201
13202 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013203 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013204 synchronized (this) {
13205 next = mPendingWrite;
13206 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013207 if (next == null) {
13208 return;
13209 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013210 }
13211
Amith Yamasanid2450862017-02-07 15:58:24 -080013212 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013214 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013215 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013216 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013217 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013218 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013219 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013220 mFile.commit();
Dianne Hackborne17b4452018-01-10 13:15:40 -080013221 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13222 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013223 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013224 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013225 mFile.rollback();
13226 } finally {
13227 next.recycle();
13228 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013230 }
13231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013232 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013233 if (mDailyFile != null) {
13234 readDailyStatsLocked();
13235 }
13236
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013237 if (mFile == null) {
13238 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013239 return;
13240 }
13241
13242 mUidStats.clear();
13243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013244 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013245 File file = mFile.chooseForRead();
13246 if (!file.exists()) {
13247 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013248 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013249 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013250
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013251 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013252 Parcel in = Parcel.obtain();
13253 in.unmarshall(raw, 0, raw.length);
13254 in.setDataPosition(0);
13255 stream.close();
13256
13257 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013258 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013259 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013260 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013261 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013262
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013263 mEndPlatformVersion = Build.ID;
13264
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013265 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013266 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013267 final long elapsedRealtime = mClocks.elapsedRealtime();
13268 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013269 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013270 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013271 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000013272 addHistoryBufferLocked(elapsedRealtime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013273 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013274 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013275
13276 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013277 }
13278
13279 public int describeContents() {
13280 return 0;
13281 }
13282
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013283 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013284 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013285
13286 mHistoryBuffer.setDataSize(0);
13287 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013288 mHistoryTagPool.clear();
13289 mNextHistoryTagIdx = 0;
13290 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013291
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013292 int numTags = in.readInt();
13293 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013294 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013295 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013296 if (str == null) {
13297 throw new ParcelFormatException("null history tag string");
13298 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013299 int uid = in.readInt();
13300 HistoryTag tag = new HistoryTag();
13301 tag.string = str;
13302 tag.uid = uid;
13303 tag.poolIdx = idx;
13304 mHistoryTagPool.put(tag, idx);
13305 if (idx >= mNextHistoryTagIdx) {
13306 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013307 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013308 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013309 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013310
13311 int bufSize = in.readInt();
13312 int curPos = in.dataPosition();
13313 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013314 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13315 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013316 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013317 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13318 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013319 } else {
13320 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13321 + " bytes at " + curPos);
13322 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13323 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013324 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013325
Dianne Hackbornae384452011-06-28 12:33:48 -070013326 if (andOldHistory) {
13327 readOldHistory(in);
13328 }
13329
13330 if (DEBUG_HISTORY) {
13331 StringBuilder sb = new StringBuilder(128);
13332 sb.append("****************** OLD mHistoryBaseTime: ");
13333 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13334 Slog.i(TAG, sb.toString());
13335 }
13336 mHistoryBaseTime = historyBaseTime;
13337 if (DEBUG_HISTORY) {
13338 StringBuilder sb = new StringBuilder(128);
13339 sb.append("****************** NEW mHistoryBaseTime: ");
13340 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13341 Slog.i(TAG, sb.toString());
13342 }
13343
13344 // We are just arbitrarily going to insert 1 minute from the sample of
13345 // the last run until samples in this run.
13346 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013347 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013348 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013349 if (DEBUG_HISTORY) {
13350 StringBuilder sb = new StringBuilder(128);
13351 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13352 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13353 Slog.i(TAG, sb.toString());
13354 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013355 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013356 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013357
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013358 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013359 if (!USE_OLD_HISTORY) {
13360 return;
13361 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013362 mHistory = mHistoryEnd = mHistoryCache = null;
13363 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013364 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013365 HistoryItem rec = new HistoryItem(time, in);
13366 addHistoryRecordLocked(rec);
13367 }
13368 }
13369
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013370 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013371 if (DEBUG_HISTORY) {
13372 StringBuilder sb = new StringBuilder(128);
13373 sb.append("****************** WRITING mHistoryBaseTime: ");
13374 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013375 sb.append(" mLastHistoryElapsedRealtime: ");
13376 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013377 Slog.i(TAG, sb.toString());
13378 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013379 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013380 if (!inclData) {
13381 out.writeInt(0);
13382 out.writeInt(0);
13383 return;
13384 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013385 out.writeInt(mHistoryTagPool.size());
13386 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13387 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013388 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013389 out.writeString(tag.string);
13390 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013391 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013392 out.writeInt(mHistoryBuffer.dataSize());
13393 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13394 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13395 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013396
13397 if (andOldHistory) {
13398 writeOldHistory(out);
13399 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013400 }
13401
13402 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013403 if (!USE_OLD_HISTORY) {
13404 return;
13405 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013406 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013407 while (rec != null) {
13408 if (rec.time >= 0) rec.writeToParcel(out, 0);
13409 rec = rec.next;
13410 }
13411 out.writeLong(-1);
13412 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013413
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013414 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013415 final int version = in.readInt();
13416 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013417 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013418 + ", expected " + VERSION + "; erasing old stats");
13419 return;
13420 }
13421
Dianne Hackbornae384452011-06-28 12:33:48 -070013422 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013424 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013425 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013426 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013427 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013428 mStartPlatformVersion = in.readString();
13429 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013430 mOnBatteryTimeBase.readSummaryFromParcel(in);
13431 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013432 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013433 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013434 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013435 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013436 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013437 mMinLearnedBatteryCapacity = in.readInt();
13438 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013439 mLowDischargeAmountSinceCharge = in.readInt();
13440 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013441 mDischargeAmountScreenOnSinceCharge = in.readInt();
13442 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013443 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013444 mDischargeStepTracker.readFromParcel(in);
13445 mChargeStepTracker.readFromParcel(in);
13446 mDailyDischargeStepTracker.readFromParcel(in);
13447 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013448 mDischargeCounter.readSummaryFromParcelLocked(in);
13449 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013450 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013451 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13452 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013453 int NPKG = in.readInt();
13454 if (NPKG > 0) {
13455 mDailyPackageChanges = new ArrayList<>(NPKG);
13456 while (NPKG > 0) {
13457 NPKG--;
13458 PackageChange pc = new PackageChange();
13459 pc.mPackageName = in.readString();
13460 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013461 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013462 mDailyPackageChanges.add(pc);
13463 }
13464 } else {
13465 mDailyPackageChanges = null;
13466 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013467 mDailyStartTime = in.readLong();
13468 mNextMinDailyDeadline = in.readLong();
13469 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013471 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013472
Jeff Browne95c3cd2014-05-02 16:59:26 -070013473 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013474 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013475 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013476 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13477 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13478 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013479 mInteractive = false;
13480 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013481 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013482 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013483 mLongestLightIdleTime = in.readLong();
13484 mLongestFullIdleTime = in.readLong();
13485 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13486 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13487 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013488 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013489 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013490 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013491 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13492 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013493 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013494 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13495 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13496 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013497 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013498 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13499 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013500 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013501 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013502 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013503 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013504 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013505 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13506 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013507 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013508 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013509 mWifiOn = false;
13510 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013511 mGlobalWifiRunning = false;
13512 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013513 for (int i=0; i<NUM_WIFI_STATES; i++) {
13514 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13515 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013516 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13517 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13518 }
13519 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13520 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13521 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013522 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13523 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013524 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13525 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13526 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013527 mBluetoothActivity.readSummaryFromParcel(in);
13528 mModemActivity.readSummaryFromParcel(in);
13529 mHasWifiReporting = in.readInt() != 0;
13530 mHasBluetoothReporting = in.readInt() != 0;
13531 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013532
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013533 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013534 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013535 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013536 mCameraOnNesting = 0;
13537 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013538 mBluetoothScanNesting = 0;
13539 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013540
Bookatz50df7112017-08-04 14:53:26 -070013541 int NRPMS = in.readInt();
13542 if (NRPMS > 10000) {
13543 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13544 }
13545 for (int irpm = 0; irpm < NRPMS; irpm++) {
13546 if (in.readInt() != 0) {
13547 String rpmName = in.readString();
13548 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13549 }
13550 }
13551 int NSORPMS = in.readInt();
13552 if (NSORPMS > 10000) {
13553 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13554 }
13555 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13556 if (in.readInt() != 0) {
13557 String rpmName = in.readString();
13558 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13559 }
13560 }
13561
Evan Millarc64edde2009-04-18 12:26:32 -070013562 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013563 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013564 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013565 }
Evan Millarc64edde2009-04-18 12:26:32 -070013566 for (int ikw = 0; ikw < NKW; ikw++) {
13567 if (in.readInt() != 0) {
13568 String kwltName = in.readString();
13569 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13570 }
13571 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013572
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013573 int NWR = in.readInt();
13574 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013575 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013576 }
13577 for (int iwr = 0; iwr < NWR; iwr++) {
13578 if (in.readInt() != 0) {
13579 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013580 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013581 }
13582 }
13583
James Carr3a226052016-07-01 14:49:52 -070013584 int NMS = in.readInt();
13585 for (int ims = 0; ims < NMS; ims++) {
13586 if (in.readInt() != 0) {
13587 long kmstName = in.readLong();
13588 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13589 }
13590 }
13591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013592 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013593 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013594 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013596 for (int iu = 0; iu < NU; iu++) {
13597 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013598 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013599 mUidStats.put(uid, u);
13600
Bookatz867c0d72017-03-07 18:23:42 -080013601 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013602 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013603
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013604 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013605 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013606 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013607 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013608 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013609 if (in.readInt() != 0) {
13610 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13611 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013612 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013613 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013614 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013615 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013616 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13617 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13618 if (in.readInt() != 0) {
13619 u.makeWifiBatchedScanBin(i, null);
13620 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13621 }
13622 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013623 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013624 if (in.readInt() != 0) {
13625 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13626 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013627 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013628 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013629 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013630 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013631 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13632 }
13633 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013634 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13635 }
13636 if (in.readInt() != 0) {
13637 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13638 }
13639 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013640 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13641 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013642 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013643 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13644 }
13645 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013646 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13647 }
13648 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013649 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13650 }
Bookatz956f36bf2017-04-28 09:48:17 -070013651 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013652 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13653 }
13654 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013655 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13656 }
Bookatzb1f04f32017-05-19 13:57:32 -070013657 if (in.readInt() != 0) {
13658 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13659 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013660 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013661 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13662 if (in.readInt() != 0) {
13663 u.makeProcessState(i, null);
13664 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13665 }
13666 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013667 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013668 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013669 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013670
Dianne Hackborn617f8772009-03-31 15:04:46 -070013671 if (in.readInt() != 0) {
13672 if (u.mUserActivityCounters == null) {
13673 u.initUserActivityLocked();
13674 }
13675 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13676 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13677 }
13678 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013679
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013680 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013681 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013682 u.initNetworkActivityLocked();
13683 }
13684 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013685 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13686 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013687 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013688 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13689 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013690 }
13691
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013692 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13693 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13694
Adam Lesinski6832f392015-09-05 18:05:40 -070013695 if (in.readInt() != 0) {
13696 final int numClusters = in.readInt();
13697 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13698 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013699 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013700
Sudheer Shankaaf857412017-07-21 00:14:24 -070013701 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013702 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013703 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013704 final int NSB = in.readInt();
13705 if (mPowerProfile != null &&
13706 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13707 throw new ParcelFormatException("File corrupt: too many speed bins " +
13708 NSB);
13709 }
13710
Sudheer Shankaaf857412017-07-21 00:14:24 -070013711 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070013712 for (int speed = 0; speed < NSB; speed++) {
13713 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013714 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070013715 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013716 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070013717 }
13718 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070013719 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013720 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070013721 }
13722 }
13723 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013724 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013725 }
13726
Sudheer Shanka59f5c002017-05-15 10:57:15 -070013727 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13728 in, mOnBatteryTimeBase);
13729 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13730 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070013731
13732 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
13733 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
13734
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013735 int length = in.readInt();
13736 if (length == Uid.NUM_PROCESS_STATE) {
13737 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
13738 for (int procState = 0; procState < length; ++procState) {
13739 u.mProcStateTimeMs[procState]
13740 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13741 in, mOnBatteryTimeBase);
13742 }
13743 } else {
13744 u.mProcStateTimeMs = null;
13745 }
13746 length = in.readInt();
13747 if (length == Uid.NUM_PROCESS_STATE) {
13748 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
13749 for (int procState = 0; procState < length; ++procState) {
13750 u.mProcStateScreenOffTimeMs[procState]
13751 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13752 in, mOnBatteryScreenOffTimeBase);
13753 }
13754 } else {
13755 u.mProcStateScreenOffTimeMs = null;
13756 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070013757
13758 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070013759 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13760 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
13761 } else {
13762 u.mMobileRadioApWakeupCount = null;
13763 }
13764
13765 if (in.readInt() != 0) {
13766 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13767 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
13768 } else {
13769 u.mWifiRadioApWakeupCount = null;
13770 }
13771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013772 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013773 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013774 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013776 for (int iw = 0; iw < NW; iw++) {
13777 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013778 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013779 }
13780
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013781 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013782 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013783 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013784 }
13785 for (int is = 0; is < NS; is++) {
13786 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013787 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013788 }
13789
13790 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013791 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013792 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013793 }
13794 for (int ij = 0; ij < NJ; ij++) {
13795 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013796 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013797 }
13798
Dianne Hackborn94326cb2017-06-28 16:17:20 -070013799 u.readJobCompletionsFromParcelLocked(in);
13800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013801 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013802 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013803 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013805 for (int is = 0; is < NP; is++) {
13806 int seNumber = in.readInt();
13807 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080013808 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013809 }
13810 }
13811
13812 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013813 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013814 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013816 for (int ip = 0; ip < NP; ip++) {
13817 String procName = in.readString();
13818 Uid.Proc p = u.getProcessStatsLocked(procName);
13819 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013820 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013821 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013822 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013823 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
13824 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013825 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013826 }
13827
13828 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013829 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013830 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013832 for (int ip = 0; ip < NP; ip++) {
13833 String pkgName = in.readString();
13834 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013835 final int NWA = in.readInt();
13836 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013837 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013838 }
13839 p.mWakeupAlarms.clear();
13840 for (int iwa=0; iwa<NWA; iwa++) {
13841 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070013842 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013843 c.readSummaryFromParcelLocked(in);
13844 p.mWakeupAlarms.put(tag, c);
13845 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013846 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013847 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013848 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013850 for (int is = 0; is < NS; is++) {
13851 String servName = in.readString();
13852 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
13853 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013854 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013855 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013856 }
13857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013858 }
13859 }
13860
13861 /**
13862 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
13863 * disk. This format does not allow a lossless round-trip.
13864 *
13865 * @param out the Parcel to be written to.
13866 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013867 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013868 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013869
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013870 // Pull the clock time. This may update the time and make a new history entry
13871 // if we had originally pulled a time before the RTC was set.
13872 long startClockTime = getStartClockTime();
13873
Joe Onoratoabded112016-02-08 16:49:39 -080013874 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
13875 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013876
13877 out.writeInt(VERSION);
13878
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013879 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013881 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013882 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013883 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013884 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013885 out.writeString(mStartPlatformVersion);
13886 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013887 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
13888 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013889 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013890 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070013891 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013892 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013893 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070013894 out.writeInt(mMinLearnedBatteryCapacity);
13895 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080013896 out.writeInt(getLowDischargeAmountSinceCharge());
13897 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013898 out.writeInt(getDischargeAmountScreenOnSinceCharge());
13899 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070013900 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013901 mDischargeStepTracker.writeToParcel(out);
13902 mChargeStepTracker.writeToParcel(out);
13903 mDailyDischargeStepTracker.writeToParcel(out);
13904 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070013905 mDischargeCounter.writeSummaryFromParcelLocked(out);
13906 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070013907 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080013908 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
13909 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013910 if (mDailyPackageChanges != null) {
13911 final int NPKG = mDailyPackageChanges.size();
13912 out.writeInt(NPKG);
13913 for (int i=0; i<NPKG; i++) {
13914 PackageChange pc = mDailyPackageChanges.get(i);
13915 out.writeString(pc.mPackageName);
13916 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070013917 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013918 }
13919 } else {
13920 out.writeInt(0);
13921 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013922 out.writeLong(mDailyStartTime);
13923 out.writeLong(mNextMinDailyDeadline);
13924 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013925
13926 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070013927 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013928 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013929 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013930 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013931 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013932 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013933 out.writeLong(mLongestLightIdleTime);
13934 out.writeLong(mLongestFullIdleTime);
13935 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13936 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13937 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013938 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013939 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080013940 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013941 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013942 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013943 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013944 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013945 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013946 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013947 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013948 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
13949 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013950 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013951 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13952 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013953 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013954 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
13955 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013956 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013957 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13958 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013959 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013960 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013961 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013962 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13963 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13964 }
13965 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13966 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13967 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013968 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13969 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013970 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13971 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13972 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013973 mBluetoothActivity.writeSummaryToParcel(out);
13974 mModemActivity.writeSummaryToParcel(out);
13975 out.writeInt(mHasWifiReporting ? 1 : 0);
13976 out.writeInt(mHasBluetoothReporting ? 1 : 0);
13977 out.writeInt(mHasModemReporting ? 1 : 0);
13978
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013979 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013980 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013981 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013982 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013983
Bookatz50df7112017-08-04 14:53:26 -070013984 out.writeInt(mRpmStats.size());
13985 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
13986 Timer rpmt = ent.getValue();
13987 if (rpmt != null) {
13988 out.writeInt(1);
13989 out.writeString(ent.getKey());
13990 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13991 } else {
13992 out.writeInt(0);
13993 }
13994 }
13995 out.writeInt(mScreenOffRpmStats.size());
13996 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
13997 Timer rpmt = ent.getValue();
13998 if (rpmt != null) {
13999 out.writeInt(1);
14000 out.writeString(ent.getKey());
14001 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14002 } else {
14003 out.writeInt(0);
14004 }
14005 }
14006
Evan Millarc64edde2009-04-18 12:26:32 -070014007 out.writeInt(mKernelWakelockStats.size());
14008 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14009 Timer kwlt = ent.getValue();
14010 if (kwlt != null) {
14011 out.writeInt(1);
14012 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014013 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14014 } else {
14015 out.writeInt(0);
14016 }
14017 }
14018
14019 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014020 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14021 SamplingTimer timer = ent.getValue();
14022 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014023 out.writeInt(1);
14024 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014025 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014026 } else {
14027 out.writeInt(0);
14028 }
14029 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014030
James Carr3a226052016-07-01 14:49:52 -070014031 out.writeInt(mKernelMemoryStats.size());
14032 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14033 Timer kmt = mKernelMemoryStats.valueAt(i);
14034 if (kmt != null) {
14035 out.writeInt(1);
14036 out.writeLong(mKernelMemoryStats.keyAt(i));
14037 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14038 } else {
14039 out.writeInt(0);
14040 }
14041 }
14042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014043 final int NU = mUidStats.size();
14044 out.writeInt(NU);
14045 for (int iu = 0; iu < NU; iu++) {
14046 out.writeInt(mUidStats.keyAt(iu));
14047 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014048
Bookatz867c0d72017-03-07 18:23:42 -080014049 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014050 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014051
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014052 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014053 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014054 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014055 } else {
14056 out.writeInt(0);
14057 }
14058 if (u.mFullWifiLockTimer != null) {
14059 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014060 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014061 } else {
14062 out.writeInt(0);
14063 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014064 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014065 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014066 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014067 } else {
14068 out.writeInt(0);
14069 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014070 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14071 if (u.mWifiBatchedScanTimer[i] != null) {
14072 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014073 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014074 } else {
14075 out.writeInt(0);
14076 }
14077 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014078 if (u.mWifiMulticastTimer != null) {
14079 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014080 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014081 } else {
14082 out.writeInt(0);
14083 }
14084 if (u.mAudioTurnedOnTimer != null) {
14085 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014086 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014087 } else {
14088 out.writeInt(0);
14089 }
14090 if (u.mVideoTurnedOnTimer != null) {
14091 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014092 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014093 } else {
14094 out.writeInt(0);
14095 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014096 if (u.mFlashlightTurnedOnTimer != null) {
14097 out.writeInt(1);
14098 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14099 } else {
14100 out.writeInt(0);
14101 }
14102 if (u.mCameraTurnedOnTimer != null) {
14103 out.writeInt(1);
14104 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14105 } else {
14106 out.writeInt(0);
14107 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014108 if (u.mForegroundActivityTimer != null) {
14109 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014110 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014111 } else {
14112 out.writeInt(0);
14113 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014114 if (u.mForegroundServiceTimer != null) {
14115 out.writeInt(1);
14116 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14117 } else {
14118 out.writeInt(0);
14119 }
Bookatzc8c44962017-05-11 12:12:54 -070014120 if (u.mAggregatedPartialWakelockTimer != null) {
14121 out.writeInt(1);
14122 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14123 } else {
14124 out.writeInt(0);
14125 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014126 if (u.mBluetoothScanTimer != null) {
14127 out.writeInt(1);
14128 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14129 } else {
14130 out.writeInt(0);
14131 }
Bookatzb1f04f32017-05-19 13:57:32 -070014132 if (u.mBluetoothUnoptimizedScanTimer != null) {
14133 out.writeInt(1);
14134 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14135 } else {
14136 out.writeInt(0);
14137 }
Bookatz956f36bf2017-04-28 09:48:17 -070014138 if (u.mBluetoothScanResultCounter != null) {
14139 out.writeInt(1);
14140 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14141 } else {
14142 out.writeInt(0);
14143 }
Bookatzb1f04f32017-05-19 13:57:32 -070014144 if (u.mBluetoothScanResultBgCounter != null) {
14145 out.writeInt(1);
14146 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14147 } else {
14148 out.writeInt(0);
14149 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014150 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14151 if (u.mProcessStateTimer[i] != null) {
14152 out.writeInt(1);
14153 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14154 } else {
14155 out.writeInt(0);
14156 }
14157 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014158 if (u.mVibratorOnTimer != null) {
14159 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014160 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014161 } else {
14162 out.writeInt(0);
14163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014164
Dianne Hackborn617f8772009-03-31 15:04:46 -070014165 if (u.mUserActivityCounters == null) {
14166 out.writeInt(0);
14167 } else {
14168 out.writeInt(1);
14169 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14170 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14171 }
14172 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014173
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014174 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014175 out.writeInt(0);
14176 } else {
14177 out.writeInt(1);
14178 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014179 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14180 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014181 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014182 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14183 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014184 }
14185
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014186 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14187 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14188
Sudheer Shankaaf857412017-07-21 00:14:24 -070014189 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014190 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014191 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14192 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014193 if (cpuSpeeds != null) {
14194 out.writeInt(1);
14195 out.writeInt(cpuSpeeds.length);
14196 for (LongSamplingCounter c : cpuSpeeds) {
14197 if (c != null) {
14198 out.writeInt(1);
14199 c.writeSummaryFromParcelLocked(out);
14200 } else {
14201 out.writeInt(0);
14202 }
14203 }
14204 } else {
14205 out.writeInt(0);
14206 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014207 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014208 } else {
14209 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014210 }
14211
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014212 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14213 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014214
Mike Ma3d422c32017-10-25 11:08:57 -070014215 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14216 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14217
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014218 if (u.mProcStateTimeMs != null) {
14219 out.writeInt(u.mProcStateTimeMs.length);
14220 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14221 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14222 }
14223 } else {
14224 out.writeInt(0);
14225 }
14226 if (u.mProcStateScreenOffTimeMs != null) {
14227 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14228 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14229 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14230 }
14231 } else {
14232 out.writeInt(0);
14233 }
14234
Adam Lesinski5f056f62016-07-14 16:56:08 -070014235 if (u.mMobileRadioApWakeupCount != null) {
14236 out.writeInt(1);
14237 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14238 } else {
14239 out.writeInt(0);
14240 }
14241
14242 if (u.mWifiRadioApWakeupCount != null) {
14243 out.writeInt(1);
14244 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14245 } else {
14246 out.writeInt(0);
14247 }
14248
Dianne Hackbornd953c532014-08-16 18:17:38 -070014249 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14250 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014251 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014252 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014253 out.writeString(wakeStats.keyAt(iw));
14254 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014255 if (wl.mTimerFull != null) {
14256 out.writeInt(1);
14257 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14258 } else {
14259 out.writeInt(0);
14260 }
14261 if (wl.mTimerPartial != null) {
14262 out.writeInt(1);
14263 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14264 } else {
14265 out.writeInt(0);
14266 }
14267 if (wl.mTimerWindow != null) {
14268 out.writeInt(1);
14269 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14270 } else {
14271 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014272 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014273 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014274 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014275 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014276 } else {
14277 out.writeInt(0);
14278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014279 }
14280
Bookatz2bffb5b2017-04-13 11:59:33 -070014281 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014282 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014283 out.writeInt(NS);
14284 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014285 out.writeString(syncStats.keyAt(is));
14286 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014287 }
14288
Bookatzaa4594a2017-03-24 12:39:56 -070014289 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014290 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014291 out.writeInt(NJ);
14292 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014293 out.writeString(jobStats.keyAt(ij));
14294 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014295 }
14296
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014297 u.writeJobCompletionsToParcelLocked(out);
14298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014299 int NSE = u.mSensorStats.size();
14300 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014301 for (int ise=0; ise<NSE; ise++) {
14302 out.writeInt(u.mSensorStats.keyAt(ise));
14303 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14304 if (se.mTimer != null) {
14305 out.writeInt(1);
14306 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14307 } else {
14308 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014309 }
14310 }
14311
14312 int NP = u.mProcessStats.size();
14313 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014314 for (int ip=0; ip<NP; ip++) {
14315 out.writeString(u.mProcessStats.keyAt(ip));
14316 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14317 out.writeLong(ps.mUserTime);
14318 out.writeLong(ps.mSystemTime);
14319 out.writeLong(ps.mForegroundTime);
14320 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014321 out.writeInt(ps.mNumCrashes);
14322 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014323 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014324 }
14325
14326 NP = u.mPackageStats.size();
14327 out.writeInt(NP);
14328 if (NP > 0) {
14329 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14330 : u.mPackageStats.entrySet()) {
14331 out.writeString(ent.getKey());
14332 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014333 final int NWA = ps.mWakeupAlarms.size();
14334 out.writeInt(NWA);
14335 for (int iwa=0; iwa<NWA; iwa++) {
14336 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14337 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14338 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014339 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014340 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014341 for (int is=0; is<NS; is++) {
14342 out.writeString(ps.mServiceStats.keyAt(is));
14343 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14344 long time = ss.getStartTimeToNowLocked(
14345 mOnBatteryTimeBase.getUptime(NOW_SYS));
14346 out.writeLong(time);
14347 out.writeInt(ss.mStarts);
14348 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014349 }
14350 }
14351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014352 }
14353 }
14354
14355 public void readFromParcel(Parcel in) {
14356 readFromParcelLocked(in);
14357 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014359 void readFromParcelLocked(Parcel in) {
14360 int magic = in.readInt();
14361 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014362 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014363 }
14364
Dianne Hackbornae384452011-06-28 12:33:48 -070014365 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014367 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014368 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014369 mStartPlatformVersion = in.readString();
14370 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014371 mUptime = in.readLong();
14372 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014373 mRealtime = in.readLong();
14374 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014375 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014376 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014377 mMinLearnedBatteryCapacity = in.readInt();
14378 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014379 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014380 mOnBatteryTimeBase.readFromParcel(in);
14381 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14382
Jeff Browne95c3cd2014-05-02 16:59:26 -070014383 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014384 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014385 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014386 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014387 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14388 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014389 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014390 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014391 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014392 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014393 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14394 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014395 mLongestLightIdleTime = in.readLong();
14396 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014397 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14398 mOnBatteryTimeBase, in);
14399 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14400 mOnBatteryTimeBase, in);
14401 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14402 mOnBatteryTimeBase, in);
14403 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14404 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014405 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014406 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014407 null, mOnBatteryTimeBase, in);
14408 }
Joe Onoratoabded112016-02-08 16:49:39 -080014409 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14410 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014411 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014412 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014413 null, mOnBatteryTimeBase, in);
14414 }
14415 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14416 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14417 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14418 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014419 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014420 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14421 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014422 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014423 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014424 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014425 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14426 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014427 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14428 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014429 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014430 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014431 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014432 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014433 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14434 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014435 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014436 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014437 null, mOnBatteryTimeBase, in);
14438 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014439 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014440 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014441 null, mOnBatteryTimeBase, in);
14442 }
14443 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014444 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014445 null, mOnBatteryTimeBase, in);
14446 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014447 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14448 mOnBatteryTimeBase, in);
14449 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14450 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014451 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14452 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14453 null, mOnBatteryTimeBase, in);
14454 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014455 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14456 NUM_BT_TX_LEVELS, in);
14457 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14458 ModemActivityInfo.TX_POWER_LEVELS, in);
14459 mHasWifiReporting = in.readInt() != 0;
14460 mHasBluetoothReporting = in.readInt() != 0;
14461 mHasModemReporting = in.readInt() != 0;
14462
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014463 mNumConnectivityChange = in.readInt();
14464 mLoadedNumConnectivityChange = in.readInt();
14465 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014466 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014467 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014468 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014469 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014470 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014471 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014472 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014473 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014474 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014475 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014476 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014477 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014478 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014479 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014480 mLowDischargeAmountSinceCharge = in.readInt();
14481 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014482 mDischargeAmountScreenOn = in.readInt();
14483 mDischargeAmountScreenOnSinceCharge = in.readInt();
14484 mDischargeAmountScreenOff = in.readInt();
14485 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014486 mDischargeAmountScreenDoze = in.readInt();
14487 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014488 mDischargeStepTracker.readFromParcel(in);
14489 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014490 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014491 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14492 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014493 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14494 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014495 mLastWriteTime = in.readLong();
14496
Bookatz50df7112017-08-04 14:53:26 -070014497 mRpmStats.clear();
14498 int NRPMS = in.readInt();
14499 for (int irpm = 0; irpm < NRPMS; irpm++) {
14500 if (in.readInt() != 0) {
14501 String rpmName = in.readString();
14502 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14503 mRpmStats.put(rpmName, rpmt);
14504 }
14505 }
14506 mScreenOffRpmStats.clear();
14507 int NSORPMS = in.readInt();
14508 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14509 if (in.readInt() != 0) {
14510 String rpmName = in.readString();
14511 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14512 mScreenOffRpmStats.put(rpmName, rpmt);
14513 }
14514 }
14515
Evan Millarc64edde2009-04-18 12:26:32 -070014516 mKernelWakelockStats.clear();
14517 int NKW = in.readInt();
14518 for (int ikw = 0; ikw < NKW; ikw++) {
14519 if (in.readInt() != 0) {
14520 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014521 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014522 mKernelWakelockStats.put(wakelockName, kwlt);
14523 }
14524 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014525
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014526 mWakeupReasonStats.clear();
14527 int NWR = in.readInt();
14528 for (int iwr = 0; iwr < NWR; iwr++) {
14529 if (in.readInt() != 0) {
14530 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014531 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014532 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014533 }
14534 }
14535
James Carr3a226052016-07-01 14:49:52 -070014536 mKernelMemoryStats.clear();
14537 int nmt = in.readInt();
14538 for (int imt = 0; imt < nmt; imt++) {
14539 if (in.readInt() != 0) {
14540 Long bucket = in.readLong();
14541 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14542 mKernelMemoryStats.put(bucket, kmt);
14543 }
14544 }
14545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014546 mPartialTimers.clear();
14547 mFullTimers.clear();
14548 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014549 mWifiRunningTimers.clear();
14550 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014551 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014552 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014553 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014554 mAudioTurnedOnTimers.clear();
14555 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014556 mFlashlightTurnedOnTimers.clear();
14557 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014558
14559 int numUids = in.readInt();
14560 mUidStats.clear();
14561 for (int i = 0; i < numUids; i++) {
14562 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014563 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014564 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014565 mUidStats.append(uid, u);
14566 }
14567 }
14568
14569 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014570 writeToParcelLocked(out, true, flags);
14571 }
14572
14573 public void writeToParcelWithoutUids(Parcel out, int flags) {
14574 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014575 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014576
14577 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014578 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014579 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014580 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014581
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014582 // Pull the clock time. This may update the time and make a new history entry
14583 // if we had originally pulled a time before the RTC was set.
14584 long startClockTime = getStartClockTime();
14585
Joe Onoratoabded112016-02-08 16:49:39 -080014586 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14587 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014588 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14589 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014591 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014592
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014593 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014595 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014596 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014597 out.writeString(mStartPlatformVersion);
14598 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014599 out.writeLong(mUptime);
14600 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014601 out.writeLong(mRealtime);
14602 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014603 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014604 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014605 out.writeInt(mMinLearnedBatteryCapacity);
14606 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014607 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14608 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14609
14610 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014611 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014612 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14613 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14614 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014615 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014616 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014617 out.writeLong(mLongestLightIdleTime);
14618 out.writeLong(mLongestFullIdleTime);
14619 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14620 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14621 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014622 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014623 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14624 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14625 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14626 }
14627 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14628 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14629 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14630 }
14631 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14632 mNetworkByteActivityCounters[i].writeToParcel(out);
14633 mNetworkPacketActivityCounters[i].writeToParcel(out);
14634 }
14635 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14636 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014637 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014638 mMobileRadioActiveUnknownTime.writeToParcel(out);
14639 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014640 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014641 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14642 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14643 for (int i=0; i<NUM_WIFI_STATES; i++) {
14644 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14645 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014646 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14647 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14648 }
14649 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14650 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14651 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014652 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
14653 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014654 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14655 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
14656 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014657 mBluetoothActivity.writeToParcel(out, 0);
14658 mModemActivity.writeToParcel(out, 0);
14659 out.writeInt(mHasWifiReporting ? 1 : 0);
14660 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14661 out.writeInt(mHasModemReporting ? 1 : 0);
14662
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014663 out.writeInt(mNumConnectivityChange);
14664 out.writeInt(mLoadedNumConnectivityChange);
14665 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014666 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014667 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014668 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014669 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014670 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014671 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014672 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014673 out.writeInt(mLowDischargeAmountSinceCharge);
14674 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014675 out.writeInt(mDischargeAmountScreenOn);
14676 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14677 out.writeInt(mDischargeAmountScreenOff);
14678 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014679 out.writeInt(mDischargeAmountScreenDoze);
14680 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014681 mDischargeStepTracker.writeToParcel(out);
14682 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014683 mDischargeCounter.writeToParcel(out);
14684 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014685 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080014686 mDischargeLightDozeCounter.writeToParcel(out);
14687 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014688 out.writeLong(mLastWriteTime);
14689
Bookatz50df7112017-08-04 14:53:26 -070014690 out.writeInt(mRpmStats.size());
14691 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14692 SamplingTimer rpmt = ent.getValue();
14693 if (rpmt != null) {
14694 out.writeInt(1);
14695 out.writeString(ent.getKey());
14696 rpmt.writeToParcel(out, uSecRealtime);
14697 } else {
14698 out.writeInt(0);
14699 }
14700 }
14701 out.writeInt(mScreenOffRpmStats.size());
14702 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14703 SamplingTimer rpmt = ent.getValue();
14704 if (rpmt != null) {
14705 out.writeInt(1);
14706 out.writeString(ent.getKey());
14707 rpmt.writeToParcel(out, uSecRealtime);
14708 } else {
14709 out.writeInt(0);
14710 }
14711 }
14712
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014713 if (inclUids) {
14714 out.writeInt(mKernelWakelockStats.size());
14715 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14716 SamplingTimer kwlt = ent.getValue();
14717 if (kwlt != null) {
14718 out.writeInt(1);
14719 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014720 kwlt.writeToParcel(out, uSecRealtime);
14721 } else {
14722 out.writeInt(0);
14723 }
14724 }
14725 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014726 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14727 SamplingTimer timer = ent.getValue();
14728 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014729 out.writeInt(1);
14730 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014731 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014732 } else {
14733 out.writeInt(0);
14734 }
Evan Millarc64edde2009-04-18 12:26:32 -070014735 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014736 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070014737 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014738 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070014739 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070014740
James Carr3a226052016-07-01 14:49:52 -070014741 out.writeInt(mKernelMemoryStats.size());
14742 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14743 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
14744 if (kmt != null) {
14745 out.writeInt(1);
14746 out.writeLong(mKernelMemoryStats.keyAt(i));
14747 kmt.writeToParcel(out, uSecRealtime);
14748 } else {
14749 out.writeInt(0);
14750 }
14751 }
14752
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014753 if (inclUids) {
14754 int size = mUidStats.size();
14755 out.writeInt(size);
14756 for (int i = 0; i < size; i++) {
14757 out.writeInt(mUidStats.keyAt(i));
14758 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014759
Bookatz867c0d72017-03-07 18:23:42 -080014760 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014761 }
14762 } else {
14763 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014764 }
14765 }
14766
14767 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
14768 new Parcelable.Creator<BatteryStatsImpl>() {
14769 public BatteryStatsImpl createFromParcel(Parcel in) {
14770 return new BatteryStatsImpl(in);
14771 }
14772
14773 public BatteryStatsImpl[] newArray(int size) {
14774 return new BatteryStatsImpl[size];
14775 }
14776 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014777
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014778 public void prepareForDumpLocked() {
14779 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014780 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014781
14782 // Pull the clock time. This may update the time and make a new history entry
14783 // if we had originally pulled a time before the RTC was set.
14784 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014785 }
14786
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014787 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014788 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014789 pw.println("mOnBatteryTimeBase:");
14790 mOnBatteryTimeBase.dump(pw, " ");
14791 pw.println("mOnBatteryScreenOffTimeBase:");
14792 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014793 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070014794 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014795 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070014796 pr.println("*** Screen doze timer:");
14797 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014798 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014799 pr.println("*** Screen brightness #" + i + ":");
14800 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014801 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014802 pr.println("*** Interactive timer:");
14803 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014804 pr.println("*** Power save mode timer:");
14805 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014806 pr.println("*** Device idle mode light timer:");
14807 mDeviceIdleModeLightTimer.logState(pr, " ");
14808 pr.println("*** Device idle mode full timer:");
14809 mDeviceIdleModeFullTimer.logState(pr, " ");
14810 pr.println("*** Device light idling timer:");
14811 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014812 pr.println("*** Device idling timer:");
14813 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014814 pr.println("*** Phone timer:");
14815 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080014816 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070014817 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014818 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014819 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070014820 pr.println("*** Signal scanning :");
14821 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014822 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014823 pr.println("*** Data connection type #" + i + ":");
14824 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014825 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014826 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080014827 pr.println("*** Mobile network active timer:");
14828 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014829 pr.println("*** Mobile network active adjusted timer:");
14830 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014831 pr.println("*** Wifi Multicast WakeLock Timer:");
14832 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014833 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014834 pr.println("*** Wifi timer:");
14835 mWifiOnTimer.logState(pr, " ");
14836 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014837 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014838 for (int i=0; i<NUM_WIFI_STATES; i++) {
14839 pr.println("*** Wifi state #" + i + ":");
14840 mWifiStateTimer[i].logState(pr, " ");
14841 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014842 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14843 pr.println("*** Wifi suppl state #" + i + ":");
14844 mWifiSupplStateTimer[i].logState(pr, " ");
14845 }
14846 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14847 pr.println("*** Wifi signal strength #" + i + ":");
14848 mWifiSignalStrengthsTimer[i].logState(pr, " ");
14849 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014850 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14851 pr.println("*** GPS signal quality #" + i + ":");
14852 mGpsSignalQualityTimer[i].logState(pr, " ");
14853 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014854 pr.println("*** Flashlight timer:");
14855 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014856 pr.println("*** Camera timer:");
14857 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014858 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014859 super.dumpLocked(context, pw, flags, reqUid, histStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014861}