blob: 467e2a43d3e7f8c75703e8355f38d9b2c9b49972 [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;
Narayan Kamathefa0fe62018-02-05 16:04:43 +0000681 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
682 protected final StopwatchTimer[] mGpsSignalQualityTimer =
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800683 new StopwatchTimer[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
684
Dianne Hackborn627bba72009-03-24 22:32:56 -0700685 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800686 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700687 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800688 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700689
690 StopwatchTimer mPhoneSignalScanningTimer;
691
Dianne Hackborn627bba72009-03-24 22:32:56 -0700692 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700693 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700694 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700695
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800696 final LongSamplingCounter[] mNetworkByteActivityCounters =
697 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
698 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700699 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
700
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800701 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800702 * The WiFi Overall wakelock timer
703 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
704 * since addition of per UID timers would not result in an accurate value due to overlapp of
705 * per uid wakelock timers
706 */
707 StopwatchTimer mWifiMulticastWakelockTimer;
708
709 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800710 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
711 */
712 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700713
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800714 /**
715 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
716 */
717 ControllerActivityCounterImpl mBluetoothActivity;
718
719 /**
720 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
721 */
722 ControllerActivityCounterImpl mModemActivity;
723
724 /**
725 * Whether the device supports WiFi controller energy reporting. This is set to true on
726 * the first WiFi energy report. See {@link #mWifiActivity}.
727 */
728 boolean mHasWifiReporting = false;
729
730 /**
731 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
732 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
733 */
734 boolean mHasBluetoothReporting = false;
735
736 /**
737 * Whether the device supports Modem controller energy reporting. This is set to true on
738 * the first Modem energy report. See {@link #mModemActivity}.
739 */
740 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700741
The Android Open Source Project10592532009-03-18 17:39:46 -0700742 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700743 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700744
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700745 boolean mGlobalWifiRunning;
746 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700747
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800748 int mWifiState = -1;
749 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
750
Dianne Hackborn3251b902014-06-20 14:40:53 -0700751 int mWifiSupplState = -1;
752 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
753
754 int mWifiSignalStrengthBin = -1;
755 final StopwatchTimer[] mWifiSignalStrengthsTimer =
756 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
757
Siddharth Rayb50a6842017-12-14 15:15:28 -0800758 StopwatchTimer mWifiActiveTimer;
759
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800760 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800761 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
762 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800763
Siddharth Rayf5e796a2018-01-22 18:18:17 -0800764 boolean mIsCellularTxPowerHigh = false;
765
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700766 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700767 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800768 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800769 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700770 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800771 LongSamplingCounter mMobileRadioActiveUnknownTime;
772 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800773
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700774 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 /**
777 * These provide time bases that discount the time the device is plugged
778 * in to power.
779 */
780 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700781 @VisibleForTesting
782 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700783
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700784 /**
785 * External reporting of whether the device is actually charging.
786 */
787 boolean mCharging = true;
788 int mLastChargingStateLevel;
789
The Android Open Source Project10592532009-03-18 17:39:46 -0700790 /*
791 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
792 */
Evan Millar633a1742009-04-02 16:36:33 -0700793 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700794 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700795 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700796 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700797 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700798 int mLowDischargeAmountSinceCharge;
799 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800800 int mDischargeScreenOnUnplugLevel;
801 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700802 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800803 int mDischargeAmountScreenOn;
804 int mDischargeAmountScreenOnSinceCharge;
805 int mDischargeAmountScreenOff;
806 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700807 int mDischargeAmountScreenDoze;
808 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700809
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700810 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700811 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700812 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800813 private LongSamplingCounter mDischargeLightDozeCounter;
814 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700815
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700816 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700817
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700818 int mInitStepMode = 0;
819 int mCurStepMode = 0;
820 int mModStepMode = 0;
821
Dianne Hackborn260c5022014-04-29 11:23:16 -0700822 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700823 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800824 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
825 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700826 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700827
828 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700829 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800830 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
831 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
832
833 static final int MAX_DAILY_ITEMS = 10;
834
835 long mDailyStartTime = 0;
836 long mNextMinDailyDeadline = 0;
837 long mNextMaxDailyDeadline = 0;
838
839 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700842
Amith Yamasanif37447b2009-10-08 18:28:01 -0700843 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800844 private int mPhoneServiceStateRaw = -1;
845 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700846
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800847 private int mNumConnectivityChange;
848 private int mLoadedNumConnectivityChange;
849 private int mUnpluggedNumConnectivityChange;
850
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700851 private int mEstimatedBatteryCapacity = -1;
852
Jocelyn Dangc627d102017-04-14 13:15:14 -0700853 private int mMinLearnedBatteryCapacity = -1;
854 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800855
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700856 private long[] mCpuFreqs;
857
Sudheer Shanka38383232017-07-25 09:55:03 -0700858 @VisibleForTesting
859 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700860
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800861 @GuardedBy("this")
862 private final Constants mConstants;
863
Evan Millarc64edde2009-04-18 12:26:32 -0700864 /*
Bookatz50df7112017-08-04 14:53:26 -0700865 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
866 * recording their times when on-battery (regardless of screen state).
867 */
868 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
869 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
870 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
871
872 @Override
873 public Map<String, ? extends Timer> getRpmStats() {
874 return mRpmStats;
875 }
876
Bookatz82b341172017-09-07 19:06:08 -0700877 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700878 @Override
879 public Map<String, ? extends Timer> getScreenOffRpmStats() {
880 return mScreenOffRpmStats;
881 }
882
883 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700884 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
885 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700886 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700887
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700888 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700889 return mKernelWakelockStats;
890 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700891
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700892 String mLastWakeupReason = null;
893 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700894 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700895
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700896 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700897 return mWakeupReasonStats;
898 }
899
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700900 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700901 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700902 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700903 }
904
905 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700906 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700907 return mDischargeScreenOffCounter.getCountLocked(which);
908 }
909
910 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700911 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700912 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700913 }
914
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700915 @Override
Mike Ma15313c92017-11-15 17:58:21 -0800916 public long getUahDischargeLightDoze(int which) {
917 return mDischargeLightDozeCounter.getCountLocked(which);
918 }
919
920 @Override
921 public long getUahDischargeDeepDoze(int which) {
922 return mDischargeDeepDozeCounter.getCountLocked(which);
923 }
924
925 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700926 public int getEstimatedBatteryCapacity() {
927 return mEstimatedBatteryCapacity;
928 }
929
Jocelyn Dangc627d102017-04-14 13:15:14 -0700930 @Override
931 public int getMinLearnedBatteryCapacity() {
932 return mMinLearnedBatteryCapacity;
933 }
934
935 @Override
936 public int getMaxLearnedBatteryCapacity() {
937 return mMaxLearnedBatteryCapacity;
938 }
939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -0800941 this(new SystemClocks());
942 }
943
944 public BatteryStatsImpl(Clocks clocks) {
945 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700946 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700947 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800948 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700949 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700950 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700951 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800952 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700953 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
955
Joe Onoratoabded112016-02-08 16:49:39 -0800956 private void init(Clocks clocks) {
957 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -0800958 }
959
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700960 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800961 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
962 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
963 }
964
Joe Onoratoabded112016-02-08 16:49:39 -0800965 // methods are protected not private to be VisibleForTesting
966 public static class TimeBase {
967 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800968
Joe Onoratoabded112016-02-08 16:49:39 -0800969 protected long mUptime;
970 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800971
Joe Onoratoabded112016-02-08 16:49:39 -0800972 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800973
Joe Onoratoabded112016-02-08 16:49:39 -0800974 protected long mPastUptime;
975 protected long mUptimeStart;
976 protected long mPastRealtime;
977 protected long mRealtimeStart;
978 protected long mUnpluggedUptime;
979 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800980
981 public void dump(PrintWriter pw, String prefix) {
982 StringBuilder sb = new StringBuilder(128);
983 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
984 sb.setLength(0);
985 sb.append(prefix);
986 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700987 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800988 pw.println(sb.toString());
989 sb.setLength(0);
990 sb.append(prefix);
991 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700992 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800993 pw.println(sb.toString());
994 sb.setLength(0);
995 sb.append(prefix);
996 sb.append("mPastUptime=");
997 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
998 formatTimeMs(sb, mUptimeStart / 1000);
999 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
1000 pw.println(sb.toString());
1001 sb.setLength(0);
1002 sb.append(prefix);
1003 sb.append("mPastRealtime=");
1004 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
1005 formatTimeMs(sb, mRealtimeStart / 1000);
1006 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
1007 pw.println(sb.toString());
1008 }
1009
1010 public void add(TimeBaseObs observer) {
1011 mObservers.add(observer);
1012 }
1013
1014 public void remove(TimeBaseObs observer) {
1015 if (!mObservers.remove(observer)) {
1016 Slog.wtf(TAG, "Removed unknown observer: " + observer);
1017 }
1018 }
1019
Joe Onoratoabded112016-02-08 16:49:39 -08001020 public boolean hasObserver(TimeBaseObs observer) {
1021 return mObservers.contains(observer);
1022 }
1023
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001024 public void init(long uptime, long realtime) {
1025 mRealtime = 0;
1026 mUptime = 0;
1027 mPastUptime = 0;
1028 mPastRealtime = 0;
1029 mUptimeStart = uptime;
1030 mRealtimeStart = realtime;
1031 mUnpluggedUptime = getUptime(mUptimeStart);
1032 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1033 }
1034
1035 public void reset(long uptime, long realtime) {
1036 if (!mRunning) {
1037 mPastUptime = 0;
1038 mPastRealtime = 0;
1039 } else {
1040 mUptimeStart = uptime;
1041 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001042 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1043 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001044 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001045 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001046 mUnpluggedRealtime = getRealtime(realtime);
1047 }
1048 }
1049
1050 public long computeUptime(long curTime, int which) {
1051 switch (which) {
1052 case STATS_SINCE_CHARGED:
1053 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001054 case STATS_CURRENT:
1055 return getUptime(curTime);
1056 case STATS_SINCE_UNPLUGGED:
1057 return getUptime(curTime) - mUnpluggedUptime;
1058 }
1059 return 0;
1060 }
1061
1062 public long computeRealtime(long curTime, int which) {
1063 switch (which) {
1064 case STATS_SINCE_CHARGED:
1065 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001066 case STATS_CURRENT:
1067 return getRealtime(curTime);
1068 case STATS_SINCE_UNPLUGGED:
1069 return getRealtime(curTime) - mUnpluggedRealtime;
1070 }
1071 return 0;
1072 }
1073
1074 public long getUptime(long curTime) {
1075 long time = mPastUptime;
1076 if (mRunning) {
1077 time += curTime - mUptimeStart;
1078 }
1079 return time;
1080 }
1081
1082 public long getRealtime(long curTime) {
1083 long time = mPastRealtime;
1084 if (mRunning) {
1085 time += curTime - mRealtimeStart;
1086 }
1087 return time;
1088 }
1089
1090 public long getUptimeStart() {
1091 return mUptimeStart;
1092 }
1093
1094 public long getRealtimeStart() {
1095 return mRealtimeStart;
1096 }
1097
1098 public boolean isRunning() {
1099 return mRunning;
1100 }
1101
1102 public boolean setRunning(boolean running, long uptime, long realtime) {
1103 if (mRunning != running) {
1104 mRunning = running;
1105 if (running) {
1106 mUptimeStart = uptime;
1107 mRealtimeStart = realtime;
1108 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1109 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
1110
1111 for (int i = mObservers.size() - 1; i >= 0; i--) {
1112 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
1113 }
1114 } else {
1115 mPastUptime += uptime - mUptimeStart;
1116 mPastRealtime += realtime - mRealtimeStart;
1117
1118 long batteryUptime = getUptime(uptime);
1119 long batteryRealtime = getRealtime(realtime);
1120
1121 for (int i = mObservers.size() - 1; i >= 0; i--) {
1122 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
1123 }
1124 }
1125 return true;
1126 }
1127 return false;
1128 }
1129
1130 public void readSummaryFromParcel(Parcel in) {
1131 mUptime = in.readLong();
1132 mRealtime = in.readLong();
1133 }
1134
1135 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1136 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1137 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1138 }
1139
1140 public void readFromParcel(Parcel in) {
1141 mRunning = false;
1142 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001143 mPastUptime = in.readLong();
1144 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001145 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001146 mPastRealtime = in.readLong();
1147 mRealtimeStart = in.readLong();
1148 mUnpluggedUptime = in.readLong();
1149 mUnpluggedRealtime = in.readLong();
1150 }
1151
1152 public void writeToParcel(Parcel out, long uptime, long realtime) {
1153 final long runningUptime = getUptime(uptime);
1154 final long runningRealtime = getRealtime(realtime);
1155 out.writeLong(mUptime);
1156 out.writeLong(runningUptime);
1157 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001158 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001159 out.writeLong(runningRealtime);
1160 out.writeLong(mRealtimeStart);
1161 out.writeLong(mUnpluggedUptime);
1162 out.writeLong(mUnpluggedRealtime);
1163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001167 * State for keeping track of counting information.
1168 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001169 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -07001170 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001171 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001172 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001173 int mUnpluggedCount;
1174 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001175
Bookatz8c6f3c52017-05-24 12:00:17 -07001176 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001177 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -07001178 mPluggedCount = in.readInt();
1179 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001180 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001181 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001182 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001183 }
1184
Bookatz8c6f3c52017-05-24 12:00:17 -07001185 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001186 mTimeBase = timeBase;
1187 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001188 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001189
Dianne Hackborn617f8772009-03-31 15:04:46 -07001190 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001191 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001192 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001193 out.writeInt(mUnpluggedCount);
1194 }
1195
Bookatz8c6f3c52017-05-24 12:00:17 -07001196 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001197 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001198 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001199 }
1200
Bookatz8c6f3c52017-05-24 12:00:17 -07001201 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001202 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001203 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001204 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001205
Dianne Hackborn617f8772009-03-31 15:04:46 -07001206 /**
1207 * Writes a possibly null Counter to a Parcel.
1208 *
1209 * @param out the Parcel to be written to.
1210 * @param counter a Counter, or null.
1211 */
1212 public static void writeCounterToParcel(Parcel out, Counter counter) {
1213 if (counter == null) {
1214 out.writeInt(0); // indicates null
1215 return;
1216 }
1217 out.writeInt(1); // indicates non-null
1218
1219 counter.writeToParcel(out);
1220 }
1221
1222 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001223 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001224 int val = mCount.get();
1225 if (which == STATS_SINCE_UNPLUGGED) {
1226 val -= mUnpluggedCount;
1227 } else if (which != STATS_SINCE_CHARGED) {
1228 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001229 }
1230
1231 return val;
1232 }
1233
1234 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001235 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001236 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001237 + " mUnpluggedCount=" + mUnpluggedCount
1238 + " mPluggedCount=" + mPluggedCount);
1239 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001240
Bookatz8c6f3c52017-05-24 12:00:17 -07001241 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1242 public void stepAtomic() {
1243 if (mTimeBase.isRunning()) {
1244 mCount.incrementAndGet();
1245 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001246 }
1247
Bookatz4ebc0642017-05-11 12:21:19 -07001248 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001249 if (mTimeBase.isRunning()) {
1250 mCount.addAndGet(delta);
1251 }
Bookatz4ebc0642017-05-11 12:21:19 -07001252 }
1253
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001254 /**
1255 * Clear state of this counter.
1256 */
1257 void reset(boolean detachIfReset) {
1258 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001259 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001260 if (detachIfReset) {
1261 detach();
1262 }
1263 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001264
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001265 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001266 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001267 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001268
Bookatz8c6f3c52017-05-24 12:00:17 -07001269 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1270 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001271 int count = mCount.get();
1272 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001273 }
1274
Bookatz8c6f3c52017-05-24 12:00:17 -07001275 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1276 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001277 mLoadedCount = in.readInt();
1278 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001279 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001280 }
1281 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001282
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001283 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001284 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1285 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001286 public long[] mCounts;
1287 public long[] mLoadedCounts;
1288 public long[] mUnpluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001289
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001290 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001291 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001292 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001293 mLoadedCounts = in.createLongArray();
1294 mUnpluggedCounts = in.createLongArray();
1295 timeBase.add(this);
1296 }
1297
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001298 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001299 mTimeBase = timeBase;
1300 timeBase.add(this);
1301 }
1302
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001303 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001304 out.writeLongArray(mCounts);
1305 out.writeLongArray(mLoadedCounts);
1306 out.writeLongArray(mUnpluggedCounts);
1307 }
1308
1309 @Override
1310 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001311 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001312 }
1313
1314 @Override
1315 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001316 }
1317
1318 @Override
1319 public long[] getCountsLocked(int which) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001320 long[] val = copyArray(mCounts, null);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001321 if (which == STATS_SINCE_UNPLUGGED) {
1322 subtract(val, mUnpluggedCounts);
1323 } else if (which != STATS_SINCE_CHARGED) {
1324 subtract(val, mLoadedCounts);
1325 }
1326 return val;
1327 }
1328
1329 @Override
1330 public void logState(Printer pw, String prefix) {
1331 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1332 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
Sudheer Shankae544d162017-12-28 17:06:20 -08001333 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001334 }
1335
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001336 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001337 addCountLocked(counts, mTimeBase.isRunning());
1338 }
1339
1340 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001341 if (counts == null) {
1342 return;
1343 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001344 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001345 if (mCounts == null) {
1346 mCounts = new long[counts.length];
1347 }
1348 for (int i = 0; i < counts.length; ++i) {
1349 mCounts[i] += counts[i];
1350 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001351 }
1352 }
1353
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001354 public int getSize() {
1355 return mCounts == null ? 0 : mCounts.length;
1356 }
1357
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001358 /**
1359 * Clear state of this counter.
1360 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001361 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001362 fillArray(mCounts, 0);
1363 fillArray(mLoadedCounts, 0);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001364 fillArray(mUnpluggedCounts, 0);
1365 if (detachIfReset) {
1366 detach();
1367 }
1368 }
1369
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001370 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001371 mTimeBase.remove(this);
1372 }
1373
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001374 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001375 out.writeLongArray(mCounts);
1376 }
1377
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001378 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001379 mCounts = in.createLongArray();
1380 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1381 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001382 }
1383
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001384 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1385 if (counterArray != null) {
1386 out.writeInt(1);
1387 counterArray.writeToParcel(out);
1388 } else {
1389 out.writeInt(0);
1390 }
1391 }
1392
1393 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1394 if (in.readInt() != 0) {
1395 return new LongSamplingCounterArray(timeBase, in);
1396 } else {
1397 return null;
1398 }
1399 }
1400
1401 public static void writeSummaryToParcelLocked(Parcel out,
1402 LongSamplingCounterArray counterArray) {
1403 if (counterArray != null) {
1404 out.writeInt(1);
1405 counterArray.writeSummaryToParcelLocked(out);
1406 } else {
1407 out.writeInt(0);
1408 }
1409 }
1410
1411 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1412 TimeBase timeBase) {
1413 if (in.readInt() != 0) {
1414 final LongSamplingCounterArray counterArray
1415 = new LongSamplingCounterArray(timeBase);
1416 counterArray.readSummaryFromParcelLocked(in);
1417 return counterArray;
1418 } else {
1419 return null;
1420 }
1421 }
1422
Bookatz8c6f3c52017-05-24 12:00:17 -07001423 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001424 if (a != null) {
1425 Arrays.fill(a, val);
1426 }
1427 }
1428
Bookatz8c6f3c52017-05-24 12:00:17 -07001429 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001430 if (toSubtract == null) {
1431 return;
1432 }
1433 for (int i = 0; i < val.length; i++) {
1434 val[i] -= toSubtract[i];
1435 }
1436 }
1437
Bookatz8c6f3c52017-05-24 12:00:17 -07001438 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001439 if (src == null) {
1440 return null;
1441 } else {
1442 if (dest == null) {
1443 dest = new long[src.length];
1444 }
1445 System.arraycopy(src, 0, dest, 0, src.length);
1446 return dest;
1447 }
1448 }
1449 }
1450
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001451 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001452 final TimeBase mTimeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001453 long mCount;
1454 long mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001455 long mUnpluggedCount;
1456 long mPluggedCount;
1457
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001458 LongSamplingCounter(TimeBase timeBase, Parcel in) {
1459 mTimeBase = timeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001460 mPluggedCount = in.readLong();
1461 mCount = mPluggedCount;
1462 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001463 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001464 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001465 }
1466
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001467 LongSamplingCounter(TimeBase timeBase) {
1468 mTimeBase = timeBase;
1469 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001470 }
1471
1472 public void writeToParcel(Parcel out) {
1473 out.writeLong(mCount);
1474 out.writeLong(mLoadedCount);
1475 out.writeLong(mUnpluggedCount);
1476 }
1477
1478 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001479 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001480 mUnpluggedCount = mPluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001481 }
1482
1483 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001484 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001485 mPluggedCount = mCount;
1486 }
1487
1488 public long getCountLocked(int which) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001489 long val = mTimeBase.isRunning() ? mCount : mPluggedCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001490 if (which == STATS_SINCE_UNPLUGGED) {
1491 val -= mUnpluggedCount;
1492 } else if (which != STATS_SINCE_CHARGED) {
1493 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001494 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001495 return val;
1496 }
1497
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001498 @Override
1499 public void logState(Printer pw, String prefix) {
1500 pw.println(prefix + "mCount=" + mCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001501 + " mLoadedCount=" + mLoadedCount
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001502 + " mUnpluggedCount=" + mUnpluggedCount
1503 + " mPluggedCount=" + mPluggedCount);
1504 }
1505
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001506 void addCountLocked(long count) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001507 if (mTimeBase.isRunning()) {
1508 mCount += count;
1509 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001510 }
1511
1512 /**
1513 * Clear state of this counter.
1514 */
1515 void reset(boolean detachIfReset) {
1516 mCount = 0;
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001517 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001518 if (detachIfReset) {
1519 detach();
1520 }
1521 }
1522
1523 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001524 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001525 }
1526
1527 void writeSummaryFromParcelLocked(Parcel out) {
1528 out.writeLong(mCount);
1529 }
1530
1531 void readSummaryFromParcelLocked(Parcel in) {
1532 mLoadedCount = in.readLong();
1533 mCount = mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001534 mUnpluggedCount = mPluggedCount = mLoadedCount;
1535 }
1536 }
1537
Dianne Hackborn617f8772009-03-31 15:04:46 -07001538 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 * State for keeping track of timing information.
1540 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001541 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001542 protected final Clocks mClocks;
1543 protected final int mType;
1544 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001545
Joe Onoratoabded112016-02-08 16:49:39 -08001546 protected int mCount;
1547 protected int mLoadedCount;
1548 protected int mLastCount;
1549 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 // Times are in microseconds for better accuracy when dividing by the
1552 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 /**
1555 * The total time we have accumulated since the start of the original
1556 * boot, to the last time something interesting happened in the
1557 * current run.
1558 */
Joe Onoratoabded112016-02-08 16:49:39 -08001559 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 /**
1562 * The total time we loaded for the previous runs. Subtract this from
1563 * mTotalTime to find the time for the current run of the system.
1564 */
Joe Onoratoabded112016-02-08 16:49:39 -08001565 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 /**
1568 * The run time of the last run of the system, as loaded from the
1569 * saved data.
1570 */
Joe Onoratoabded112016-02-08 16:49:39 -08001571 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 /**
1574 * The value of mTotalTime when unplug() was last called. Subtract
1575 * this from mTotalTime to find the time since the last unplug from
1576 * power.
1577 */
Joe Onoratoabded112016-02-08 16:49:39 -08001578 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001579
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001580 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001581 * The total time this timer has been running until the latest mark has been set.
1582 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1583 */
Joe Onoratoabded112016-02-08 16:49:39 -08001584 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001585
1586 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001587 * Constructs from a parcel.
1588 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001589 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001590 * @param in
1591 */
Joe Onoratoabded112016-02-08 16:49:39 -08001592 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1593 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001595 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 mCount = in.readInt();
1598 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001599 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 mUnpluggedCount = in.readInt();
1601 mTotalTime = in.readLong();
1602 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001603 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001605 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001606 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001607 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 }
1609
Joe Onoratoabded112016-02-08 16:49:39 -08001610 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1611 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001613 mTimeBase = timeBase;
1614 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 }
Evan Millarc64edde2009-04-18 12:26:32 -07001616
1617 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001618
Evan Millarc64edde2009-04-18 12:26:32 -07001619 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001620
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001621 /**
1622 * Clear state of this timer. Returns true if the timer is inactive
1623 * so can be completely dropped.
1624 */
Joe Onoratoabded112016-02-08 16:49:39 -08001625 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001626 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001627 mCount = mLoadedCount = mLastCount = 0;
1628 if (detachIfReset) {
1629 detach();
1630 }
1631 return true;
1632 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001633
Joe Onoratoabded112016-02-08 16:49:39 -08001634 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001635 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001636 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001637
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001638 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001639 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1640 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001641 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001644 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001647 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649
Adam Lesinskie08af192015-03-25 16:42:59 -07001650 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001651 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001653 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 + " old mUnpluggedTime=" + mUnpluggedTime
1655 + " old mUnpluggedCount=" + mUnpluggedCount);
1656 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001657 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001658 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 if (DEBUG && mType < 0) {
1660 Log.v(TAG, "unplug #" + mType
1661 + ": new mUnpluggedTime=" + mUnpluggedTime
1662 + " new mUnpluggedCount=" + mUnpluggedCount);
1663 }
1664 }
1665
Adam Lesinskie08af192015-03-25 16:42:59 -07001666 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001667 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001668 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001669 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001670 + " old mTotalTime=" + mTotalTime);
1671 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001672 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001673 mCount = computeCurrentCountLocked();
1674 if (DEBUG && mType < 0) {
1675 Log.v(TAG, "plug #" + mType
1676 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
1678 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 /**
1681 * Writes a possibly null Timer to a Parcel.
1682 *
1683 * @param out the Parcel to be written to.
1684 * @param timer a Timer, or null.
1685 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001686 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 if (timer == null) {
1688 out.writeInt(0); // indicates null
1689 return;
1690 }
1691 out.writeInt(1); // indicates non-null
1692
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001693 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695
1696 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001697 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001698 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1699 if (which == STATS_SINCE_UNPLUGGED) {
1700 val -= mUnpluggedTime;
1701 } else if (which != STATS_SINCE_CHARGED) {
1702 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 }
1704
1705 return val;
1706 }
1707
1708 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001709 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001710 int val = computeCurrentCountLocked();
1711 if (which == STATS_SINCE_UNPLUGGED) {
1712 val -= mUnpluggedCount;
1713 } else if (which != STATS_SINCE_CHARGED) {
1714 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 }
1716
1717 return val;
1718 }
1719
Adam Lesinskie08af192015-03-25 16:42:59 -07001720 @Override
1721 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1722 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1723 return val - mTimeBeforeMark;
1724 }
1725
1726 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001727 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001728 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1730 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001731 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001733 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001735 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001736
1737
Joe Onoratoabded112016-02-08 16:49:39 -08001738 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001739 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1740 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001741 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001742 }
1743
Joe Onoratoabded112016-02-08 16:49:39 -08001744 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001745 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001746 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001747 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001748 mUnpluggedTime = mTotalTime;
1749 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001750 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001751 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001752
1753 // When reading the summary, we set the mark to be the latest information.
1754 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001755 }
1756 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001757
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001758 /**
1759 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1760 * method. The state of the timer according to its {@link TimeBase} will determine how much
1761 * of the value is recorded.
1762 *
1763 * If the value being recorded resets, {@link #endSample()} can be called in order to
1764 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1765 * between calls, the {@link #endSample()} is automatically called and the new value is
1766 * expected to increase monotonically from that point on.
1767 */
Joe Onoratoabded112016-02-08 16:49:39 -08001768 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001769
Evan Millarc64edde2009-04-18 12:26:32 -07001770 /**
1771 * The most recent reported count from /proc/wakelocks.
1772 */
1773 int mCurrentReportedCount;
1774
1775 /**
1776 * The reported count from /proc/wakelocks when unplug() was last
1777 * called.
1778 */
1779 int mUnpluggedReportedCount;
1780
1781 /**
1782 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001783 */
Evan Millarc64edde2009-04-18 12:26:32 -07001784 long mCurrentReportedTotalTime;
1785
1786
1787 /**
1788 * The reported total_time from /proc/wakelocks when unplug() was last
1789 * called.
1790 */
1791 long mUnpluggedReportedTotalTime;
1792
1793 /**
1794 * Whether we are currently in a discharge cycle.
1795 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001796 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001797
1798 /**
1799 * Whether we are currently recording reported values.
1800 */
1801 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001802
Evan Millarc64edde2009-04-18 12:26:32 -07001803 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001804 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001805 */
1806 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001807
Adam Lesinski98f0d462016-04-19 16:46:20 -07001808 @VisibleForTesting
1809 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001810 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001811 mCurrentReportedCount = in.readInt();
1812 mUnpluggedReportedCount = in.readInt();
1813 mCurrentReportedTotalTime = in.readLong();
1814 mUnpluggedReportedTotalTime = in.readLong();
1815 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001816 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001817 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001818
Adam Lesinski98f0d462016-04-19 16:46:20 -07001819 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001820 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001821 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001822 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001823 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001824 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001825
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001826 /**
1827 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1828 * be less than the values used for a previous invocation.
1829 */
1830 public void endSample() {
1831 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1832 mCount = computeCurrentCountLocked();
1833 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1834 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001835 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001836
Evan Millarc64edde2009-04-18 12:26:32 -07001837 public void setUpdateVersion(int version) {
1838 mUpdateVersion = version;
1839 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001840
Evan Millarc64edde2009-04-18 12:26:32 -07001841 public int getUpdateVersion() {
1842 return mUpdateVersion;
1843 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001844
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001845 /**
1846 * Updates the current recorded values. These are meant to be monotonically increasing
1847 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1848 *
1849 * If the values being recorded have been reset, the monotonically increasing requirement
1850 * will be broken. In this case, {@link #endSample()} is automatically called and
1851 * the total value of totalTime and count are recorded, starting a new monotonically
1852 * increasing sample.
1853 *
1854 * @param totalTime total time of sample in microseconds.
1855 * @param count total number of times the event being sampled occurred.
1856 */
1857 public void update(long totalTime, int count) {
1858 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001859 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001860 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001861 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001862 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001863
1864 mTrackingReportedValues = true;
1865
1866 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1867 endSample();
1868 }
1869
1870 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001871 mCurrentReportedCount = count;
1872 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001873
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001874 /**
1875 * Adds deltaTime and deltaCount to the current sample.
1876 *
1877 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1878 * @param deltaCount additional number of times the event being sampled occurred.
1879 */
1880 public void add(long deltaTime, int deltaCount) {
1881 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001882 }
1883
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001884 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001885 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
1886 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001887 if (mTrackingReportedValues) {
1888 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
1889 mUnpluggedReportedCount = mCurrentReportedCount;
1890 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001891 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07001892 }
1893
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001894 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001895 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1896 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1897 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07001898 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001899
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001900 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001901 public void logState(Printer pw, String prefix) {
1902 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001903 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07001904 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
1905 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
1906 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
1907 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001908
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001909 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001910 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001911 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001912 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
1913 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001914
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001915 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001916 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001917 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001918 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
1919 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001920
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001921 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001922 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1923 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001924 out.writeInt(mCurrentReportedCount);
1925 out.writeInt(mUnpluggedReportedCount);
1926 out.writeLong(mCurrentReportedTotalTime);
1927 out.writeLong(mUnpluggedReportedTotalTime);
1928 out.writeInt(mTrackingReportedValues ? 1 : 0);
1929 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001930
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001931 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001932 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001933 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001934 mTrackingReportedValues = false;
1935 mUnpluggedReportedTotalTime = 0;
1936 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001937 return true;
1938 }
Evan Millarc64edde2009-04-18 12:26:32 -07001939 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001940
Evan Millarc64edde2009-04-18 12:26:32 -07001941 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001942 * A timer that increments in batches. It does not run for durations, but just jumps
1943 * for a pre-determined amount.
1944 */
Joe Onoratoabded112016-02-08 16:49:39 -08001945 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001946 final Uid mUid;
1947
1948 /**
1949 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
1950 */
1951 long mLastAddedTime;
1952
1953 /**
1954 * The last duration that we added to the timer. This is in microseconds.
1955 */
1956 long mLastAddedDuration;
1957
1958 /**
1959 * Whether we are currently in a discharge cycle.
1960 */
1961 boolean mInDischarge;
1962
Joe Onoratoabded112016-02-08 16:49:39 -08001963 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
1964 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001965 mUid = uid;
1966 mLastAddedTime = in.readLong();
1967 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001968 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001969 }
1970
Joe Onoratoabded112016-02-08 16:49:39 -08001971 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
1972 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001973 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001974 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001975 }
1976
1977 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001978 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1979 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001980 out.writeLong(mLastAddedTime);
1981 out.writeLong(mLastAddedDuration);
1982 }
1983
1984 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001985 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001986 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001987 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001988 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001989 }
1990
1991 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001992 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001993 recomputeLastDuration(elapsedRealtime, false);
1994 mInDischarge = true;
1995 // If we are still within the last added duration, then re-added whatever remains.
1996 if (mLastAddedTime == elapsedRealtime) {
1997 mTotalTime += mLastAddedDuration;
1998 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001999 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002000 }
2001
2002 @Override
2003 public void logState(Printer pw, String prefix) {
2004 super.logState(pw, prefix);
2005 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
2006 + " mLastAddedDuration=" + mLastAddedDuration);
2007 }
2008
2009 private long computeOverage(long curTime) {
2010 if (mLastAddedTime > 0) {
2011 return mLastTime + mLastAddedDuration - curTime;
2012 }
2013 return 0;
2014 }
2015
2016 private void recomputeLastDuration(long curTime, boolean abort) {
2017 final long overage = computeOverage(curTime);
2018 if (overage > 0) {
2019 // Aborting before the duration ran out -- roll back the remaining
2020 // duration. Only do this if currently discharging; otherwise we didn't
2021 // actually add the time.
2022 if (mInDischarge) {
2023 mTotalTime -= overage;
2024 }
2025 if (abort) {
2026 mLastAddedTime = 0;
2027 } else {
2028 mLastAddedTime = curTime;
2029 mLastAddedDuration -= overage;
2030 }
2031 }
2032 }
2033
2034 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08002035 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002036 recomputeLastDuration(now, true);
2037 mLastAddedTime = now;
2038 mLastAddedDuration = durationMillis * 1000;
2039 if (mInDischarge) {
2040 mTotalTime += mLastAddedDuration;
2041 mCount++;
2042 }
2043 }
2044
2045 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002046 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002047 recomputeLastDuration(now, true);
2048 }
2049
2050 @Override
2051 protected int computeCurrentCountLocked() {
2052 return mCount;
2053 }
2054
2055 @Override
2056 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002057 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002058 if (overage > 0) {
2059 return mTotalTime = overage;
2060 }
2061 return mTotalTime;
2062 }
2063
2064 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002065 public boolean reset(boolean detachIfReset) {
2066 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002067 recomputeLastDuration(now, true);
2068 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002069 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002070 return !stillActive;
2071 }
2072 }
2073
Joe Onorato92fd23f2016-07-25 11:18:42 -07002074
2075 /**
2076 * A StopwatchTimer that also tracks the total and max individual
2077 * time spent active according to the given timebase. Whereas
2078 * StopwatchTimer apportions the time amongst all in the pool,
2079 * the total and max durations are not apportioned.
2080 */
2081 public static class DurationTimer extends StopwatchTimer {
2082 /**
2083 * The time (in ms) that the timer was last acquired or the time base
2084 * last (re-)started. Increasing the nesting depth does not reset this time.
2085 *
2086 * -1 if the timer is currently not running or the time base is not running.
2087 *
2088 * If written to a parcel, the start time is reset, as is mNesting in the base class
2089 * StopwatchTimer.
2090 */
2091 long mStartTimeMs = -1;
2092
2093 /**
Bookatz867c0d72017-03-07 18:23:42 -08002094 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002095 */
2096 long mMaxDurationMs;
2097
2098 /**
Bookatz867c0d72017-03-07 18:23:42 -08002099 * The time (in ms) that that the timer has been active since most recent
2100 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002101 */
2102 long mCurrentDurationMs;
2103
Bookatz867c0d72017-03-07 18:23:42 -08002104 /**
2105 * The total time (in ms) that that the timer has been active since most recent reset()
2106 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2107 * (but not including the present currentDuration) since reset. Not pooled.
2108 */
2109 long mTotalDurationMs;
2110
Joe Onorato92fd23f2016-07-25 11:18:42 -07002111 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2112 TimeBase timeBase, Parcel in) {
2113 super(clocks, uid, type, timerPool, timeBase, in);
2114 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002115 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002116 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002117 }
2118
2119 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2120 TimeBase timeBase) {
2121 super(clocks, uid, type, timerPool, timeBase);
2122 }
2123
2124 @Override
2125 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2126 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002127 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002128 out.writeLong(mTotalDurationMs);
2129 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002130 }
2131
2132 /**
2133 * Write the summary to the parcel.
2134 *
2135 * Since the time base is probably meaningless after we come back, reading
2136 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002137 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002138 */
2139 @Override
2140 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2141 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002142 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002143 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002144 }
2145
2146 /**
2147 * Read the summary parcel.
2148 *
2149 * Has the side effect of stopping the timer.
2150 */
2151 @Override
2152 public void readSummaryFromParcelLocked(Parcel in) {
2153 super.readSummaryFromParcelLocked(in);
2154 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002155 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002156 mStartTimeMs = -1;
2157 mCurrentDurationMs = 0;
2158 }
2159
2160 /**
2161 * The TimeBase time started (again).
2162 *
2163 * If the timer is also running, store the start time.
2164 */
2165 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2166 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2167 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002168 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002169 }
2170 }
2171
2172 /**
2173 * The TimeBase stopped running.
2174 *
2175 * If the timer is running, add the duration into mCurrentDurationMs.
2176 */
2177 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002178 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2179 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002180 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002181 // baseRealtimeUs has already been converted to the timebase's realtime.
2182 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002183 }
2184 mStartTimeMs = -1;
2185 }
2186
2187 @Override
2188 public void logState(Printer pw, String prefix) {
2189 super.logState(pw, prefix);
2190 }
2191
2192 @Override
2193 public void startRunningLocked(long elapsedRealtimeMs) {
2194 super.startRunningLocked(elapsedRealtimeMs);
2195 if (mNesting == 1 && mTimeBase.isRunning()) {
2196 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002197 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002198 }
2199 }
2200
2201 /**
2202 * Decrements the mNesting ref-count on this timer.
2203 *
2204 * If it actually stopped (mNesting went to 0), then possibly update
2205 * mMaxDuration if the current duration was the longest ever.
2206 */
2207 @Override
2208 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002209 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002210 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002211 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002212 if (durationMs > mMaxDurationMs) {
2213 mMaxDurationMs = durationMs;
2214 }
2215 mStartTimeMs = -1;
2216 mCurrentDurationMs = 0;
2217 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002218 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2219 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2220 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002221 }
2222
2223 @Override
2224 public boolean reset(boolean detachIfReset) {
2225 boolean result = super.reset(detachIfReset);
2226 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002227 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002228 mCurrentDurationMs = 0;
2229 if (mNesting > 0) {
2230 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2231 } else {
2232 mStartTimeMs = -1;
2233 }
2234 return result;
2235 }
2236
2237 /**
2238 * Returns the max duration that this timer has ever seen.
2239 *
2240 * Note that this time is NOT split between the timers in the timer group that
2241 * this timer is attached to. It is the TOTAL time.
2242 */
2243 @Override
2244 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2245 if (mNesting > 0) {
2246 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2247 if (durationMs > mMaxDurationMs) {
2248 return durationMs;
2249 }
2250 }
2251 return mMaxDurationMs;
2252 }
2253
2254 /**
2255 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002256 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002257 *
2258 * Note that this time is NOT split between the timers in the timer group that
2259 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002260 *
2261 * Note that if running timer is parceled and unparceled, this method will return
2262 * current duration value at the time of parceling even though timer may not be
2263 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002264 */
2265 @Override
2266 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2267 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002268 if (mNesting > 0 && mTimeBase.isRunning()) {
2269 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2270 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002271 }
2272 return durationMs;
2273 }
Bookatz867c0d72017-03-07 18:23:42 -08002274
2275 /**
2276 * Returns the total cumulative duration that this timer has been on since reset().
2277 * If mTimerPool == null, this should be the same
2278 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2279 *
2280 * Note that this time is NOT split between the timers in the timer group that
2281 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2282 * the result will not be equivalent to getTotalTimeLocked.
2283 */
2284 @Override
2285 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2286 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2287 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002288 }
2289
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002290 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002291 * State for keeping track of timing information.
2292 */
Joe Onoratoabded112016-02-08 16:49:39 -08002293 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002294 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002295 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002296
Evan Millarc64edde2009-04-18 12:26:32 -07002297 int mNesting;
2298
Evan Millarc64edde2009-04-18 12:26:32 -07002299 /**
2300 * The last time at which we updated the timer. If mNesting is > 0,
2301 * subtract this from the current battery time to find the amount of
2302 * time we have been running since we last computed an update.
2303 */
2304 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002305
Evan Millarc64edde2009-04-18 12:26:32 -07002306 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002307 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002308 * was actually held for an interesting duration. If time base was not running when timer
2309 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002310 */
Bookatzceebafe2017-04-06 11:59:13 -07002311 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002312
Amith Yamasanif37447b2009-10-08 18:28:01 -07002313 long mTimeout;
2314
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002315 /**
2316 * For partial wake locks, keep track of whether we are in the list
2317 * to consume CPU cycles.
2318 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002319 @VisibleForTesting
2320 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002321
Joe Onoratoabded112016-02-08 16:49:39 -08002322 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002323 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002324 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002325 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002326 mTimerPool = timerPool;
2327 mUpdateTime = in.readLong();
2328 }
2329
Joe Onoratoabded112016-02-08 16:49:39 -08002330 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002331 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002332 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002333 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002334 mTimerPool = timerPool;
2335 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002336
Joe Onoratoabded112016-02-08 16:49:39 -08002337 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002338 mTimeout = timeout;
2339 }
2340
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002341 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2342 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002343 out.writeLong(mUpdateTime);
2344 }
2345
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002346 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002347 if (mNesting > 0) {
2348 if (DEBUG && mType < 0) {
2349 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2350 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002351 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2352 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002353 if (DEBUG && mType < 0) {
2354 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2355 }
2356 }
2357 }
2358
2359 public void logState(Printer pw, String prefix) {
2360 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002361 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 + " mAcquireTime=" + mAcquireTime);
2363 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002364
Joe Onoratoabded112016-02-08 16:49:39 -08002365 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002367 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002368 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 if (mTimerPool != null) {
2370 // Accumulate time to all currently active timers before adding
2371 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002372 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 // Add this timer to the active pool
2374 mTimerPool.add(this);
2375 }
Bookatzceebafe2017-04-06 11:59:13 -07002376 if (mTimeBase.isRunning()) {
2377 // Increment the count
2378 mCount++;
2379 mAcquireTime = mTotalTime;
2380 } else {
2381 mAcquireTime = -1;
2382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 if (DEBUG && mType < 0) {
2384 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2385 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2386 + " mAcquireTime=" + mAcquireTime);
2387 }
2388 }
2389 }
2390
Joe Onoratoabded112016-02-08 16:49:39 -08002391 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002392 return mNesting > 0;
2393 }
2394
Joe Onoratoabded112016-02-08 16:49:39 -08002395 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 // Ignore attempt to stop a timer that isn't running
2397 if (mNesting == 0) {
2398 return;
2399 }
2400 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002401 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 if (mTimerPool != null) {
2403 // Accumulate time to all active counters, scaled by the total
2404 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002405 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 // Remove this timer from the active pool
2407 mTimerPool.remove(this);
2408 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 mNesting = 1;
2410 mTotalTime = computeRunTimeLocked(batteryRealtime);
2411 mNesting = 0;
2412 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 if (DEBUG && mType < 0) {
2415 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2416 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2417 + " mAcquireTime=" + mAcquireTime);
2418 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002419
Bookatzceebafe2017-04-06 11:59:13 -07002420 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 // If there was no change in the time, then discard this
2422 // count. A somewhat cheezy strategy, but hey.
2423 mCount--;
2424 }
2425 }
2426 }
2427
Joe Onoratoabded112016-02-08 16:49:39 -08002428 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002429 if (mNesting > 0) {
2430 mNesting = 1;
2431 stopRunningLocked(elapsedRealtimeMs);
2432 }
2433 }
2434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 // Update the total time for all other running Timers with the same type as this Timer
2436 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002437 private static long refreshTimersLocked(long batteryRealtime,
2438 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002439 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 final int N = pool.size();
2441 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002442 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 long heldTime = batteryRealtime - t.mUpdateTime;
2444 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002445 final long myTime = heldTime / N;
2446 if (t == self) {
2447 selfTime = myTime;
2448 }
2449 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 }
2451 t.mUpdateTime = batteryRealtime;
2452 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002453 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 }
2455
Evan Millarc64edde2009-04-18 12:26:32 -07002456 @Override
2457 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002458 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2459 curBatteryRealtime = mUpdateTime + mTimeout;
2460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 return mTotalTime + (mNesting > 0
2462 ? (curBatteryRealtime - mUpdateTime)
2463 / (mTimerPool != null ? mTimerPool.size() : 1)
2464 : 0);
2465 }
2466
Evan Millarc64edde2009-04-18 12:26:32 -07002467 @Override
2468 protected int computeCurrentCountLocked() {
2469 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 }
2471
Adam Lesinskie08af192015-03-25 16:42:59 -07002472 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002473 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002474 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002475 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002476 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002477 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002478 }
Bookatzceebafe2017-04-06 11:59:13 -07002479 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002480 return canDetach;
2481 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002482
Adam Lesinskie08af192015-03-25 16:42:59 -07002483 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002484 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002485 super.detach();
2486 if (mTimerPool != null) {
2487 mTimerPool.remove(this);
2488 }
2489 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002490
Adam Lesinskie08af192015-03-25 16:42:59 -07002491 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002492 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002493 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 mNesting = 0;
2495 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002496
2497 /**
2498 * Set the mark so that we can query later for the total time the timer has
2499 * accumulated since this point. The timer can be running or not.
2500 *
2501 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2502 */
2503 public void setMark(long elapsedRealtimeMs) {
2504 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2505 if (mNesting > 0) {
2506 // We are running.
2507 if (mTimerPool != null) {
2508 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2509 } else {
2510 mTotalTime += batteryRealtime - mUpdateTime;
2511 mUpdateTime = batteryRealtime;
2512 }
2513 }
2514 mTimeBeforeMark = mTotalTime;
2515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002517
Bookatz867c0d72017-03-07 18:23:42 -08002518 /**
2519 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2520 * TimeBase is effectively a subset of the other.
2521 */
Bookatzaa4594a2017-03-24 12:39:56 -07002522 public static class DualTimer extends DurationTimer {
2523 // This class both is a DurationTimer and also holds a second DurationTimer.
2524 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2525 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2526 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002527 // mSubTimer typically tracks only part of the total time, such as background time, as
2528 // determined by a subTimeBase. It is NOT pooled.
2529 private final DurationTimer mSubTimer;
2530
2531 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002532 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2533 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002534 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002535 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002536 */
2537 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2538 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002539 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002540 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2541 }
2542
2543 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002544 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2545 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002546 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002547 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002548 */
2549 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2550 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002551 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002552 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2553 }
2554
Bookatz867c0d72017-03-07 18:23:42 -08002555 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002556 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002557 public DurationTimer getSubTimer() {
2558 return mSubTimer;
2559 }
2560
Bookatzaa4594a2017-03-24 12:39:56 -07002561 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002562 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002563 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002564 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2565 }
2566
Bookatzaa4594a2017-03-24 12:39:56 -07002567 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002568 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002569 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002570 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2571 }
2572
Bookatzaa4594a2017-03-24 12:39:56 -07002573 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002574 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002575 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002576 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2577 }
2578
Bookatzaa4594a2017-03-24 12:39:56 -07002579 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002580 public boolean reset(boolean detachIfReset) {
2581 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002582 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2583 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002584 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002585 return !active;
2586 }
2587
Bookatzaa4594a2017-03-24 12:39:56 -07002588 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002589 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002590 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002591 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002592 }
2593
Bookatzaa4594a2017-03-24 12:39:56 -07002594 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002595 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002596 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002597 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2598 }
2599
Bookatzaa4594a2017-03-24 12:39:56 -07002600 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002601 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002602 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002603 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2604 }
2605
Bookatzaa4594a2017-03-24 12:39:56 -07002606 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002607 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002608 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002609 mSubTimer.readSummaryFromParcelLocked(in);
2610 }
2611 }
2612
2613
Dianne Hackbornd953c532014-08-16 18:17:38 -07002614 public abstract class OverflowArrayMap<T> {
2615 private static final String OVERFLOW_NAME = "*overflow*";
2616
Dianne Hackborn657153b2016-07-29 14:54:14 -07002617 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002618 final ArrayMap<String, T> mMap = new ArrayMap<>();
2619 T mCurOverflow;
2620 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002621 long mLastOverflowTime;
2622 long mLastOverflowFinishTime;
2623 long mLastClearTime;
2624 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002625
Dianne Hackborn657153b2016-07-29 14:54:14 -07002626 public OverflowArrayMap(int uid) {
2627 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002628 }
2629
2630 public ArrayMap<String, T> getMap() {
2631 return mMap;
2632 }
2633
2634 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002635 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002636 mMap.clear();
2637 mCurOverflow = null;
2638 mActiveOverflow = null;
2639 }
2640
2641 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002642 if (name == null) {
2643 name = "";
2644 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002645 mMap.put(name, obj);
2646 if (OVERFLOW_NAME.equals(name)) {
2647 mCurOverflow = obj;
2648 }
2649 }
2650
2651 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002652 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002653 if (mActiveOverflow != null) {
2654 if (mActiveOverflow.size() == 0) {
2655 mActiveOverflow = null;
2656 }
2657 }
2658 if (mActiveOverflow == null) {
2659 // There is no currently active overflow, so we should no longer have
2660 // an overflow entry.
2661 if (mMap.containsKey(OVERFLOW_NAME)) {
2662 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2663 + mMap.get(OVERFLOW_NAME));
2664 mMap.remove(OVERFLOW_NAME);
2665 }
2666 mCurOverflow = null;
2667 } else {
2668 // There is currently active overflow, so we should still have an overflow entry.
2669 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2670 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2671 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2672 }
2673 }
2674 }
2675
2676 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002677 if (name == null) {
2678 name = "";
2679 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002680 T obj = mMap.get(name);
2681 if (obj != null) {
2682 return obj;
2683 }
2684
2685 // No object exists for the given name, but do we currently have it
2686 // running as part of the overflow?
2687 if (mActiveOverflow != null) {
2688 MutableInt over = mActiveOverflow.get(name);
2689 if (over != null) {
2690 // We are already actively counting this name in the overflow object.
2691 obj = mCurOverflow;
2692 if (obj == null) {
2693 // Shouldn't be here, but we'll try to recover.
2694 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2695 obj = mCurOverflow = instantiateObject();
2696 mMap.put(OVERFLOW_NAME, obj);
2697 }
2698 over.value++;
2699 return obj;
2700 }
2701 }
2702
2703 // No object exists for given name nor in the overflow; we need to make
2704 // a new one.
2705 final int N = mMap.size();
2706 if (N >= MAX_WAKELOCKS_PER_UID) {
2707 // Went over the limit on number of objects to track; this one goes
2708 // in to the overflow.
2709 obj = mCurOverflow;
2710 if (obj == null) {
2711 // Need to start overflow now...
2712 obj = mCurOverflow = instantiateObject();
2713 mMap.put(OVERFLOW_NAME, obj);
2714 }
2715 if (mActiveOverflow == null) {
2716 mActiveOverflow = new ArrayMap<>();
2717 }
2718 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002719 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002720 return obj;
2721 }
2722
2723 // Normal case where we just need to make a new object.
2724 obj = instantiateObject();
2725 mMap.put(name, obj);
2726 return obj;
2727 }
2728
2729 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002730 if (name == null) {
2731 name = "";
2732 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002733 T obj = mMap.get(name);
2734 if (obj != null) {
2735 return obj;
2736 }
2737
2738 // No object exists for the given name, but do we currently have it
2739 // running as part of the overflow?
2740 if (mActiveOverflow != null) {
2741 MutableInt over = mActiveOverflow.get(name);
2742 if (over != null) {
2743 // We are already actively counting this name in the overflow object.
2744 obj = mCurOverflow;
2745 if (obj != null) {
2746 over.value--;
2747 if (over.value <= 0) {
2748 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002749 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002750 }
2751 return obj;
2752 }
2753 }
2754 }
2755
2756 // Huh, they are stopping an active operation but we can't find one!
2757 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002758 StringBuilder sb = new StringBuilder();
2759 sb.append("Unable to find object for ");
2760 sb.append(name);
2761 sb.append(" in uid ");
2762 sb.append(mUid);
2763 sb.append(" mapsize=");
2764 sb.append(mMap.size());
2765 sb.append(" activeoverflow=");
2766 sb.append(mActiveOverflow);
2767 sb.append(" curoverflow=");
2768 sb.append(mCurOverflow);
2769 long now = SystemClock.elapsedRealtime();
2770 if (mLastOverflowTime != 0) {
2771 sb.append(" lastOverflowTime=");
2772 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2773 }
2774 if (mLastOverflowFinishTime != 0) {
2775 sb.append(" lastOverflowFinishTime=");
2776 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2777 }
2778 if (mLastClearTime != 0) {
2779 sb.append(" lastClearTime=");
2780 TimeUtils.formatDuration(mLastClearTime-now, sb);
2781 }
2782 if (mLastCleanupTime != 0) {
2783 sb.append(" lastCleanupTime=");
2784 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2785 }
2786 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002787 return null;
2788 }
2789
2790 public abstract T instantiateObject();
2791 }
2792
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002793 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2794 implements Parcelable {
2795 private final LongSamplingCounter mIdleTimeMillis;
Siddharth Rayb50a6842017-12-14 15:15:28 -08002796 private final LongSamplingCounter mScanTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002797 private final LongSamplingCounter mRxTimeMillis;
2798 private final LongSamplingCounter[] mTxTimeMillis;
2799 private final LongSamplingCounter mPowerDrainMaMs;
2800
2801 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2802 mIdleTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002803 mScanTimeMillis = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002804 mRxTimeMillis = new LongSamplingCounter(timeBase);
2805 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2806 for (int i = 0; i < numTxStates; i++) {
2807 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2808 }
2809 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2810 }
2811
2812 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2813 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002814 mScanTimeMillis = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002815 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2816 final int recordedTxStates = in.readInt();
2817 if (recordedTxStates != numTxStates) {
2818 throw new ParcelFormatException("inconsistent tx state lengths");
2819 }
2820
2821 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2822 for (int i = 0; i < numTxStates; i++) {
2823 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2824 }
2825 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2826 }
2827
2828 public void readSummaryFromParcel(Parcel in) {
2829 mIdleTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002830 mScanTimeMillis.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002831 mRxTimeMillis.readSummaryFromParcelLocked(in);
2832 final int recordedTxStates = in.readInt();
2833 if (recordedTxStates != mTxTimeMillis.length) {
2834 throw new ParcelFormatException("inconsistent tx state lengths");
2835 }
2836 for (LongSamplingCounter counter : mTxTimeMillis) {
2837 counter.readSummaryFromParcelLocked(in);
2838 }
2839 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2840 }
2841
2842 @Override
2843 public int describeContents() {
2844 return 0;
2845 }
2846
2847 public void writeSummaryToParcel(Parcel dest) {
2848 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002849 mScanTimeMillis.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002850 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2851 dest.writeInt(mTxTimeMillis.length);
2852 for (LongSamplingCounter counter : mTxTimeMillis) {
2853 counter.writeSummaryFromParcelLocked(dest);
2854 }
2855 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2856 }
2857
2858 @Override
2859 public void writeToParcel(Parcel dest, int flags) {
2860 mIdleTimeMillis.writeToParcel(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002861 mScanTimeMillis.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002862 mRxTimeMillis.writeToParcel(dest);
2863 dest.writeInt(mTxTimeMillis.length);
2864 for (LongSamplingCounter counter : mTxTimeMillis) {
2865 counter.writeToParcel(dest);
2866 }
2867 mPowerDrainMaMs.writeToParcel(dest);
2868 }
2869
2870 public void reset(boolean detachIfReset) {
2871 mIdleTimeMillis.reset(detachIfReset);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002872 mScanTimeMillis.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002873 mRxTimeMillis.reset(detachIfReset);
2874 for (LongSamplingCounter counter : mTxTimeMillis) {
2875 counter.reset(detachIfReset);
2876 }
2877 mPowerDrainMaMs.reset(detachIfReset);
2878 }
2879
2880 public void detach() {
2881 mIdleTimeMillis.detach();
Siddharth Rayb50a6842017-12-14 15:15:28 -08002882 mScanTimeMillis.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002883 mRxTimeMillis.detach();
2884 for (LongSamplingCounter counter : mTxTimeMillis) {
2885 counter.detach();
2886 }
2887 mPowerDrainMaMs.detach();
2888 }
2889
2890 /**
2891 * @return a LongSamplingCounter, measuring time spent in the idle state in
2892 * milliseconds.
2893 */
2894 @Override
2895 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07002896 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002897 }
2898
2899 /**
Siddharth Rayb50a6842017-12-14 15:15:28 -08002900 * @return a LongSamplingCounter, measuring time spent in the scan state in
2901 * milliseconds.
2902 */
2903 @Override
2904 public LongSamplingCounter getScanTimeCounter() {
2905 return mScanTimeMillis;
2906 }
2907
2908 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002909 * @return a LongSamplingCounter, measuring time spent in the receive state in
2910 * milliseconds.
2911 */
2912 @Override
2913 public LongSamplingCounter getRxTimeCounter() {
2914 return mRxTimeMillis;
2915 }
2916
2917 /**
2918 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
2919 * milliseconds.
2920 */
2921 @Override
2922 public LongSamplingCounter[] getTxTimeCounters() {
2923 return mTxTimeMillis;
2924 }
2925
2926 /**
2927 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
2928 */
2929 @Override
2930 public LongSamplingCounter getPowerCounter() {
2931 return mPowerDrainMaMs;
2932 }
2933 }
2934
Bookatz50df7112017-08-04 14:53:26 -07002935 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
2936 public SamplingTimer getRpmTimerLocked(String name) {
2937 SamplingTimer rpmt = mRpmStats.get(name);
2938 if (rpmt == null) {
2939 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2940 mRpmStats.put(name, rpmt);
2941 }
2942 return rpmt;
2943 }
2944
2945 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
2946 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
2947 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
2948 if (rpmt == null) {
2949 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
2950 mScreenOffRpmStats.put(name, rpmt);
2951 }
2952 return rpmt;
2953 }
2954
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002955 /*
2956 * Get the wakeup reason counter, and create a new one if one
2957 * doesn't already exist.
2958 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002959 public SamplingTimer getWakeupReasonTimerLocked(String name) {
2960 SamplingTimer timer = mWakeupReasonStats.get(name);
2961 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002962 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002963 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002964 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002965 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002966 }
2967
Evan Millarc64edde2009-04-18 12:26:32 -07002968 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002969 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07002970 * doesn't already exist.
2971 */
2972 public SamplingTimer getKernelWakelockTimerLocked(String name) {
2973 SamplingTimer kwlt = mKernelWakelockStats.get(name);
2974 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002975 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07002976 mKernelWakelockStats.put(name, kwlt);
2977 }
2978 return kwlt;
2979 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07002980
James Carr3a226052016-07-01 14:49:52 -07002981 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
2982 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
2983 if (kmt == null) {
2984 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2985 mKernelMemoryStats.put(bucket, kmt);
2986 }
2987 return kmt;
2988 }
2989
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002990 private int writeHistoryTag(HistoryTag tag) {
2991 Integer idxObj = mHistoryTagPool.get(tag);
2992 int idx;
2993 if (idxObj != null) {
2994 idx = idxObj;
2995 } else {
2996 idx = mNextHistoryTagIdx;
2997 HistoryTag key = new HistoryTag();
2998 key.setTo(tag);
2999 tag.poolIdx = idx;
3000 mHistoryTagPool.put(key, idx);
3001 mNextHistoryTagIdx++;
3002 mNumHistoryTagChars += key.string.length() + 1;
3003 }
3004 return idx;
3005 }
3006
3007 private void readHistoryTag(int index, HistoryTag tag) {
3008 tag.string = mReadHistoryStrings[index];
3009 tag.uid = mReadHistoryUids[index];
3010 tag.poolIdx = index;
3011 }
3012
Adam Lesinski926969b2016-04-28 17:31:12 -07003013 /*
3014 The history delta format uses flags to denote further data in subsequent ints in the parcel.
3015
3016 There is always the first token, which may contain the delta time, or an indicator of
3017 the length of the time (int or long) following this token.
3018
3019 First token: always present,
3020 31 23 15 7 0
3021 â–ˆ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â–ˆ
3022
3023 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
3024 follows containing the time, and 0x7ffff indicates a long immediately follows with the
3025 delta time.
3026 A: battery level changed and an int follows with battery data.
3027 B: state changed and an int follows with state change data.
3028 C: state2 has changed and an int follows with state2 change data.
3029 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
3030 E: event data has changed and an event struct follows.
3031 F: battery charge in coulombs has changed and an int with the charge follows.
3032 G: state flag denoting that the mobile radio was active.
3033 H: state flag denoting that the wifi radio was active.
3034 I: state flag denoting that a wifi scan occurred.
3035 J: state flag denoting that a wifi full lock was held.
3036 K: state flag denoting that the gps was on.
3037 L: state flag denoting that a wakelock was held.
3038 M: state flag denoting that the cpu was running.
3039
3040 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3041 with the time delta.
3042
3043 Battery level int: if A in the first token is set,
3044 31 23 15 7 0
3045 â–ˆ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â–ˆ
3046
3047 D: indicates that extra history details follow.
3048 V: the battery voltage.
3049 T: the battery temperature.
3050 L: the battery level (out of 100).
3051
3052 State change int: if B in the first token is set,
3053 31 23 15 7 0
3054 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3055
3056 A: wifi multicast was on.
3057 B: battery was plugged in.
3058 C: screen was on.
3059 D: phone was scanning for signal.
3060 E: audio was on.
3061 F: a sensor was active.
3062
3063 State2 change int: if C in the first token is set,
3064 31 23 15 7 0
3065 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3066
3067 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3068 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3069 C: a bluetooth scan was active.
3070 D: the camera was active.
3071 E: bluetooth was on.
3072 F: a phone call was active.
3073 G: the device was charging.
3074 H: 2 bits indicating the device-idle (doze) state: off, light, full
3075 I: the flashlight was on.
3076 J: wifi was on.
3077 K: wifi was running.
3078 L: video was playing.
3079 M: power save mode was on.
3080
3081 Wakelock/wakereason struct: if D in the first token is set,
3082 TODO(adamlesinski): describe wakelock/wakereason struct.
3083
3084 Event struct: if E in the first token is set,
3085 TODO(adamlesinski): describe the event struct.
3086
3087 History step details struct: if D in the battery level int is set,
3088 TODO(adamlesinski): describe the history step details struct.
3089
3090 Battery charge int: if F in the first token is set, an int representing the battery charge
3091 in coulombs follows.
3092 */
3093
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003094 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003095 static final int DELTA_TIME_MASK = 0x7ffff;
3096 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3097 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3098 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003099 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003100 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003101 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003102 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003103 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003104 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003105 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003106 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003107 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003108 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003109 // Flag in delta int: contains the battery charge count in uAh.
3110 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003111 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003112 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003113
3114 // These are the pieces of battery state that are packed in to the upper bits of
3115 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003116 // in STATE_BATTERY_MASK.
3117 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003118 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3119 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3120 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3121 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3122 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3123 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003124
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003125 // We use the low bit of the battery state int to indicate that we have full details
3126 // from a battery level change.
3127 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3128
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003129 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003130 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003131 dest.writeInt(DELTA_TIME_ABS);
3132 cur.writeToParcel(dest, 0);
3133 return;
3134 }
3135
3136 final long deltaTime = cur.time - last.time;
3137 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3138 final int lastStateInt = buildStateInt(last);
3139
3140 int deltaTimeToken;
3141 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3142 deltaTimeToken = DELTA_TIME_LONG;
3143 } else if (deltaTime >= DELTA_TIME_ABS) {
3144 deltaTimeToken = DELTA_TIME_INT;
3145 } else {
3146 deltaTimeToken = (int)deltaTime;
3147 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003148 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003149 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3150 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3151 final boolean computeStepDetails = includeStepDetails != 0
3152 || mLastHistoryStepDetails == null;
3153 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003154 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3155 if (batteryLevelIntChanged) {
3156 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3157 }
3158 final int stateInt = buildStateInt(cur);
3159 final boolean stateIntChanged = stateInt != lastStateInt;
3160 if (stateIntChanged) {
3161 firstToken |= DELTA_STATE_FLAG;
3162 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003163 final boolean state2IntChanged = cur.states2 != last.states2;
3164 if (state2IntChanged) {
3165 firstToken |= DELTA_STATE2_FLAG;
3166 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003167 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003168 firstToken |= DELTA_WAKELOCK_FLAG;
3169 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003170 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3171 firstToken |= DELTA_EVENT_FLAG;
3172 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003173
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003174 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3175 if (batteryChargeChanged) {
3176 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003177 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003178 dest.writeInt(firstToken);
3179 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3180 + " deltaTime=" + deltaTime);
3181
3182 if (deltaTimeToken >= DELTA_TIME_INT) {
3183 if (deltaTimeToken == DELTA_TIME_INT) {
3184 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3185 dest.writeInt((int)deltaTime);
3186 } else {
3187 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3188 dest.writeLong(deltaTime);
3189 }
3190 }
3191 if (batteryLevelIntChanged) {
3192 dest.writeInt(batteryLevelInt);
3193 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3194 + Integer.toHexString(batteryLevelInt)
3195 + " batteryLevel=" + cur.batteryLevel
3196 + " batteryTemp=" + cur.batteryTemperature
3197 + " batteryVolt=" + (int)cur.batteryVoltage);
3198 }
3199 if (stateIntChanged) {
3200 dest.writeInt(stateInt);
3201 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3202 + Integer.toHexString(stateInt)
3203 + " batteryStatus=" + cur.batteryStatus
3204 + " batteryHealth=" + cur.batteryHealth
3205 + " batteryPlugType=" + cur.batteryPlugType
3206 + " states=0x" + Integer.toHexString(cur.states));
3207 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003208 if (state2IntChanged) {
3209 dest.writeInt(cur.states2);
3210 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3211 + Integer.toHexString(cur.states2));
3212 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003213 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3214 int wakeLockIndex;
3215 int wakeReasonIndex;
3216 if (cur.wakelockTag != null) {
3217 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3218 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3219 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3220 } else {
3221 wakeLockIndex = 0xffff;
3222 }
3223 if (cur.wakeReasonTag != null) {
3224 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3225 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3226 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3227 } else {
3228 wakeReasonIndex = 0xffff;
3229 }
3230 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003231 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003232 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003233 int index = writeHistoryTag(cur.eventTag);
3234 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003235 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003236 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3237 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3238 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003239 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003240 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003241 if (mPlatformIdleStateCallback != null) {
3242 mCurHistoryStepDetails.statPlatformIdleState =
3243 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3244 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3245 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003246
3247 mCurHistoryStepDetails.statSubsystemPowerState =
3248 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3249 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3250 mCurHistoryStepDetails.statSubsystemPowerState);
3251
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003252 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003253 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3254 if (includeStepDetails != 0) {
3255 mCurHistoryStepDetails.writeToParcel(dest);
3256 }
3257 cur.stepDetails = mCurHistoryStepDetails;
3258 mLastHistoryStepDetails = mCurHistoryStepDetails;
3259 } else {
3260 cur.stepDetails = null;
3261 }
3262 if (mLastHistoryStepLevel < cur.batteryLevel) {
3263 mLastHistoryStepDetails = null;
3264 }
3265 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003266
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003267 if (batteryChargeChanged) {
3268 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3269 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003270 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003271 }
3272
3273 private int buildBatteryLevelInt(HistoryItem h) {
3274 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003275 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3276 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3277 }
3278
3279 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3280 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3281 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3282 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003283 }
3284
3285 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003286 int plugType = 0;
3287 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3288 plugType = 1;
3289 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3290 plugType = 2;
3291 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3292 plugType = 3;
3293 }
3294 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3295 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3296 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003297 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003298 }
3299
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003300 private void computeHistoryStepDetails(final HistoryStepDetails out,
3301 final HistoryStepDetails last) {
3302 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3303
3304 // Perform a CPU update right after we do this collection, so we have started
3305 // collecting good data for the next step.
3306 requestImmediateCpuUpdate();
3307
3308 if (last == null) {
3309 // We are not generating a delta, so all we need to do is reset the stats
3310 // we will later be doing a delta from.
3311 final int NU = mUidStats.size();
3312 for (int i=0; i<NU; i++) {
3313 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3314 uid.mLastStepUserTime = uid.mCurStepUserTime;
3315 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3316 }
3317 mLastStepCpuUserTime = mCurStepCpuUserTime;
3318 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3319 mLastStepStatUserTime = mCurStepStatUserTime;
3320 mLastStepStatSystemTime = mCurStepStatSystemTime;
3321 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3322 mLastStepStatIrqTime = mCurStepStatIrqTime;
3323 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3324 mLastStepStatIdleTime = mCurStepStatIdleTime;
3325 tmp.clear();
3326 return;
3327 }
3328 if (DEBUG) {
3329 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3330 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3331 + " irq=" + mLastStepStatIrqTime + " sirq="
3332 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3333 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3334 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3335 + " irq=" + mCurStepStatIrqTime + " sirq="
3336 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3337 }
3338 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3339 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3340 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3341 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3342 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3343 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3344 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3345 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3346 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3347 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3348 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3349 final int NU = mUidStats.size();
3350 for (int i=0; i<NU; i++) {
3351 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3352 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3353 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3354 final int totalTime = totalUTime + totalSTime;
3355 uid.mLastStepUserTime = uid.mCurStepUserTime;
3356 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3357 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3358 continue;
3359 }
3360 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3361 out.appCpuUid3 = uid.mUid;
3362 out.appCpuUTime3 = totalUTime;
3363 out.appCpuSTime3 = totalSTime;
3364 } else {
3365 out.appCpuUid3 = out.appCpuUid2;
3366 out.appCpuUTime3 = out.appCpuUTime2;
3367 out.appCpuSTime3 = out.appCpuSTime2;
3368 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3369 out.appCpuUid2 = uid.mUid;
3370 out.appCpuUTime2 = totalUTime;
3371 out.appCpuSTime2 = totalSTime;
3372 } else {
3373 out.appCpuUid2 = out.appCpuUid1;
3374 out.appCpuUTime2 = out.appCpuUTime1;
3375 out.appCpuSTime2 = out.appCpuSTime1;
3376 out.appCpuUid1 = uid.mUid;
3377 out.appCpuUTime1 = totalUTime;
3378 out.appCpuSTime1 = totalSTime;
3379 }
3380 }
3381 }
3382 mLastStepCpuUserTime = mCurStepCpuUserTime;
3383 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3384 mLastStepStatUserTime = mCurStepStatUserTime;
3385 mLastStepStatSystemTime = mCurStepStatSystemTime;
3386 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3387 mLastStepStatIrqTime = mCurStepStatIrqTime;
3388 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3389 mLastStepStatIdleTime = mCurStepStatIdleTime;
3390 }
3391
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003392 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3393 int firstToken = src.readInt();
3394 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003395 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003396 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003397 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3398 + " deltaTimeToken=" + deltaTimeToken);
3399
3400 if (deltaTimeToken < DELTA_TIME_ABS) {
3401 cur.time += deltaTimeToken;
3402 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3403 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003404 cur.numReadInts += 2;
3405 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003406 cur.readFromParcel(src);
3407 return;
3408 } else if (deltaTimeToken == DELTA_TIME_INT) {
3409 int delta = src.readInt();
3410 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003411 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003412 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3413 } else {
3414 long delta = src.readLong();
3415 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3416 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003417 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003418 }
3419
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003420 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003421 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003422 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003423 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003424 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003425 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3426 + Integer.toHexString(batteryLevelInt)
3427 + " batteryLevel=" + cur.batteryLevel
3428 + " batteryTemp=" + cur.batteryTemperature
3429 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003430 } else {
3431 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003432 }
3433
3434 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3435 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003436 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003437 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3438 & STATE_BATTERY_STATUS_MASK);
3439 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3440 & STATE_BATTERY_HEALTH_MASK);
3441 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3442 & STATE_BATTERY_PLUG_MASK);
3443 switch (cur.batteryPlugType) {
3444 case 1:
3445 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3446 break;
3447 case 2:
3448 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3449 break;
3450 case 3:
3451 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3452 break;
3453 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003454 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003455 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3456 + Integer.toHexString(stateInt)
3457 + " batteryStatus=" + cur.batteryStatus
3458 + " batteryHealth=" + cur.batteryHealth
3459 + " batteryPlugType=" + cur.batteryPlugType
3460 + " states=0x" + Integer.toHexString(cur.states));
3461 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003462 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003463 }
3464
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003465 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3466 cur.states2 = src.readInt();
3467 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3468 + Integer.toHexString(cur.states2));
3469 }
3470
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003471 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003472 int indexes = src.readInt();
3473 int wakeLockIndex = indexes&0xffff;
3474 int wakeReasonIndex = (indexes>>16)&0xffff;
3475 if (wakeLockIndex != 0xffff) {
3476 cur.wakelockTag = cur.localWakelockTag;
3477 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3478 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3479 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3480 } else {
3481 cur.wakelockTag = null;
3482 }
3483 if (wakeReasonIndex != 0xffff) {
3484 cur.wakeReasonTag = cur.localWakeReasonTag;
3485 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3486 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3487 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3488 } else {
3489 cur.wakeReasonTag = null;
3490 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003491 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003492 } else {
3493 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003494 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003495 }
3496
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003497 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003498 cur.eventTag = cur.localEventTag;
3499 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003500 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003501 final int index = ((codeAndIndex>>16)&0xffff);
3502 readHistoryTag(index, cur.eventTag);
3503 cur.numReadInts += 1;
3504 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3505 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3506 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003507 } else {
3508 cur.eventCode = HistoryItem.EVENT_NONE;
3509 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003510
3511 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3512 cur.stepDetails = mReadHistoryStepDetails;
3513 cur.stepDetails.readFromParcel(src);
3514 } else {
3515 cur.stepDetails = null;
3516 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003517
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003518 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3519 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003520 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003521 }
3522
Dianne Hackbornfc064132014-06-02 12:42:12 -07003523 @Override
3524 public void commitCurrentHistoryBatchLocked() {
3525 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3526 }
3527
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003528 void addHistoryBufferLocked(long elapsedRealtimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003529 if (!mHaveBatteryLevel || !mRecordingHistory) {
3530 return;
3531 }
3532
Dianne Hackborn40c87252014-03-19 16:55:40 -07003533 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003534 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3535 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003536 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003537 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003538 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3539 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003540 + Integer.toHexString(lastDiffStates) + " diff2="
3541 + Integer.toHexString(diffStates2) + " lastDiff2="
3542 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003543 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003544 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003545 && (diffStates2&lastDiffStates2) == 0
3546 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3547 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003548 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003549 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003550 || cur.eventCode == HistoryItem.EVENT_NONE)
3551 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3552 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3553 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3554 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3555 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3556 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003557 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003558 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003559 // as long as no bit has changed both between now and the last entry, as
3560 // well as the last entry and the one before it (so we capture any toggles).
3561 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003562 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3563 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3564 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003565 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003566 // If the last written history had a wakelock tag, we need to retain it.
3567 // Note that the condition above made sure that we aren't in a case where
3568 // both it and the current history item have a wakelock tag.
3569 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003570 cur.wakelockTag = cur.localWakelockTag;
3571 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003572 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003573 // If the last written history had a wake reason tag, we need to retain it.
3574 // Note that the condition above made sure that we aren't in a case where
3575 // both it and the current history item have a wakelock tag.
3576 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003577 cur.wakeReasonTag = cur.localWakeReasonTag;
3578 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003579 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003580 // If the last written history had an event, we need to retain it.
3581 // Note that the condition above made sure that we aren't in a case where
3582 // both it and the current history item have an event.
3583 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003584 cur.eventCode = mHistoryLastWritten.eventCode;
3585 cur.eventTag = cur.localEventTag;
3586 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003587 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003588 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003589 }
3590
Adam Lesinski45489782016-12-15 23:45:17 -08003591 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003592 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003593 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3594 // Clients can't deal with history buffers this large. This only
3595 // really happens when the device is on charger and interacted with
3596 // for long periods of time, like in retail mode. Since the device is
3597 // most likely charged, when unplugged, stats would have reset anyways.
3598 // Reset the stats and mark that we overflowed.
3599 // b/32540341
3600 resetAllStatsLocked();
3601
3602 // Mark that we want to set *OVERFLOW* event and the RESET:START
3603 // events.
3604 recordResetDueToOverflow = true;
3605
3606 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003607 if (!mHistoryOverflow) {
3608 mHistoryOverflow = true;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003609 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
3610 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003611 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003612 }
3613
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003614 // After overflow, we allow various bit-wise states to settle to 0.
3615 boolean writeAnyway = false;
3616 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3617 & mActiveHistoryStates;
3618 if (mHistoryLastWritten.states != curStates) {
3619 // mActiveHistoryStates keeps track of which bits in .states are now being
3620 // forced to 0.
3621 int old = mActiveHistoryStates;
3622 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3623 writeAnyway |= old != mActiveHistoryStates;
3624 }
3625 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3626 & mActiveHistoryStates2;
3627 if (mHistoryLastWritten.states2 != curStates2) {
3628 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3629 // forced to 0.
3630 int old = mActiveHistoryStates2;
3631 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3632 writeAnyway |= old != mActiveHistoryStates2;
3633 }
3634
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003635 // Once we've reached the maximum number of items, we only
3636 // record changes to the battery level and the most interesting states.
3637 // Once we've reached the maximum maximum number of items, we only
3638 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003639 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003640 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003641 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003642 & HistoryItem.MOST_INTERESTING_STATES) == 0
3643 || ((mHistoryLastWritten.states2^cur.states2)
3644 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003645 return;
3646 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003647
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003648 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003649 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003650 }
3651
Adam Lesinski45489782016-12-15 23:45:17 -08003652 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003653 // The history is currently empty; we need it to start with a time stamp.
3654 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003655 if (recordResetDueToOverflow) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003656 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Adam Lesinski45489782016-12-15 23:45:17 -08003657 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003658 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_RESET, cur);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003659 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003660 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003661 }
3662
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003663 private void addHistoryBufferLocked(long elapsedRealtimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003664 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003665 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003666 }
3667 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3668 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003669 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003670 mHistoryLastWritten.states &= mActiveHistoryStates;
3671 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003672 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003673 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003674 cur.wakelockTag = null;
3675 cur.wakeReasonTag = null;
3676 cur.eventCode = HistoryItem.EVENT_NONE;
3677 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003678 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3679 + " now " + mHistoryBuffer.dataPosition()
3680 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003681 }
3682
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003683 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003684 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003685
Dianne Hackborn40c87252014-03-19 16:55:40 -07003686 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003687 if (mTrackRunningHistoryElapsedRealtime != 0) {
3688 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3689 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3690 if (diffUptime < (diffElapsed-20)) {
3691 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3692 mHistoryAddTmp.setTo(mHistoryLastWritten);
3693 mHistoryAddTmp.wakelockTag = null;
3694 mHistoryAddTmp.wakeReasonTag = null;
3695 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3696 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003697 addHistoryRecordInnerLocked(wakeElapsedTime, mHistoryAddTmp);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003698 }
3699 }
3700 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3701 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3702 mTrackRunningHistoryUptime = uptimeMs;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003703 addHistoryRecordInnerLocked(elapsedRealtimeMs, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003704 }
3705
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003706 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, HistoryItem cur) {
3707 addHistoryBufferLocked(elapsedRealtimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003708
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003709 if (!USE_OLD_HISTORY) {
3710 return;
3711 }
3712
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003713 if (!mHaveBatteryLevel || !mRecordingHistory) {
3714 return;
3715 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003716
3717 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003718 // and no states have since the last recorded entry changed and
3719 // are now resetting back to their original value, then just collapse
3720 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003721 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003722 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003723 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3724 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003725 // If the current is the same as the one before, then we no
3726 // longer need the entry.
3727 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003728 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003729 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003730 mHistoryLastEnd.next = null;
3731 mHistoryEnd.next = mHistoryCache;
3732 mHistoryCache = mHistoryEnd;
3733 mHistoryEnd = mHistoryLastEnd;
3734 mHistoryLastEnd = null;
3735 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003736 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3737 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003738 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003739 }
3740 return;
3741 }
3742
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003743 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003744 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003745
3746 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3747 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003748 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003749 }
3750
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003751 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3752 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003753 // record changes to the battery level and the most interesting states.
3754 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003755 // record changes to the battery level.
3756 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003757 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003758 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003759 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003760 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003761 return;
3762 }
3763 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003764
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003765 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003766 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003767
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003768 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003769 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003770 mHistoryCur.eventCode = code;
3771 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3772 mHistoryCur.eventTag.string = name;
3773 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003774 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003775 }
3776
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003777 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003778 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003779 if (rec != null) {
3780 mHistoryCache = rec.next;
3781 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003782 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003783 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003784 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003785
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003786 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003787 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003788
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003789 void addHistoryRecordLocked(HistoryItem rec) {
3790 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003791 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003792 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003793 if (mHistoryEnd != null) {
3794 mHistoryEnd.next = rec;
3795 mHistoryEnd = rec;
3796 } else {
3797 mHistory = mHistoryEnd = rec;
3798 }
3799 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003800
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003801 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003802 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003803 if (USE_OLD_HISTORY) {
3804 if (mHistory != null) {
3805 mHistoryEnd.next = mHistoryCache;
3806 mHistoryCache = mHistory;
3807 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3808 }
3809 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003810 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003811
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003812 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003813 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003814 mTrackRunningHistoryElapsedRealtime = 0;
3815 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003816
3817 mHistoryBuffer.setDataSize(0);
3818 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003819 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003820 mHistoryLastLastWritten.clear();
3821 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003822 mHistoryTagPool.clear();
3823 mNextHistoryTagIdx = 0;
3824 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003825 mHistoryBufferLastPos = -1;
3826 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003827 mActiveHistoryStates = 0xffffffff;
3828 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003829 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003830
Mike Mac2f518a2017-09-19 16:06:03 -07003831 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003832 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003833 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003834 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3835 final boolean updateOnBatteryScreenOffTimeBase =
3836 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003837
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003838 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3839 if (updateOnBatteryScreenOffTimeBase) {
3840 updateKernelWakelocksLocked();
3841 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003842 }
Bookatz82b341172017-09-07 19:06:08 -07003843 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3844 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3845 // improved, remove the surrounding if{}.
3846 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3847 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3848 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003849 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003850 Slog.d(TAG, "Updating cpu time because screen is now "
3851 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003852 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003853 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -07003854 updateCpuTimeLocked();
Sudheer Shankae544d162017-12-28 17:06:20 -08003855 mExternalSync.scheduleCopyFromAllUidsCpuTimes(mOnBatteryTimeBase.isRunning(),
3856 mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003857
3858 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07003859 if (updateOnBatteryTimeBase) {
3860 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3861 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003862 }
Mike Mac2f518a2017-09-19 16:06:03 -07003863 }
3864 if (updateOnBatteryScreenOffTimeBase) {
3865 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
3866 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3867 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003868 }
Bookatzc8c44962017-05-11 12:12:54 -07003869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 }
3871 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003872
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003873 private void updateBatteryPropertiesLocked() {
3874 try {
3875 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
3876 ServiceManager.getService("batteryproperties"));
3877 registrar.scheduleUpdate();
3878 } catch (RemoteException e) {
3879 // Ignore.
3880 }
3881 }
3882
Dianne Hackborn099bc622014-01-22 13:39:16 -08003883 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
3884 mIsolatedUids.put(isolatedUid, appUid);
Bookatz90867622018-01-31 15:05:57 -08003885 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid,
3886 StatsLog.ISOLATED_UID_CHANGED__EVENT__CREATED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003887 final Uid u = getUidStatsLocked(appUid);
3888 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003889 }
3890
Adam Lesinski61db88f2015-07-01 15:05:07 -07003891 /**
3892 * Schedules a read of the latest cpu times before removing the isolated UID.
3893 * @see #removeIsolatedUidLocked(int)
3894 */
3895 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003896 int curUid = mIsolatedUids.get(isolatedUid, -1);
3897 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07003898 if (mExternalSync != null) {
3899 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
3900 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08003901 }
3902 }
3903
Adam Lesinski61db88f2015-07-01 15:05:07 -07003904 /**
3905 * This should only be called after the cpu times have been read.
3906 * @see #scheduleRemoveIsolatedUidLocked(int, int)
3907 */
3908 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003909 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08003910 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1),
3911 isolatedUid, StatsLog.ISOLATED_UID_CHANGED__EVENT__REMOVED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003912 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
3913 if (idx >= 0) {
3914 final int ownerUid = mIsolatedUids.valueAt(idx);
3915 final Uid u = getUidStatsLocked(ownerUid);
3916 u.removeIsolatedUid(isolatedUid);
3917 mIsolatedUids.removeAt(idx);
3918 }
3919 mKernelUidCpuTimeReader.removeUid(isolatedUid);
3920 mKernelUidCpuFreqTimeReader.removeUid(isolatedUid);
Mike Mafae87da2018-01-19 20:07:20 -08003921 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
3922 mKernelUidCpuActiveTimeReader.removeUid(isolatedUid);
3923 mKernelUidCpuClusterTimeReader.removeUid(isolatedUid);
3924 }
Adam Lesinski61db88f2015-07-01 15:05:07 -07003925 }
3926
Dianne Hackborn099bc622014-01-22 13:39:16 -08003927 public int mapUid(int uid) {
3928 int isolated = mIsolatedUids.get(uid, -1);
3929 return isolated > 0 ? isolated : uid;
3930 }
3931
3932 public void noteEventLocked(int code, String name, int uid) {
3933 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003934 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3935 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003936 }
Joe Onoratoabded112016-02-08 16:49:39 -08003937 final long elapsedRealtime = mClocks.elapsedRealtime();
3938 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003939 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003940 }
3941
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003942 boolean ensureStartClockTime(final long currentTime) {
3943 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
3944 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
3945 // If the start clock time has changed by more than a year, then presumably
3946 // the previous time was completely bogus. So we are going to figure out a
3947 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08003948 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003949 return true;
3950 }
3951 return false;
3952 }
3953
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003954 public void noteCurrentTimeChangedLocked() {
3955 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003956 final long elapsedRealtime = mClocks.elapsedRealtime();
3957 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003958 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003959 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003960 }
3961
Dianne Hackborn61659e52014-07-09 16:13:01 -07003962 public void noteProcessStartLocked(String name, int uid) {
3963 uid = mapUid(uid);
3964 if (isOnBattery()) {
3965 Uid u = getUidStatsLocked(uid);
3966 u.getProcessStatsLocked(name).incStartsLocked();
3967 }
3968 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3969 return;
3970 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003971 if (!mRecordAllHistory) {
3972 return;
3973 }
Joe Onoratoabded112016-02-08 16:49:39 -08003974 final long elapsedRealtime = mClocks.elapsedRealtime();
3975 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07003976 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
3977 }
3978
Dianne Hackborn1e01d162014-12-04 17:46:42 -08003979 public void noteProcessCrashLocked(String name, int uid) {
3980 uid = mapUid(uid);
3981 if (isOnBattery()) {
3982 Uid u = getUidStatsLocked(uid);
3983 u.getProcessStatsLocked(name).incNumCrashesLocked();
3984 }
3985 }
3986
3987 public void noteProcessAnrLocked(String name, int uid) {
3988 uid = mapUid(uid);
3989 if (isOnBattery()) {
3990 Uid u = getUidStatsLocked(uid);
3991 u.getProcessStatsLocked(name).incNumAnrsLocked();
3992 }
3993 }
3994
Dianne Hackborna8d10942015-11-19 17:55:19 -08003995 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07003996 int parentUid = mapUid(uid);
3997 if (uid != parentUid) {
3998 // Isolated UIDs process state is already rolled up into parent, so no need to track
3999 // Otherwise the parent's process state will get downgraded incorrectly
4000 return;
4001 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08004002 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004003 }
4004
4005 public void noteProcessFinishLocked(String name, int uid) {
4006 uid = mapUid(uid);
4007 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4008 return;
4009 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004010 if (!mRecordAllHistory) {
4011 return;
4012 }
Joe Onoratoabded112016-02-08 16:49:39 -08004013 final long elapsedRealtime = mClocks.elapsedRealtime();
4014 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004015 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004016 }
4017
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004018 public void noteSyncStartLocked(String name, int uid) {
4019 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004020 final long elapsedRealtime = mClocks.elapsedRealtime();
4021 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004022 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4023 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4024 return;
4025 }
4026 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4027 }
4028
4029 public void noteSyncFinishLocked(String name, int uid) {
4030 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004031 final long elapsedRealtime = mClocks.elapsedRealtime();
4032 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004033 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4034 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4035 return;
4036 }
4037 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4038 }
4039
4040 public void noteJobStartLocked(String name, int uid) {
4041 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004042 final long elapsedRealtime = mClocks.elapsedRealtime();
4043 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004044 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4045 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4046 return;
4047 }
4048 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4049 }
4050
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004051 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004052 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004053 final long elapsedRealtime = mClocks.elapsedRealtime();
4054 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004055 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004056 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4057 return;
4058 }
4059 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4060 }
4061
Narayan Kamath695cf722017-12-21 18:32:47 +00004062 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4063 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004064 }
4065
Narayan Kamath695cf722017-12-21 18:32:47 +00004066 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4067 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4068 }
4069
4070 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4071 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004072 if (!mRecordAllHistory) {
4073 return;
4074 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004075
Joe Onoratoabded112016-02-08 16:49:39 -08004076 final long elapsedRealtime = mClocks.elapsedRealtime();
4077 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004078
4079 if (workSource != null) {
4080 for (int i = 0; i < workSource.size(); ++i) {
4081 uid = mapUid(workSource.get(i));
4082 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4083 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4084 }
4085 }
4086
4087 List<WorkChain> workChains = workSource.getWorkChains();
4088 if (workChains != null) {
4089 for (int i = 0; i < workChains.size(); ++i) {
4090 uid = mapUid(workChains.get(i).getAttributionUid());
4091 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4092 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4093 }
4094 }
4095 }
4096 } else {
4097 uid = mapUid(uid);
4098
4099 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4100 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4101 }
4102 }
4103 }
4104
4105 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4106 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004107 if (workSource != null) {
4108 for (int i = 0; i < workSource.size(); ++i) {
4109 uid = workSource.get(i);
4110 final String workSourceName = workSource.getName(i);
4111
Tej Singh6f724c42018-01-03 20:02:03 -08004112 if (isOnBattery()) {
4113 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4114 workSourceName != null ? workSourceName : packageName);
4115 pkg.noteWakeupAlarmLocked(tag);
4116 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004117 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4118 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004119 }
4120
4121 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4122 if (workChains != null) {
4123 for (int i = 0; i < workChains.size(); ++i) {
4124 final WorkChain wc = workChains.get(i);
4125 uid = wc.getAttributionUid();
4126
Tej Singh6f724c42018-01-03 20:02:03 -08004127 if (isOnBattery()) {
4128 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4129 pkg.noteWakeupAlarmLocked(tag);
4130 }
Yangster-macafad8c62018-01-05 22:30:49 -08004131 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004132 }
4133 }
4134 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004135 if (isOnBattery()) {
4136 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4137 pkg.noteWakeupAlarmLocked(tag);
4138 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004139 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004140 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004141 }
4142
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004143 private void requestWakelockCpuUpdate() {
4144 if (!mHandler.hasMessages(MSG_UPDATE_WAKELOCKS)) {
4145 Message m = mHandler.obtainMessage(MSG_UPDATE_WAKELOCKS);
4146 mHandler.sendMessageDelayed(m, DELAY_UPDATE_WAKELOCKS);
4147 }
4148 }
4149
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004150 private void requestImmediateCpuUpdate() {
4151 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
4152 mHandler.sendEmptyMessage(MSG_UPDATE_WAKELOCKS);
4153 }
4154
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004155 public void setRecordAllHistoryLocked(boolean enabled) {
4156 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004157 if (!enabled) {
4158 // Clear out any existing state.
4159 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004160 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004161 // Record the currently running processes as stopping, now that we are no
4162 // longer tracking them.
4163 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4164 HistoryItem.EVENT_PROC);
4165 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004166 long mSecRealtime = mClocks.elapsedRealtime();
4167 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004168 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4169 SparseIntArray uids = ent.getValue();
4170 for (int j=0; j<uids.size(); j++) {
4171 addHistoryEventLocked(mSecRealtime, mSecUptime,
4172 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4173 }
4174 }
4175 }
4176 } else {
4177 // Record the currently running processes as starting, now that we are tracking them.
4178 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4179 HistoryItem.EVENT_PROC);
4180 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004181 long mSecRealtime = mClocks.elapsedRealtime();
4182 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004183 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4184 SparseIntArray uids = ent.getValue();
4185 for (int j=0; j<uids.size(); j++) {
4186 addHistoryEventLocked(mSecRealtime, mSecUptime,
4187 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4188 }
4189 }
4190 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004191 }
4192 }
4193
Dianne Hackborn9a755432014-05-15 17:05:22 -07004194 public void setNoAutoReset(boolean enabled) {
4195 mNoAutoReset = enabled;
4196 }
4197
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004198 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004199 if (mPretendScreenOff != pretendScreenOff) {
4200 mPretendScreenOff = pretendScreenOff;
4201 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4202 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004203 }
4204
Dianne Hackborn9a755432014-05-15 17:05:22 -07004205 private String mInitialAcquireWakeName;
4206 private int mInitialAcquireWakeUid = -1;
4207
Narayan Kamath81822022017-12-08 11:56:01 +00004208 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4209 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004210 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004211 if (type == WAKE_TYPE_PARTIAL) {
4212 // Only care about partial wake locks, since full wake locks
4213 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004214 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004215 if (historyName == null) {
4216 historyName = name;
4217 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004218 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004219 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4220 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004221 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004222 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004223 }
4224 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004225 if (mWakeLockNesting == 0) {
4226 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4227 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4228 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004229 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004230 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004231 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004232 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004233 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004234 } else if (!mWakeLockImportant && !unimportantForLogging
4235 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004236 if (mHistoryLastWritten.wakelockTag != null) {
4237 // We'll try to update the last tag.
4238 mHistoryLastWritten.wakelockTag = null;
4239 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004240 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004241 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004242 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004243 }
4244 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004245 }
4246 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004247 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004248 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004249 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4250 // We only update the cpu time when a wake lock is acquired if the screen is off.
4251 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4252 if (DEBUG_ENERGY_CPU) {
4253 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4254 }
4255 requestWakelockCpuUpdate();
4256 }
Narayan Kamath81822022017-12-08 11:56:01 +00004257
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004258 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004259
Yangster-mac20877162017-12-22 17:19:39 -08004260 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004261 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004262 getPowerManagerWakeLockLevel(type), name,
4263 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Yangster-macafad8c62018-01-05 22:30:49 -08004264 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004265 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004266 getPowerManagerWakeLockLevel(type), name,
4267 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Narayan Kamath81822022017-12-08 11:56:01 +00004268 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004269 }
4270 }
4271
Narayan Kamath81822022017-12-08 11:56:01 +00004272 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4273 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004274 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004275 if (type == WAKE_TYPE_PARTIAL) {
4276 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004277 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004278 if (historyName == null) {
4279 historyName = name;
4280 }
4281 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4282 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004283 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004284 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004285 }
4286 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004287 if (mWakeLockNesting == 0) {
4288 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4289 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4290 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004291 mInitialAcquireWakeName = null;
4292 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004293 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004294 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004295 }
4296 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004297 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4298 if (DEBUG_ENERGY_CPU) {
4299 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4300 }
4301 requestWakelockCpuUpdate();
4302 }
Narayan Kamath81822022017-12-08 11:56:01 +00004303
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004304 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004305 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004306 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004307 getPowerManagerWakeLockLevel(type), name,
4308 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Yangster-macafad8c62018-01-05 22:30:49 -08004309 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004310 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004311 getPowerManagerWakeLockLevel(type), name,
4312 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Narayan Kamath81822022017-12-08 11:56:01 +00004313 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004314 }
4315 }
4316
Bookatz1a1b0462018-01-12 11:47:03 -08004317 /**
4318 * Converts BatteryStats wakelock types back into PowerManager wakelock levels.
4319 * This is the inverse map of Notifier.getBatteryStatsWakeLockMonitorType().
4320 * These are estimations, since batterystats loses some of the original data.
4321 * TODO: Delete this. Instead, StatsLog.write should be called from PowerManager's Notifier.
4322 */
4323 private int getPowerManagerWakeLockLevel(int battertStatsWakelockType) {
4324 switch (battertStatsWakelockType) {
4325 // PowerManager.PARTIAL_WAKE_LOCK or PROXIMITY_SCREEN_OFF_WAKE_LOCK
4326 case BatteryStats.WAKE_TYPE_PARTIAL:
4327 return PowerManager.PARTIAL_WAKE_LOCK;
4328
4329 // PowerManager.SCREEN_DIM_WAKE_LOCK or SCREEN_BRIGHT_WAKE_LOCK
4330 case BatteryStats.WAKE_TYPE_FULL:
4331 return PowerManager.FULL_WAKE_LOCK;
4332
4333 case BatteryStats.WAKE_TYPE_DRAW:
4334 return PowerManager.DRAW_WAKE_LOCK;
4335
4336 // It appears that nothing can ever make a Window and PowerManager lacks an equivalent.
4337 case BatteryStats.WAKE_TYPE_WINDOW:
4338 Slog.e(TAG, "Illegal window wakelock type observed in batterystats.");
4339 return -1;
4340
4341 default:
4342 Slog.e(TAG, "Illegal wakelock type in batterystats: " + battertStatsWakelockType);
4343 return -1;
4344 }
4345 }
4346
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004347 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4348 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004349 final long elapsedRealtime = mClocks.elapsedRealtime();
4350 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004351 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004352 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004353 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4354 unimportantForLogging, elapsedRealtime, uptime);
4355 }
4356
4357 List<WorkChain> wcs = ws.getWorkChains();
4358 if (wcs != null) {
4359 for (int i = 0; i < wcs.size(); ++i) {
4360 final WorkChain wc = wcs.get(i);
4361 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4362 unimportantForLogging, elapsedRealtime, uptime);
4363 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004364 }
4365 }
4366
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004367 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4368 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004369 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004370 final long elapsedRealtime = mClocks.elapsedRealtime();
4371 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004372
4373 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4374
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004375 // For correct semantics, we start the need worksources first, so that we won't
4376 // make inappropriate history items as if all wake locks went away and new ones
4377 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004378 //
4379 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004380 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004381 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004382 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004383 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004384 }
Narayan Kamath81822022017-12-08 11:56:01 +00004385 if (wcs != null) {
4386 List<WorkChain> newChains = wcs[0];
4387 if (newChains != null) {
4388 for (int i = 0; i < newChains.size(); ++i) {
4389 final WorkChain newChain = newChains.get(i);
4390 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4391 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4392 uptime);
4393 }
4394 }
4395 }
4396
4397 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004398 final int NO = ws.size();
4399 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004400 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4401 uptime);
4402 }
4403 if (wcs != null) {
4404 List<WorkChain> goneChains = wcs[1];
4405 if (goneChains != null) {
4406 for (int i = 0; i < goneChains.size(); ++i) {
4407 final WorkChain goneChain = goneChains.get(i);
4408 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4409 historyName, type, elapsedRealtime, uptime);
4410 }
4411 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004412 }
4413 }
4414
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004415 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4416 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004417 final long elapsedRealtime = mClocks.elapsedRealtime();
4418 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004419 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004420 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004421 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4422 uptime);
4423 }
4424
4425 List<WorkChain> wcs = ws.getWorkChains();
4426 if (wcs != null) {
4427 for (int i = 0; i < wcs.size(); ++i) {
4428 final WorkChain wc = wcs.get(i);
4429 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4430 elapsedRealtime, uptime);
4431 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004432 }
4433 }
4434
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004435 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004436 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004437 uid, null, name, historyName,
4438 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08004439
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004440 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004441 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004442 }
4443
4444 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4445 WorkSource workSource) {
4446 final int N = workSource.size();
4447 for (int i = 0; i < N; ++i) {
4448 final int uid = mapUid(workSource.get(i));
4449 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004450 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004451 workSource.get(i), workSource.getName(i), name, historyName,
4452 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004453 }
4454
4455 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4456 if (workChains != null) {
4457 for (int i = 0; i < workChains.size(); ++i) {
4458 final WorkChain workChain = workChains.get(i);
4459 final int uid = workChain.getAttributionUid();
4460 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4461
Yangster-macafad8c62018-01-05 22:30:49 -08004462 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004463 workChain.getUids(), workChain.getTags(), name, historyName,
4464 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004465 }
4466 }
4467 }
4468
4469 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004470 final long elapsedRealtime = mClocks.elapsedRealtime();
4471 final long uptime = mClocks.uptimeMillis();
4472 if (historyName == null) {
4473 historyName = name;
4474 }
4475 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4476 0)) {
4477 return;
4478 }
4479 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4480 historyName, uid);
4481 }
4482
4483 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Bookatz90867622018-01-31 15:05:57 -08004484 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, null,
4485 name, historyName, StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08004486
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004487 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004488 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004489 }
4490
4491 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4492 WorkSource workSource) {
4493 final int N = workSource.size();
4494 for (int i = 0; i < N; ++i) {
4495 final int uid = mapUid(workSource.get(i));
4496 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004497 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004498 workSource.get(i), workSource.getName(i), name, historyName,
4499 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004500 }
4501
4502 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4503 if (workChains != null) {
4504 for (int i = 0; i < workChains.size(); ++i) {
4505 final WorkChain workChain = workChains.get(i);
4506 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004507 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004508 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004509 workChain.getUids(), workChain.getTags(), name, historyName,
4510 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004511 }
4512 }
4513 }
4514
4515 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004516 final long elapsedRealtime = mClocks.elapsedRealtime();
4517 final long uptime = mClocks.uptimeMillis();
4518 if (historyName == null) {
4519 historyName = name;
4520 }
4521 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4522 0)) {
4523 return;
4524 }
4525 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4526 historyName, uid);
4527 }
4528
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004529 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4530 if (mLastWakeupReason != null) {
4531 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004532 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004533 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz90867622018-01-31 15:05:57 -08004534 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
4535 /* duration_usec */ deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004536 mLastWakeupReason = null;
4537 }
4538 }
4539
4540 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004541 final long elapsedRealtime = mClocks.elapsedRealtime();
4542 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004543 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004544 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004545 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004546 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4547 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004548 mHistoryCur.wakeReasonTag.uid = 0;
4549 mLastWakeupReason = reason;
4550 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004551 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004552 }
4553
Adam Lesinski72478f02015-06-17 15:39:43 -07004554 public boolean startAddingCpuLocked() {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004555 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
Adam Lesinski72478f02015-06-17 15:39:43 -07004556 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004557 }
4558
Adam Lesinski72478f02015-06-17 15:39:43 -07004559 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4560 int statSystemTime, int statIOWaitTime, int statIrqTime,
4561 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004562 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4563 + " user=" + statUserTime + " sys=" + statSystemTime
4564 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4565 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4566 mCurStepCpuUserTime += totalUTime;
4567 mCurStepCpuSystemTime += totalSTime;
4568 mCurStepStatUserTime += statUserTime;
4569 mCurStepStatSystemTime += statSystemTime;
4570 mCurStepStatIOWaitTime += statIOWaitTime;
4571 mCurStepStatIrqTime += statIrqTime;
4572 mCurStepStatSoftIrqTime += statSoftIrqTime;
4573 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004574 }
4575
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004576 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004577 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004578 Uid u = mUidStats.get(uid);
4579 if (u != null) {
4580 u.mPids.remove(pid);
4581 }
4582 }
4583
4584 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004585 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004586 Uid u = mUidStats.get(uid);
4587 if (u != null) {
4588 Uid.Pid p = u.mPids.get(pid);
4589 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004590 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004591 }
4592 }
4593 return 0;
4594 }
4595
Dianne Hackborn287952c2010-09-22 22:34:31 -07004596 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004597 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004598 Uid u = mUidStats.get(uid);
4599 if (u != null) {
4600 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4601 }
4602 }
4603
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004604 int mSensorNesting;
4605
4606 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004607 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004608 final long elapsedRealtime = mClocks.elapsedRealtime();
4609 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004610 if (mSensorNesting == 0) {
4611 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4612 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4613 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004614 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004615 }
4616 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004617 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004618 }
4619
4620 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004621 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004622 final long elapsedRealtime = mClocks.elapsedRealtime();
4623 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004624 mSensorNesting--;
4625 if (mSensorNesting == 0) {
4626 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4627 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4628 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004629 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004630 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004631 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004632 }
4633
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004634 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004635
Narayan Kamath32684dd2018-01-08 17:32:51 +00004636 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4637 for (int i = 0; i < newWs.size(); ++i) {
4638 noteStartGpsLocked(newWs.get(i), null);
4639 }
4640
4641 for (int i = 0; i < oldWs.size(); ++i) {
4642 noteStopGpsLocked((oldWs.get(i)), null);
4643 }
4644
4645 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4646 if (wcs != null) {
4647 if (wcs[0] != null) {
4648 final List<WorkChain> newChains = wcs[0];
4649 for (int i = 0; i < newChains.size(); ++i) {
4650 noteStartGpsLocked(-1, newChains.get(i));
4651 }
4652 }
4653
4654 if (wcs[1] != null) {
4655 final List<WorkChain> goneChains = wcs[1];
4656 for (int i = 0; i < goneChains.size(); ++i) {
4657 noteStopGpsLocked(-1, goneChains.get(i));
4658 }
4659 }
4660 }
4661 }
4662
4663 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4664 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004665 final long elapsedRealtime = mClocks.elapsedRealtime();
4666 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004667 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004668 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004669 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4670 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004671 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004672 }
4673 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004674
4675 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004676 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4677 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004678 } else {
4679 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004680 workChain.getUids(), workChain.getTags(),
4681 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004682 }
4683
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004684 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004685 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004686
Narayan Kamath32684dd2018-01-08 17:32:51 +00004687 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4688 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004689 final long elapsedRealtime = mClocks.elapsedRealtime();
4690 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004691 mGpsNesting--;
4692 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004693 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004694 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4695 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004696 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004697 stopAllGpsSignalQualityTimersLocked(-1);
4698 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004699 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004700
4701 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004702 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4703 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004704 } else {
4705 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08004706 workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004707 }
4708
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004709 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004710 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004711
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004712 public void noteGpsSignalQualityLocked(int signalLevel) {
4713 if (mGpsNesting == 0) {
4714 return;
4715 }
4716 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4717 stopAllGpsSignalQualityTimersLocked(-1);
4718 return;
4719 }
4720 final long elapsedRealtime = mClocks.elapsedRealtime();
4721 final long uptime = mClocks.uptimeMillis();
4722 if (mGpsSignalQualityBin != signalLevel) {
4723 if (mGpsSignalQualityBin >= 0) {
4724 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4725 }
4726 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4727 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4728 }
4729 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4730 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4731 addHistoryRecordLocked(elapsedRealtime, uptime);
4732 mGpsSignalQualityBin = signalLevel;
4733 }
4734 return;
4735 }
4736
Jeff Browne95c3cd2014-05-02 16:59:26 -07004737 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004738 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004739
4740 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4741 // original 4 are mapped to one of the originals.
4742 if (state > MAX_TRACKED_SCREEN_STATE) {
4743 switch (state) {
4744 case Display.STATE_VR:
4745 state = Display.STATE_ON;
4746 break;
4747 default:
4748 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4749 break;
4750 }
4751 }
4752
Jeff Browne95c3cd2014-05-02 16:59:26 -07004753 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004754 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004755 final int oldState = mScreenState;
4756 mScreenState = state;
4757 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4758 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004759
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004760 if (state != Display.STATE_UNKNOWN) {
4761 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004762 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4763 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4764 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004765 } else {
4766 Slog.wtf(TAG, "Unexpected screen state: " + state);
4767 }
4768 }
4769
Mike Mac2f518a2017-09-19 16:06:03 -07004770 final long elapsedRealtime = mClocks.elapsedRealtime();
4771 final long uptime = mClocks.uptimeMillis();
4772
4773 boolean updateHistory = false;
4774 if (isScreenDoze(state)) {
4775 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4776 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4777 updateHistory = true;
4778 } else if (isScreenDoze(oldState)) {
4779 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4780 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4781 updateHistory = true;
4782 }
4783 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004784 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4785 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4786 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004787 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4788 if (mScreenBrightnessBin >= 0) {
4789 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4790 }
Mike Mac2f518a2017-09-19 16:06:03 -07004791 updateHistory = true;
4792 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004793 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4794 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4795 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004796 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4797 if (mScreenBrightnessBin >= 0) {
4798 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4799 }
Mike Mac2f518a2017-09-19 16:06:03 -07004800 updateHistory = true;
4801 }
4802 if (updateHistory) {
4803 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4804 + Display.stateToString(state));
4805 addHistoryRecordLocked(elapsedRealtime, uptime);
4806 }
4807 if (isScreenOn(state)) {
4808 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4809 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4810 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004811 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004812 elapsedRealtime, uptime);
4813 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004814 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004815 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004816 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004817 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004818 }
4819 // Update discharge amounts.
4820 if (mOnBatteryInternal) {
4821 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004822 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004823 }
4824 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004825
Dianne Hackborn617f8772009-03-31 15:04:46 -07004826 public void noteScreenBrightnessLocked(int brightness) {
4827 // Bin the brightness.
4828 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4829 if (bin < 0) bin = 0;
4830 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4831 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004832 final long elapsedRealtime = mClocks.elapsedRealtime();
4833 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004834 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4835 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004836 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4837 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004838 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004839 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004840 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004841 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004842 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004843 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004844 }
4845 mScreenBrightnessBin = bin;
4846 }
4847 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004848
Dianne Hackborn617f8772009-03-31 15:04:46 -07004849 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004850 if (mOnBatteryInternal) {
4851 uid = mapUid(uid);
4852 getUidStatsLocked(uid).noteUserActivityLocked(event);
4853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004854 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004855
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004856 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004857 final long elapsedRealtime = mClocks.elapsedRealtime();
4858 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004859 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4860 reason, reasonUid);
4861 }
4862
Jeff Browne95c3cd2014-05-02 16:59:26 -07004863 public void noteInteractiveLocked(boolean interactive) {
4864 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08004865 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004866 mInteractive = interactive;
4867 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
4868 if (interactive) {
4869 mInteractiveTimer.startRunningLocked(elapsedRealtime);
4870 } else {
4871 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
4872 }
4873 }
4874 }
4875
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004876 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004877 final long elapsedRealtime = mClocks.elapsedRealtime();
4878 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004879 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4880 extra, type);
4881 mNumConnectivityChange++;
4882 }
4883
Adam Lesinski5f056f62016-07-14 16:56:08 -07004884 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4885 final long uptimeMillis, int uid) {
4886 uid = mapUid(uid);
4887 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4888 uid);
4889 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4890 }
4891
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004892 /**
4893 * Updates the radio power state and returns true if an external stats collection should occur.
4894 */
4895 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004896 final long elapsedRealtime = mClocks.elapsedRealtime();
4897 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004898 if (mMobileRadioPowerState != powerState) {
4899 long realElapsedRealtimeMs;
4900 final boolean active =
4901 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4902 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4903 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004904 if (uid > 0) {
4905 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4906 }
4907
Adam Lesinski9acfd812016-04-19 18:29:50 -07004908 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004909 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4910 } else {
4911 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004912 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004913 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4914 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4915 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004916 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004917 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4918 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4919 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004920 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004921 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4922 }
4923 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4924 + Integer.toHexString(mHistoryCur.states));
4925 addHistoryRecordLocked(elapsedRealtime, uptime);
4926 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08004927 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004928 if (active) {
4929 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4930 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4931 } else {
4932 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004933 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004934 // Tell the caller to collect radio network/power stats.
4935 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004936 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004937 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004938 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004939 }
4940
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004941 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004942 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004943 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4944 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4945 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004946 final long elapsedRealtime = mClocks.elapsedRealtime();
4947 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004948 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004949 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004950 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4951 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004952 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004953 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004954 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004955 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4956 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004957 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004958 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004959 }
4960 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatz90867622018-01-31 15:05:57 -08004961 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
4962 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
4963 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004964 }
4965 }
4966
Bookatzddccf0a2017-11-28 16:48:14 -08004967 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004968 final long elapsedRealtime = mClocks.elapsedRealtime();
4969 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004970 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004971 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004972 // We don't go out of general idling mode until explicitly taken out of
4973 // device idle through going active or significant motion.
4974 nowIdling = true;
4975 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004976 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
4977 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
4978 // We don't go out of general light idling mode until explicitly taken out of
4979 // device idle through going active or significant motion.
4980 nowLightIdling = true;
4981 }
4982 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
4983 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
4984 activeReason, activeUid);
4985 }
Bookatzddccf0a2017-11-28 16:48:14 -08004986 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
4987 int statsmode;
4988 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
4989 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
4990 else statsmode = DEVICE_IDLE_MODE_OFF;
4991 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
4992 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004993 if (mDeviceIdling != nowIdling) {
4994 mDeviceIdling = nowIdling;
4995 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
4996 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
4997 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004998 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004999 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
5000 } else {
5001 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
5002 }
5003 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005004 if (mDeviceLightIdling != nowLightIdling) {
5005 mDeviceLightIdling = nowLightIdling;
5006 if (nowLightIdling) {
5007 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005008 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005009 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005010 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005011 }
5012 if (mDeviceIdleMode != mode) {
5013 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
5014 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
5015 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
5016 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005017 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005018 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
5019 mLastIdleTimeStart = elapsedRealtime;
5020 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
5021 if (lastDuration > mLongestLightIdleTime) {
5022 mLongestLightIdleTime = lastDuration;
5023 }
5024 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005025 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005026 if (lastDuration > mLongestFullIdleTime) {
5027 mLongestFullIdleTime = lastDuration;
5028 }
5029 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
5030 }
5031 if (mode == DEVICE_IDLE_MODE_LIGHT) {
5032 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005033 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005034 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
5035 }
5036 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08005037 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005038 }
5039 }
5040
Dianne Hackborn3accca02013-09-20 09:32:11 -07005041 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08005042 final long elapsedRealtime = mClocks.elapsedRealtime();
5043 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07005044 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005045 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07005046 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005047 PackageChange pc = new PackageChange();
5048 pc.mPackageName = pkgName;
5049 pc.mUpdate = true;
5050 pc.mVersionCode = versionCode;
5051 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005052 }
5053
5054 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005055 final long elapsedRealtime = mClocks.elapsedRealtime();
5056 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005057 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5058 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005059 PackageChange pc = new PackageChange();
5060 pc.mPackageName = pkgName;
5061 pc.mUpdate = true;
5062 addPackageChange(pc);
5063 }
5064
5065 private void addPackageChange(PackageChange pc) {
5066 if (mDailyPackageChanges == null) {
5067 mDailyPackageChanges = new ArrayList<>();
5068 }
5069 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005070 }
5071
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005072 void stopAllGpsSignalQualityTimersLocked(int except) {
5073 final long elapsedRealtime = mClocks.elapsedRealtime();
5074 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5075 if (i == except) {
5076 continue;
5077 }
5078 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5079 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5080 }
5081 }
5082 }
5083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005084 public void notePhoneOnLocked() {
5085 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005086 final long elapsedRealtime = mClocks.elapsedRealtime();
5087 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005088 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005089 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5090 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005091 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005093 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 }
5095 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005097 public void notePhoneOffLocked() {
5098 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005099 final long elapsedRealtime = mClocks.elapsedRealtime();
5100 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005101 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005102 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5103 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005104 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005105 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005106 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005107 }
5108 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005109
Dianne Hackborn3251b902014-06-20 14:40:53 -07005110 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005111 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005112 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005113 if (i == except) {
5114 continue;
5115 }
5116 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005117 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005118 }
5119 }
5120 }
5121
Dianne Hackborne4a59512010-12-07 11:08:07 -08005122 private int fixPhoneServiceState(int state, int signalBin) {
5123 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5124 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5125 // to infer that we are scanning from other data.
5126 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005127 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005128 state = ServiceState.STATE_IN_SERVICE;
5129 }
5130 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005131
Dianne Hackborne4a59512010-12-07 11:08:07 -08005132 return state;
5133 }
5134
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005135 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005136 boolean scanning = false;
5137 boolean newHistory = false;
5138
5139 mPhoneServiceStateRaw = state;
5140 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005141 mPhoneSignalStrengthBinRaw = strengthBin;
5142
Joe Onoratoabded112016-02-08 16:49:39 -08005143 final long elapsedRealtime = mClocks.elapsedRealtime();
5144 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005145
5146 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5147 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5148 // to infer that we are scanning from other data.
5149 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005150 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005151 state = ServiceState.STATE_IN_SERVICE;
5152 }
5153 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005154
5155 // If the phone is powered off, stop all timers.
5156 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005157 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005158
Dianne Hackborne4a59512010-12-07 11:08:07 -08005159 // If we are in service, make sure the correct signal string timer is running.
5160 } else if (state == ServiceState.STATE_IN_SERVICE) {
5161 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005162
5163 // If we're out of service, we are in the lowest signal strength
5164 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005165 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005166 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005167 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005168 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005169 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005170 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005171 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5172 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005173 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005174 }
5175 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005176
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005177 if (!scanning) {
5178 // If we are no longer scanning, then stop the scanning timer.
5179 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5180 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5181 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5182 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005183 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005184 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005185 }
5186 }
5187
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005188 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005189 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5190 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005191 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005192 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005193 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005194 mPhoneServiceState = state;
5195 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005196
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005197 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005198 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005199 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005200 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005201 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005202 if (strengthBin >= 0) {
5203 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005204 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005205 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005206 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5207 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005208 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005209 + Integer.toHexString(mHistoryCur.states));
5210 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005211 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005212 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005213 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005214 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005215 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005216 }
5217
5218 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005219 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005220 }
5221 }
5222
5223 /**
5224 * Telephony stack updates the phone state.
5225 * @param state phone state from ServiceState.getState()
5226 */
5227 public void notePhoneStateLocked(int state, int simState) {
5228 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005229 }
5230
Wink Savillee9b06d72009-05-18 21:47:50 -07005231 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005232 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005233 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005234 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005235 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005236
Dianne Hackborn627bba72009-03-24 22:32:56 -07005237 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
5238 int bin = DATA_CONNECTION_NONE;
5239 if (hasData) {
5240 switch (dataType) {
5241 case TelephonyManager.NETWORK_TYPE_EDGE:
5242 bin = DATA_CONNECTION_EDGE;
5243 break;
5244 case TelephonyManager.NETWORK_TYPE_GPRS:
5245 bin = DATA_CONNECTION_GPRS;
5246 break;
5247 case TelephonyManager.NETWORK_TYPE_UMTS:
5248 bin = DATA_CONNECTION_UMTS;
5249 break;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005250 case TelephonyManager.NETWORK_TYPE_CDMA:
5251 bin = DATA_CONNECTION_CDMA;
5252 break;
5253 case TelephonyManager.NETWORK_TYPE_EVDO_0:
5254 bin = DATA_CONNECTION_EVDO_0;
5255 break;
5256 case TelephonyManager.NETWORK_TYPE_EVDO_A:
5257 bin = DATA_CONNECTION_EVDO_A;
5258 break;
5259 case TelephonyManager.NETWORK_TYPE_1xRTT:
5260 bin = DATA_CONNECTION_1xRTT;
5261 break;
5262 case TelephonyManager.NETWORK_TYPE_HSDPA:
5263 bin = DATA_CONNECTION_HSDPA;
5264 break;
5265 case TelephonyManager.NETWORK_TYPE_HSUPA:
5266 bin = DATA_CONNECTION_HSUPA;
5267 break;
5268 case TelephonyManager.NETWORK_TYPE_HSPA:
5269 bin = DATA_CONNECTION_HSPA;
5270 break;
5271 case TelephonyManager.NETWORK_TYPE_IDEN:
5272 bin = DATA_CONNECTION_IDEN;
5273 break;
5274 case TelephonyManager.NETWORK_TYPE_EVDO_B:
5275 bin = DATA_CONNECTION_EVDO_B;
5276 break;
Robert Greenwalt962a9902010-11-02 11:10:25 -07005277 case TelephonyManager.NETWORK_TYPE_LTE:
5278 bin = DATA_CONNECTION_LTE;
5279 break;
5280 case TelephonyManager.NETWORK_TYPE_EHRPD:
5281 bin = DATA_CONNECTION_EHRPD;
5282 break;
Patrick Tjinb71703c2013-11-06 09:27:03 -08005283 case TelephonyManager.NETWORK_TYPE_HSPAP:
5284 bin = DATA_CONNECTION_HSPAP;
5285 break;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005286 default:
5287 bin = DATA_CONNECTION_OTHER;
5288 break;
5289 }
5290 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005291 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005292 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005293 final long elapsedRealtime = mClocks.elapsedRealtime();
5294 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005295 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5296 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005297 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5298 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005299 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005300 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005301 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005302 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005303 }
5304 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005305 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005306 }
5307 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005308
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005309 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005310 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005311 final long elapsedRealtime = mClocks.elapsedRealtime();
5312 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005313 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005314 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5315 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005316 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005317 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005318 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005319 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005320 }
5321 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005322
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005323 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005324 final long elapsedRealtime = mClocks.elapsedRealtime();
5325 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005326 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005327 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005328 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5329 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005330 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005331 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005332 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005333 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005334 }
5335 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005336
5337 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005338 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005339 final long elapsedRealtime = mClocks.elapsedRealtime();
5340 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005341 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005342 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005343 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5344 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005345 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005346 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005347 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005348 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005349 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005350 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005351
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005352 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005353 if (mAudioOnNesting == 0) {
5354 return;
5355 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005356 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005357 final long elapsedRealtime = mClocks.elapsedRealtime();
5358 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005359 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005360 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005361 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5362 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005363 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005364 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005365 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005366 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005367 }
5368
5369 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005370 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005371 final long elapsedRealtime = mClocks.elapsedRealtime();
5372 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005373 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005374 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005375 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5376 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005377 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005378 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005379 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005380 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005381 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005382 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005383
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005384 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005385 if (mVideoOnNesting == 0) {
5386 return;
5387 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005388 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005389 final long elapsedRealtime = mClocks.elapsedRealtime();
5390 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005391 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005392 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005393 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5394 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005395 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005396 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005397 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005398 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005399 }
5400
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005401 public void noteResetAudioLocked() {
5402 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005403 final long elapsedRealtime = mClocks.elapsedRealtime();
5404 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005405 mAudioOnNesting = 0;
5406 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5407 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5408 + Integer.toHexString(mHistoryCur.states));
5409 addHistoryRecordLocked(elapsedRealtime, uptime);
5410 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5411 for (int i=0; i<mUidStats.size(); i++) {
5412 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5413 uid.noteResetAudioLocked(elapsedRealtime);
5414 }
5415 }
5416 }
5417
5418 public void noteResetVideoLocked() {
5419 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005420 final long elapsedRealtime = mClocks.elapsedRealtime();
5421 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005422 mAudioOnNesting = 0;
5423 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5424 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5425 + Integer.toHexString(mHistoryCur.states));
5426 addHistoryRecordLocked(elapsedRealtime, uptime);
5427 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5428 for (int i=0; i<mUidStats.size(); i++) {
5429 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5430 uid.noteResetVideoLocked(elapsedRealtime);
5431 }
5432 }
5433 }
5434
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005435 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005436 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005437 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005438 }
5439
5440 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005441 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005442 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005443 }
5444
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005445 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005446 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005447 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5448 }
5449
5450 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005451 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005452 getUidStatsLocked(uid).noteVibratorOffLocked();
5453 }
5454
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005455 public void noteFlashlightOnLocked(int uid) {
5456 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005457 final long elapsedRealtime = mClocks.elapsedRealtime();
5458 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005459 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005460 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5461 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005462 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005463 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005464 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5465 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005466 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5467 }
5468
5469 public void noteFlashlightOffLocked(int uid) {
5470 if (mFlashlightOnNesting == 0) {
5471 return;
5472 }
5473 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005474 final long elapsedRealtime = mClocks.elapsedRealtime();
5475 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005476 if (--mFlashlightOnNesting == 0) {
5477 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5478 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5479 + Integer.toHexString(mHistoryCur.states2));
5480 addHistoryRecordLocked(elapsedRealtime, uptime);
5481 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5482 }
5483 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5484 }
5485
5486 public void noteCameraOnLocked(int uid) {
5487 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005488 final long elapsedRealtime = mClocks.elapsedRealtime();
5489 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005490 if (mCameraOnNesting++ == 0) {
5491 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5492 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5493 + Integer.toHexString(mHistoryCur.states2));
5494 addHistoryRecordLocked(elapsedRealtime, uptime);
5495 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5496 }
5497 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5498 }
5499
5500 public void noteCameraOffLocked(int uid) {
5501 if (mCameraOnNesting == 0) {
5502 return;
5503 }
5504 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005505 final long elapsedRealtime = mClocks.elapsedRealtime();
5506 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005507 if (--mCameraOnNesting == 0) {
5508 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5509 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5510 + Integer.toHexString(mHistoryCur.states2));
5511 addHistoryRecordLocked(elapsedRealtime, uptime);
5512 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5513 }
5514 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5515 }
5516
5517 public void noteResetCameraLocked() {
5518 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005519 final long elapsedRealtime = mClocks.elapsedRealtime();
5520 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005521 mCameraOnNesting = 0;
5522 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5523 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5524 + Integer.toHexString(mHistoryCur.states2));
5525 addHistoryRecordLocked(elapsedRealtime, uptime);
5526 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5527 for (int i=0; i<mUidStats.size(); i++) {
5528 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5529 uid.noteResetCameraLocked(elapsedRealtime);
5530 }
5531 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005532 }
5533
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005534 public void noteResetFlashlightLocked() {
5535 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005536 final long elapsedRealtime = mClocks.elapsedRealtime();
5537 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005538 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005539 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5540 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005541 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005542 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005543 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5544 for (int i=0; i<mUidStats.size(); i++) {
5545 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5546 uid.noteResetFlashlightLocked(elapsedRealtime);
5547 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005548 }
5549 }
5550
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005551 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5552 boolean isUnoptimized) {
5553 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005554 final long elapsedRealtime = mClocks.elapsedRealtime();
5555 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005556 if (mBluetoothScanNesting == 0) {
5557 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5558 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5559 + Integer.toHexString(mHistoryCur.states2));
5560 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005561 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005562 }
5563 mBluetoothScanNesting++;
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005564
Yangster-macafad8c62018-01-05 22:30:49 -08005565 if (workChain != null) {
5566 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005567 workChain.getUids(), workChain.getTags(),
5568 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005569 if (isUnoptimized) {
5570 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005571 workChain.getUids(), workChain.getTags(),
5572 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005573 }
5574 } else {
Bookatz90867622018-01-31 15:05:57 -08005575 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null,
5576 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005577 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005578 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08005579 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005580 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005581 }
5582
Bookatzb1f04f32017-05-19 13:57:32 -07005583 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005584 if (workChain != null) {
5585 getUidStatsLocked(uid).addBluetoothWorkChain(workChain, isUnoptimized);
5586 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005587 }
5588
Bookatzb1f04f32017-05-19 13:57:32 -07005589 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005590 final int N = ws.size();
5591 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005592 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5593 }
5594
5595 final List<WorkChain> workChains = ws.getWorkChains();
5596 if (workChains != null) {
5597 for (int i = 0; i < workChains.size(); ++i) {
5598 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5599 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005600 }
5601 }
5602
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005603 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5604 boolean isUnoptimized) {
5605 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005606 final long elapsedRealtime = mClocks.elapsedRealtime();
5607 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005608 mBluetoothScanNesting--;
5609 if (mBluetoothScanNesting == 0) {
5610 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5611 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5612 + Integer.toHexString(mHistoryCur.states2));
5613 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005614 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005615 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005616
Yangster-macafad8c62018-01-05 22:30:49 -08005617 if (workChain != null) {
5618 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08005619 StatsLog.BLE_SCAN_STATE_CHANGED, workChain.getUids(), workChain.getTags(),
5620 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005621 if (isUnoptimized) {
5622 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005623 workChain.getUids(), workChain.getTags(),
5624 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005625 }
5626 } else {
Bookatz90867622018-01-31 15:05:57 -08005627 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null,
5628 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005629 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005630 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08005631 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005632 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005633 }
5634
Bookatz94c5a312017-07-11 16:49:17 -07005635 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005636 if (workChain != null) {
5637 getUidStatsLocked(uid).removeBluetoothWorkChain(workChain, isUnoptimized);
5638 }
5639 }
5640
5641 private int getAttributionUid(int uid, WorkChain workChain) {
5642 if (workChain != null) {
5643 return mapUid(workChain.getAttributionUid());
5644 }
5645
5646 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005647 }
5648
Bookatz94c5a312017-07-11 16:49:17 -07005649 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005650 final int N = ws.size();
5651 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005652 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5653 }
5654
5655 final List<WorkChain> workChains = ws.getWorkChains();
5656 if (workChains != null) {
5657 for (int i = 0; i < workChains.size(); ++i) {
5658 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5659 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005660 }
5661 }
5662
5663 public void noteResetBluetoothScanLocked() {
5664 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005665 final long elapsedRealtime = mClocks.elapsedRealtime();
5666 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005667 mBluetoothScanNesting = 0;
5668 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5669 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5670 + Integer.toHexString(mHistoryCur.states2));
5671 addHistoryRecordLocked(elapsedRealtime, uptime);
5672 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005673
5674
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005675 for (int i=0; i<mUidStats.size(); i++) {
5676 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5677 uid.noteResetBluetoothScanLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005678
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005679 List<WorkChain> allWorkChains = uid.getAllBluetoothWorkChains();
5680 if (allWorkChains != null) {
5681 for (int j = 0; j < allWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005682 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005683 allWorkChains.get(j).getUids(),
Bookatz90867622018-01-31 15:05:57 -08005684 allWorkChains.get(j).getTags(),
5685 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005686 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005687 allWorkChains.clear();
5688 }
5689
5690 List<WorkChain> unoptimizedWorkChains = uid.getUnoptimizedBluetoothWorkChains();
5691 if (unoptimizedWorkChains != null) {
5692 for (int j = 0; j < unoptimizedWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005693 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005694 unoptimizedWorkChains.get(j).getUids(),
Bookatz90867622018-01-31 15:05:57 -08005695 unoptimizedWorkChains.get(j).getTags(),
5696 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005697 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005698 unoptimizedWorkChains.clear();
5699 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005700 }
5701 }
5702 }
5703
Bookatz4ebc0642017-05-11 12:21:19 -07005704 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005705 final int N = ws.size();
5706 for (int i = 0; i < N; i++) {
5707 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005708 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005709 StatsLog.write_non_chained(StatsLog.BLE_SCAN_RESULT_RECEIVED, ws.get(i), ws.getName(i),
5710 numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005711 }
5712
5713 final List<WorkChain> workChains = ws.getWorkChains();
5714 if (workChains != null) {
5715 for (int i = 0; i < workChains.size(); ++i) {
5716 final WorkChain wc = workChains.get(i);
5717 int uid = mapUid(wc.getAttributionUid());
5718 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-macafad8c62018-01-05 22:30:49 -08005719 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED,
5720 wc.getUids(), wc.getTags(), numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005721 }
Bookatz956f36bf2017-04-28 09:48:17 -07005722 }
5723 }
5724
Adam Lesinski5f056f62016-07-14 16:56:08 -07005725 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5726 final long uptimeMillis, int uid) {
5727 uid = mapUid(uid);
5728 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5729 uid);
5730 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5731 }
5732
5733 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005734 final long elapsedRealtime = mClocks.elapsedRealtime();
5735 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005736 if (mWifiRadioPowerState != powerState) {
5737 final boolean active =
5738 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5739 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5740 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005741 if (uid > 0) {
5742 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5743 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005744 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005745 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005746 } else {
5747 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005748 mWifiActiveTimer.stopRunningLocked(
5749 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005750 }
5751 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5752 + Integer.toHexString(mHistoryCur.states));
5753 addHistoryRecordLocked(elapsedRealtime, uptime);
5754 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005755 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005756 }
5757 }
5758
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005759 public void noteWifiRunningLocked(WorkSource ws) {
5760 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005761 final long elapsedRealtime = mClocks.elapsedRealtime();
5762 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005763 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005764 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5765 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005766 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005767 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005768 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005769 int N = ws.size();
5770 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005771 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005772 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005773 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005774
5775 List<WorkChain> workChains = ws.getWorkChains();
5776 if (workChains != null) {
5777 for (int i = 0; i < workChains.size(); ++i) {
5778 int uid = mapUid(workChains.get(i).getAttributionUid());
5779 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5780 }
5781 }
5782
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005783 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005784 } else {
5785 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005786 }
5787 }
5788
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005789 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5790 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005791 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005792 int N = oldWs.size();
5793 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005794 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005795 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005796 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005797
5798 List<WorkChain> workChains = oldWs.getWorkChains();
5799 if (workChains != null) {
5800 for (int i = 0; i < workChains.size(); ++i) {
5801 int uid = mapUid(workChains.get(i).getAttributionUid());
5802 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5803 }
5804 }
5805
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005806 N = newWs.size();
5807 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005808 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005809 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005810 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005811
5812 workChains = newWs.getWorkChains();
5813 if (workChains != null) {
5814 for (int i = 0; i < workChains.size(); ++i) {
5815 int uid = mapUid(workChains.get(i).getAttributionUid());
5816 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5817 }
5818 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005819 } else {
5820 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5821 }
5822 }
5823
5824 public void noteWifiStoppedLocked(WorkSource ws) {
5825 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005826 final long elapsedRealtime = mClocks.elapsedRealtime();
5827 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005828 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005829 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5830 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005831 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005832 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005833 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005834 int N = ws.size();
5835 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005836 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005837 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005838 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005839
5840 List<WorkChain> workChains = ws.getWorkChains();
5841 if (workChains != null) {
5842 for (int i = 0; i < workChains.size(); ++i) {
5843 int uid = mapUid(workChains.get(i).getAttributionUid());
5844 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5845 }
5846 }
5847
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005848 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005849 } else {
5850 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005851 }
5852 }
5853
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005854 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5855 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5856 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005857 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005858 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005859 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005860 }
5861 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005862 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005863 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005864 }
5865 }
5866
Dianne Hackborn3251b902014-06-20 14:40:53 -07005867 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5868 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5869 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005870 final long elapsedRealtime = mClocks.elapsedRealtime();
5871 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005872 if (mWifiSupplState >= 0) {
5873 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5874 }
5875 mWifiSupplState = supplState;
5876 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5877 mHistoryCur.states2 =
5878 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5879 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5880 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5881 + Integer.toHexString(mHistoryCur.states2));
5882 addHistoryRecordLocked(elapsedRealtime, uptime);
5883 }
5884 }
5885
5886 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005887 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005888 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5889 if (i == except) {
5890 continue;
5891 }
5892 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5893 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5894 }
5895 }
5896 }
5897
5898 public void noteWifiRssiChangedLocked(int newRssi) {
5899 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5900 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5901 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005902 final long elapsedRealtime = mClocks.elapsedRealtime();
5903 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005904 if (mWifiSignalStrengthBin >= 0) {
5905 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5906 elapsedRealtime);
5907 }
5908 if (strengthBin >= 0) {
5909 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5910 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Bookatze5885242017-10-24 20:10:31 -07005911 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07005912 }
5913 mHistoryCur.states2 =
5914 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5915 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5916 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5917 + Integer.toHexString(mHistoryCur.states2));
5918 addHistoryRecordLocked(elapsedRealtime, uptime);
5919 } else {
5920 stopAllWifiSignalStrengthTimersLocked(-1);
5921 }
5922 mWifiSignalStrengthBin = strengthBin;
5923 }
5924 }
5925
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005926 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005927
The Android Open Source Project10592532009-03-18 17:39:46 -07005928 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005929 final long elapsedRealtime = mClocks.elapsedRealtime();
5930 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005931 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005932 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005933 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5934 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005935 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005936 }
5937 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005938 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005939 }
5940
5941 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005942 final long elapsedRealtime = mClocks.elapsedRealtime();
5943 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005944 mWifiFullLockNesting--;
5945 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005946 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005947 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
5948 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005949 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005950 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005951 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005952 }
5953
Nick Pelly6ccaa542012-06-15 15:22:47 -07005954 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005955
Nick Pelly6ccaa542012-06-15 15:22:47 -07005956 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005957 final long elapsedRealtime = mClocks.elapsedRealtime();
5958 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005959 if (mWifiScanNesting == 0) {
5960 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
5961 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005962 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005963 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005964 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07005965 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005966 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005967 }
5968
Nick Pelly6ccaa542012-06-15 15:22:47 -07005969 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005970 final long elapsedRealtime = mClocks.elapsedRealtime();
5971 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005972 mWifiScanNesting--;
5973 if (mWifiScanNesting == 0) {
5974 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
5975 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005976 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005977 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005978 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005979 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005980 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005981
Robert Greenwalta029ea12013-09-25 16:38:12 -07005982 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005983 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005984 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005985 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005986 }
5987
5988 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005989 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005990 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005991 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005992 }
5993
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005994 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005995
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005996 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005997 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005998 final long elapsedRealtime = mClocks.elapsedRealtime();
5999 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006000 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006001 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006002 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
6003 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006004 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006005
6006 // Start Wifi Multicast overall timer
6007 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
6008 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
6009 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
6010 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006011 }
6012 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006013 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006014 }
6015
6016 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006017 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006018 final long elapsedRealtime = mClocks.elapsedRealtime();
6019 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006020 mWifiMulticastNesting--;
6021 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006022 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006023 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
6024 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006025 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006026
6027 // Stop Wifi Multicast overall timer
6028 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
6029 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
6030 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
6031 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006032 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006033 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006034 }
6035
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006036 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
6037 int N = ws.size();
6038 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006039 final int uid = mapUid(ws.get(i));
6040 noteFullWifiLockAcquiredLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006041 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6042 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006043 }
6044
6045 final List<WorkChain> workChains = ws.getWorkChains();
6046 if (workChains != null) {
6047 for (int i = 0; i < workChains.size(); ++i) {
6048 final WorkChain workChain = workChains.get(i);
6049 final int uid = mapUid(workChain.getAttributionUid());
6050 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006051 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006052 workChain.getUids(), workChain.getTags(),
6053 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006054 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006055 }
6056 }
6057
6058 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
6059 int N = ws.size();
6060 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006061 final int uid = mapUid(ws.get(i));
6062 noteFullWifiLockReleasedLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006063 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6064 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006065 }
6066
6067 final List<WorkChain> workChains = ws.getWorkChains();
6068 if (workChains != null) {
6069 for (int i = 0; i < workChains.size(); ++i) {
6070 final WorkChain workChain = workChains.get(i);
6071 final int uid = mapUid(workChain.getAttributionUid());
6072 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006073 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006074 workChain.getUids(), workChain.getTags(),
6075 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006076 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006077 }
6078 }
6079
Nick Pelly6ccaa542012-06-15 15:22:47 -07006080 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006081 int N = ws.size();
6082 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006083 final int uid = mapUid(ws.get(i));
6084 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006085 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006086 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006087 }
6088
6089 final List<WorkChain> workChains = ws.getWorkChains();
6090 if (workChains != null) {
6091 for (int i = 0; i < workChains.size(); ++i) {
6092 final WorkChain workChain = workChains.get(i);
6093 final int uid = mapUid(workChain.getAttributionUid());
6094 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006095 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08006096 workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006097 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006098 }
6099 }
6100
Nick Pelly6ccaa542012-06-15 15:22:47 -07006101 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006102 int N = ws.size();
6103 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006104 final int uid = mapUid(ws.get(i));
6105 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006106 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006107 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006108 }
6109
6110 final List<WorkChain> workChains = ws.getWorkChains();
6111 if (workChains != null) {
6112 for (int i = 0; i < workChains.size(); ++i) {
6113 final WorkChain workChain = workChains.get(i);
6114 final int uid = mapUid(workChain.getAttributionUid());
6115 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006116 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006117 workChain.getUids(), workChain.getTags(),
6118 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006119 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006120 }
6121 }
6122
Robert Greenwalta029ea12013-09-25 16:38:12 -07006123 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6124 int N = ws.size();
6125 for (int i=0; i<N; i++) {
6126 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6127 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006128
6129 final List<WorkChain> workChains = ws.getWorkChains();
6130 if (workChains != null) {
6131 for (int i = 0; i < workChains.size(); ++i) {
6132 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6133 }
6134 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006135 }
6136
6137 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6138 int N = ws.size();
6139 for (int i=0; i<N; i++) {
6140 noteWifiBatchedScanStoppedLocked(ws.get(i));
6141 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006142
6143 final List<WorkChain> workChains = ws.getWorkChains();
6144 if (workChains != null) {
6145 for (int i = 0; i < workChains.size(); ++i) {
6146 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6147 }
6148 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006149 }
6150
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006151 private static String[] includeInStringArray(String[] array, String str) {
6152 if (ArrayUtils.indexOf(array, str) >= 0) {
6153 return array;
6154 }
6155 String[] newArray = new String[array.length+1];
6156 System.arraycopy(array, 0, newArray, 0, array.length);
6157 newArray[array.length] = str;
6158 return newArray;
6159 }
6160
6161 private static String[] excludeFromStringArray(String[] array, String str) {
6162 int index = ArrayUtils.indexOf(array, str);
6163 if (index >= 0) {
6164 String[] newArray = new String[array.length-1];
6165 if (index > 0) {
6166 System.arraycopy(array, 0, newArray, 0, index);
6167 }
6168 if (index < array.length-1) {
6169 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6170 }
6171 return newArray;
6172 }
6173 return array;
6174 }
6175
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006176 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006177 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006178
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006179 synchronized (mModemNetworkLock) {
6180 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6181 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6182 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6183 } else {
6184 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6185 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6186 }
6187 }
6188
6189 synchronized (mWifiNetworkLock) {
6190 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6191 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6192 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6193 } else {
6194 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6195 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6196 }
6197 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006198 }
6199
David Chenc8a43242017-10-17 16:23:28 -07006200 public String[] getWifiIfaces() {
6201 synchronized (mWifiNetworkLock) {
6202 return mWifiIfaces;
6203 }
6204 }
6205
6206 public String[] getMobileIfaces() {
6207 synchronized (mModemNetworkLock) {
6208 return mModemIfaces;
6209 }
6210 }
6211
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006212 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6213 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006215
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006216 @Override public int getScreenOnCount(int which) {
6217 return mScreenOnTimer.getCountLocked(which);
6218 }
6219
Mike Mac2f518a2017-09-19 16:06:03 -07006220 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6221 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6222 }
6223
6224 @Override public int getScreenDozeCount(int which) {
6225 return mScreenDozeTimer.getCountLocked(which);
6226 }
6227
Dianne Hackborn617f8772009-03-31 15:04:46 -07006228 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006229 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006230 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006231 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006232 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006233
Kweku Adams87b19ec2017-10-09 12:40:03 -07006234 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6235 return mScreenBrightnessTimer[brightnessBin];
6236 }
6237
Jeff Browne95c3cd2014-05-02 16:59:26 -07006238 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6239 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006240 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006241
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006242 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6243 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006244 }
6245
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006246 @Override public int getPowerSaveModeEnabledCount(int which) {
6247 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6248 }
6249
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006250 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6251 int which) {
6252 switch (mode) {
6253 case DEVICE_IDLE_MODE_LIGHT:
6254 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006255 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006256 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6257 }
6258 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006259 }
6260
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006261 @Override public int getDeviceIdleModeCount(int mode, int which) {
6262 switch (mode) {
6263 case DEVICE_IDLE_MODE_LIGHT:
6264 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006265 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006266 return mDeviceIdleModeFullTimer.getCountLocked(which);
6267 }
6268 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006269 }
6270
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006271 @Override public long getLongestDeviceIdleModeTime(int mode) {
6272 switch (mode) {
6273 case DEVICE_IDLE_MODE_LIGHT:
6274 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006275 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006276 return mLongestFullIdleTime;
6277 }
6278 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006279 }
6280
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006281 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6282 switch (mode) {
6283 case DEVICE_IDLE_MODE_LIGHT:
6284 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006285 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006286 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6287 }
6288 return 0;
6289 }
6290
6291 @Override public int getDeviceIdlingCount(int mode, int which) {
6292 switch (mode) {
6293 case DEVICE_IDLE_MODE_LIGHT:
6294 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006295 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006296 return mDeviceIdlingTimer.getCountLocked(which);
6297 }
6298 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006299 }
6300
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006301 @Override public int getNumConnectivityChange(int which) {
6302 int val = mNumConnectivityChange;
6303 if (which == STATS_CURRENT) {
6304 val -= mLoadedNumConnectivityChange;
6305 } else if (which == STATS_SINCE_UNPLUGGED) {
6306 val -= mUnpluggedNumConnectivityChange;
6307 }
6308 return val;
6309 }
6310
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006311 @Override public long getGpsSignalQualityTime(int strengthBin,
6312 long elapsedRealtimeUs, int which) {
6313 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6314 return 0;
6315 }
6316 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6317 elapsedRealtimeUs, which);
6318 }
6319
6320 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006321 final double opVolt = mPowerProfile.getAveragePower(
6322 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6323 if (opVolt == 0) {
6324 return 0;
6325 }
6326 double energyUsedMaMs = 0.0;
6327 final int which = STATS_SINCE_CHARGED;
6328 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6329 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6330 energyUsedMaMs
6331 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6332 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6333 }
6334 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006335 }
6336
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006337 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6338 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006340
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006341 @Override public int getPhoneOnCount(int which) {
6342 return mPhoneOnTimer.getCountLocked(which);
6343 }
6344
Dianne Hackborn627bba72009-03-24 22:32:56 -07006345 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006346 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006347 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006348 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006349 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006350
6351 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006352 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006353 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006354 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006355 }
6356
Kweku Adams87b19ec2017-10-09 12:40:03 -07006357 @Override public Timer getPhoneSignalScanningTimer() {
6358 return mPhoneSignalScanningTimer;
6359 }
6360
Catherine Liufb900812012-07-17 14:12:56 -05006361 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6362 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006363 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006364
Kweku Adams87b19ec2017-10-09 12:40:03 -07006365 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6366 return mPhoneSignalStrengthsTimer[strengthBin];
6367 }
6368
Dianne Hackborn627bba72009-03-24 22:32:56 -07006369 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006370 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006371 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006372 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006373 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006374
Dianne Hackborn617f8772009-03-31 15:04:46 -07006375 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006376 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006377 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006378
Kweku Adams87b19ec2017-10-09 12:40:03 -07006379 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6380 return mPhoneDataConnectionsTimer[dataType];
6381 }
6382
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006383 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6384 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006385 }
6386
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006387 @Override public int getMobileRadioActiveCount(int which) {
6388 return mMobileRadioActiveTimer.getCountLocked(which);
6389 }
6390
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006391 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6392 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6393 }
6394
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006395 @Override public long getMobileRadioActiveUnknownTime(int which) {
6396 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6397 }
6398
6399 @Override public int getMobileRadioActiveUnknownCount(int which) {
6400 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6401 }
6402
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006403 @Override public long getWifiMulticastWakelockTime(
6404 long elapsedRealtimeUs, int which) {
6405 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6406 elapsedRealtimeUs, which);
6407 }
6408
6409 @Override public int getWifiMulticastWakelockCount(int which) {
6410 return mWifiMulticastWakelockTimer.getCountLocked(which);
6411 }
6412
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006413 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6414 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006415 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006416
Siddharth Rayb50a6842017-12-14 15:15:28 -08006417 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6418 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6419 }
6420
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006421 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6422 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006423 }
6424
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006425 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006426 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006427 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006428 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006429 }
6430
6431 @Override public int getWifiStateCount(int wifiState, int which) {
6432 return mWifiStateTimer[wifiState].getCountLocked(which);
6433 }
6434
Kweku Adams87b19ec2017-10-09 12:40:03 -07006435 @Override public Timer getWifiStateTimer(int wifiState) {
6436 return mWifiStateTimer[wifiState];
6437 }
6438
Dianne Hackborn3251b902014-06-20 14:40:53 -07006439 @Override public long getWifiSupplStateTime(int state,
6440 long elapsedRealtimeUs, int which) {
6441 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6442 elapsedRealtimeUs, which);
6443 }
6444
6445 @Override public int getWifiSupplStateCount(int state, int which) {
6446 return mWifiSupplStateTimer[state].getCountLocked(which);
6447 }
6448
Kweku Adams87b19ec2017-10-09 12:40:03 -07006449 @Override public Timer getWifiSupplStateTimer(int state) {
6450 return mWifiSupplStateTimer[state];
6451 }
6452
Dianne Hackborn3251b902014-06-20 14:40:53 -07006453 @Override public long getWifiSignalStrengthTime(int strengthBin,
6454 long elapsedRealtimeUs, int which) {
6455 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6456 elapsedRealtimeUs, which);
6457 }
6458
6459 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6460 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6461 }
6462
Kweku Adams87b19ec2017-10-09 12:40:03 -07006463 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6464 return mWifiSignalStrengthsTimer[strengthBin];
6465 }
6466
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006467 @Override
6468 public ControllerActivityCounter getBluetoothControllerActivity() {
6469 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006470 }
6471
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006472 @Override
6473 public ControllerActivityCounter getWifiControllerActivity() {
6474 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006475 }
6476
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006477 @Override
6478 public ControllerActivityCounter getModemControllerActivity() {
6479 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006480 }
6481
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006482 @Override
6483 public boolean hasBluetoothActivityReporting() {
6484 return mHasBluetoothReporting;
6485 }
6486
6487 @Override
6488 public boolean hasWifiActivityReporting() {
6489 return mHasWifiReporting;
6490 }
6491
6492 @Override
6493 public boolean hasModemActivityReporting() {
6494 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006495 }
6496
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006497 @Override
6498 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006499 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6500 }
6501
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006502 @Override
6503 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006504 return mFlashlightOnTimer.getCountLocked(which);
6505 }
6506
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006507 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006508 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6509 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6510 }
6511
6512 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006513 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6514 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6515 }
6516
6517 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006518 public long getNetworkActivityBytes(int type, int which) {
6519 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6520 return mNetworkByteActivityCounters[type].getCountLocked(which);
6521 } else {
6522 return 0;
6523 }
6524 }
6525
6526 @Override
6527 public long getNetworkActivityPackets(int type, int which) {
6528 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6529 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006530 } else {
6531 return 0;
6532 }
6533 }
6534
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006535 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006536 final long currentTime = System.currentTimeMillis();
6537 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006538 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6539 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006540 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006541 return mStartClockTime;
6542 }
6543
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006544 @Override public String getStartPlatformVersion() {
6545 return mStartPlatformVersion;
6546 }
6547
6548 @Override public String getEndPlatformVersion() {
6549 return mEndPlatformVersion;
6550 }
6551
6552 @Override public int getParcelVersion() {
6553 return VERSION;
6554 }
6555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006556 @Override public boolean getIsOnBattery() {
6557 return mOnBattery;
6558 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6561 return mUidStats;
6562 }
6563
Adam Lesinski5f056f62016-07-14 16:56:08 -07006564 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6565 if (timer != null) {
6566 timer.detach();
6567 }
6568 }
6569
6570 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6571 boolean detachIfReset) {
6572 if (timer != null) {
6573 return timer.reset(detachIfReset);
6574 }
6575 return true;
6576 }
6577
Bookatz867c0d72017-03-07 18:23:42 -08006578 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6579 if (timer != null) {
6580 return timer.reset(detachIfReset);
6581 }
6582 return true;
6583 }
6584
Adam Lesinski5f056f62016-07-14 16:56:08 -07006585 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6586 if (counter != null) {
6587 counter.detach();
6588 }
6589 }
6590
6591 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6592 boolean detachIfReset) {
6593 if (counter != null) {
6594 counter.reset(detachIfReset);
6595 }
6596 }
6597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 /**
6599 * The statistics associated with a particular uid.
6600 */
Joe Onoratoabded112016-02-08 16:49:39 -08006601 public static class Uid extends BatteryStats.Uid {
6602 /**
6603 * BatteryStatsImpl that we are associated with.
6604 */
6605 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006608
Bookatz867c0d72017-03-07 18:23:42 -08006609 /** TimeBase for when uid is in background and device is on battery. */
6610 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6611 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006612 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6613 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006614
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006615 boolean mWifiRunning;
6616 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006617
The Android Open Source Project10592532009-03-18 17:39:46 -07006618 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006619 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006620
Nick Pelly6ccaa542012-06-15 15:22:47 -07006621 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006622 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006623
Dianne Hackborn61659e52014-07-09 16:13:01 -07006624 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006625 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6626 StopwatchTimer[] mWifiBatchedScanTimer;
6627
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006628 boolean mWifiMulticastEnabled;
6629 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006630
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006631 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006632 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006633 StopwatchTimer mFlashlightTurnedOnTimer;
6634 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006635 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006636 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006637 /** Total time spent by the uid holding any partial wakelocks. */
6638 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006639 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006640 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006641 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006642 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006643
Dianne Hackborna8d10942015-11-19 17:55:19 -08006644 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006645 StopwatchTimer[] mProcessStateTimer;
6646
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006647 boolean mInForegroundService = false;
6648
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006649 BatchTimer mVibratorOnTimer;
6650
Dianne Hackborn617f8772009-03-31 15:04:46 -07006651 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006652
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006653 LongSamplingCounter[] mNetworkByteActivityCounters;
6654 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006655 LongSamplingCounter mMobileRadioActiveTime;
6656 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006659 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6660 */
6661 private LongSamplingCounter mMobileRadioApWakeupCount;
6662
6663 /**
6664 * How many times this UID woke up the Application Processor due to a Wifi packet.
6665 */
6666 private LongSamplingCounter mWifiRadioApWakeupCount;
6667
6668 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006669 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006670 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006671 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006672 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006673
6674 /**
6675 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006676 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006677 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006678 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6679
6680 /**
6681 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6682 * Can be null if the UID has had no such activity.
6683 */
6684 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006685
6686 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006687 * The CPU times we had at the last history details update.
6688 */
6689 long mLastStepUserTime;
6690 long mLastStepSystemTime;
6691 long mCurStepUserTime;
6692 long mCurStepSystemTime;
6693
Joe Onoratoabded112016-02-08 16:49:39 -08006694 LongSamplingCounter mUserCpuTime;
6695 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006696 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006697 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006698
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006699 LongSamplingCounterArray mCpuFreqTimeMs;
6700 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006701 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006702
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006703 LongSamplingCounterArray[] mProcStateTimeMs;
6704 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6705
6706 IntArray mChildUids;
6707
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006708 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709 * The statistics we have collected for this uid's wake locks.
6710 */
Joe Onoratoabded112016-02-08 16:49:39 -08006711 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712
6713 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006714 * The statistics we have collected for this uid's syncs.
6715 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006716 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006717
6718 /**
6719 * The statistics we have collected for this uid's jobs.
6720 */
Bookatzaa4594a2017-03-24 12:39:56 -07006721 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006722
6723 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006724 * Count of the jobs that have completed and the reasons why they completed.
6725 */
6726 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6727
6728 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 * The statistics we have collected for this uid's sensor activations.
6730 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006731 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006732
6733 /**
6734 * The statistics we have collected for this uid's processes.
6735 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006736 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737
6738 /**
6739 * The statistics we have collected for this uid's processes.
6740 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006741 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006742
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006743 /**
6744 * The transient wake stats we have collected for this uid's pids.
6745 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006746 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006747
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00006748 /**
6749 * The list of WorkChains associated with active bluetooth scans.
6750 *
6751 * NOTE: This is a hack and it only needs to exist because there's a "reset" API that is
6752 * supposed to stop and log all WorkChains that were currently active.
6753 */
6754 ArrayList<WorkChain> mAllBluetoothChains = null;
6755 ArrayList<WorkChain> mUnoptimizedBluetoothChains = null;
6756
Joe Onoratoabded112016-02-08 16:49:39 -08006757 public Uid(BatteryStatsImpl bsi, int uid) {
6758 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006760
Bookatz867c0d72017-03-07 18:23:42 -08006761 mOnBatteryBackgroundTimeBase = new TimeBase();
6762 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6763 mBsi.mClocks.elapsedRealtime() * 1000);
6764
Bookatzc8c44962017-05-11 12:12:54 -07006765 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6766 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6767 mBsi.mClocks.elapsedRealtime() * 1000);
6768
Joe Onoratoabded112016-02-08 16:49:39 -08006769 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6770 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006771 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6772 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006773
Dianne Hackborn657153b2016-07-29 14:54:14 -07006774 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006775 @Override public Wakelock instantiateObject() {
6776 return new Wakelock(mBsi, Uid.this);
6777 }
6778 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006779 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6780 @Override public DualTimer instantiateObject() {
6781 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6782 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006783 }
6784 };
Bookatzaa4594a2017-03-24 12:39:56 -07006785 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6786 @Override public DualTimer instantiateObject() {
6787 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6788 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006789 }
6790 };
6791
6792 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6793 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6794 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6795 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006796 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6797 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006798 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006799 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6800 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006801 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 }
6803
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006804 @VisibleForTesting
6805 public void setProcessStateForTest(int procState) {
6806 mProcessState = procState;
6807 }
6808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006810 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006811 return nullIfAllZeros(mCpuFreqTimeMs, which);
6812 }
6813
6814 @Override
6815 public long[] getScreenOffCpuFreqTimes(int which) {
6816 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6817 }
6818
6819 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006820 public long getCpuActiveTime() {
6821 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6822 }
6823
6824 @Override
6825 public long[] getCpuClusterTimes() {
6826 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6827 }
6828
6829
6830 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006831 public long[] getCpuFreqTimes(int which, int procState) {
6832 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006833 return null;
6834 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006835 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006836 return null;
6837 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006838 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6839 mProcStateTimeMs = null;
6840 return null;
6841 }
6842 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6843 }
6844
6845 @Override
6846 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6847 if (which < 0 || which >= NUM_PROCESS_STATE) {
6848 return null;
6849 }
6850 if (mProcStateScreenOffTimeMs == null) {
6851 return null;
6852 }
6853 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6854 mProcStateScreenOffTimeMs = null;
6855 return null;
6856 }
6857 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6858 }
6859
6860 public void addIsolatedUid(int isolatedUid) {
6861 if (mChildUids == null) {
6862 mChildUids = new IntArray();
6863 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6864 return;
6865 }
6866 mChildUids.add(isolatedUid);
6867 }
6868
6869 public void removeIsolatedUid(int isolatedUid) {
6870 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6871 if (idx < 0) {
6872 return;
6873 }
6874 mChildUids.remove(idx);
6875 }
6876
6877 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6878 if (cpuTimesMs == null) {
6879 return null;
6880 }
6881 final long[] counts = cpuTimesMs.getCountsLocked(which);
6882 if (counts == null) {
6883 return null;
6884 }
6885 // Return counts only if at least one of the elements is non-zero.
6886 for (int i = counts.length - 1; i >= 0; --i) {
6887 if (counts[i] != 0) {
6888 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006889 }
6890 }
6891 return null;
6892 }
6893
Sudheer Shankae544d162017-12-28 17:06:20 -08006894 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006895 if (mProcStateTimeMs == null) {
6896 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006897 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006898 if (mProcStateTimeMs[procState] == null
6899 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
6900 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6901 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006902 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006903 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006904 }
6905
Sudheer Shankae544d162017-12-28 17:06:20 -08006906 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6907 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006908 if (mProcStateScreenOffTimeMs == null) {
6909 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006910 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006911 if (mProcStateScreenOffTimeMs[procState] == null
6912 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
6913 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
6914 mBsi.mOnBatteryScreenOffTimeBase);
6915 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006916 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006917 }
6918
6919 @Override
Bookatzc8c44962017-05-11 12:12:54 -07006920 public Timer getAggregatedPartialWakelockTimer() {
6921 return mAggregatedPartialWakelockTimer;
6922 }
6923
6924 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006925 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006926 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 }
6928
6929 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07006930 public Timer getMulticastWakelockStats() {
6931 return mWifiMulticastTimer;
6932 }
6933
6934 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006935 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006936 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006937 }
6938
6939 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006940 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006941 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006942 }
6943
6944 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006945 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
6946 return mJobCompletions;
6947 }
6948
6949 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07006950 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 return mSensorStats;
6952 }
6953
6954 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006955 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006956 return mProcessStats;
6957 }
6958
6959 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006960 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006961 return mPackageStats;
6962 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006963
6964 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 public int getUid() {
6966 return mUid;
6967 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006968
6969 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006970 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006971 if (!mWifiRunning) {
6972 mWifiRunning = true;
6973 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006974 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
6975 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006976 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006977 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006978 }
6979 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006980
Dianne Hackborn617f8772009-03-31 15:04:46 -07006981 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006982 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006983 if (mWifiRunning) {
6984 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006985 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006986 }
6987 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006988
Dianne Hackborn617f8772009-03-31 15:04:46 -07006989 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006990 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006991 if (!mFullWifiLockOut) {
6992 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006993 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006994 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
6995 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006996 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006997 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006998 }
6999 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007000
The Android Open Source Project10592532009-03-18 17:39:46 -07007001 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007002 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007003 if (mFullWifiLockOut) {
7004 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007005 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007006 }
7007 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007008
The Android Open Source Project10592532009-03-18 17:39:46 -07007009 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007010 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007011 if (!mWifiScanStarted) {
7012 mWifiScanStarted = true;
7013 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007014 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7015 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
7016 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007017 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007018 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007019 }
7020 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007021
The Android Open Source Project10592532009-03-18 17:39:46 -07007022 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007023 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007024 if (mWifiScanStarted) {
7025 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007026 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007027 }
7028 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007029
7030 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007031 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007032 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007033 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007034 csph = csph >> 3;
7035 bin++;
7036 }
7037
7038 if (mWifiBatchedScanBinStarted == bin) return;
7039
7040 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7041 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007042 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007043 }
7044 mWifiBatchedScanBinStarted = bin;
7045 if (mWifiBatchedScanTimer[bin] == null) {
7046 makeWifiBatchedScanBin(bin, null);
7047 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007048 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007049 }
7050
7051 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007052 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007053 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7054 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007055 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007056 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7057 }
7058 }
7059
7060 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007061 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007062 if (!mWifiMulticastEnabled) {
7063 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007064 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007065 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7066 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007067 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007068 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007069 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007070 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7071 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007072 }
7073 }
7074
7075 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007076 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007077 if (mWifiMulticastEnabled) {
7078 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007079 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007080 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007081 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7082 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007083 }
7084 }
7085
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007086 @Override
7087 public ControllerActivityCounter getWifiControllerActivity() {
7088 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007089 }
7090
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007091 @Override
7092 public ControllerActivityCounter getBluetoothControllerActivity() {
7093 return mBluetoothControllerActivity;
7094 }
7095
7096 @Override
7097 public ControllerActivityCounter getModemControllerActivity() {
7098 return mModemControllerActivity;
7099 }
7100
7101 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7102 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007103 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007104 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007105 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007106 return mWifiControllerActivity;
7107 }
7108
7109 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7110 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007111 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007112 NUM_BT_TX_LEVELS);
7113 }
7114 return mBluetoothControllerActivity;
7115 }
7116
7117 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7118 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007119 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007120 ModemActivityInfo.TX_POWER_LEVELS);
7121 }
7122 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007123 }
7124
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007125 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7126 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007127 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7128 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007129 }
7130 return mAudioTurnedOnTimer;
7131 }
7132
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007133 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007134 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007135 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7136 StatsLog.AUDIO_STATE_CHANGED__STATE__ON);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007137 }
7138
7139 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7140 if (mAudioTurnedOnTimer != null) {
7141 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007142 if (!mAudioTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08007143 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7144 StatsLog.AUDIO_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007145 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007146 }
7147 }
7148
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007149 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7150 if (mAudioTurnedOnTimer != null) {
7151 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007152 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7153 StatsLog.AUDIO_STATE_CHANGED__STATE__OFF);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007154 }
7155 }
7156
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007157 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7158 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007159 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7160 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007161 }
7162 return mVideoTurnedOnTimer;
7163 }
7164
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007165 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007166 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007167 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
7168 StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__ON);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007169 }
7170
7171 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7172 if (mVideoTurnedOnTimer != null) {
7173 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007174 if (!mVideoTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007175 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(),
Bookatz90867622018-01-31 15:05:57 -08007176 null, StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007177 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007178 }
7179 }
7180
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007181 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7182 if (mVideoTurnedOnTimer != null) {
7183 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007184 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08007185 StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__OFF);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007186 }
7187 }
7188
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007189 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7190 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007191 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7192 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007193 }
7194 return mFlashlightTurnedOnTimer;
7195 }
7196
7197 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7198 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007199 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7200 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__ON);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007201 }
7202
7203 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7204 if (mFlashlightTurnedOnTimer != null) {
7205 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007206 if (!mFlashlightTurnedOnTimer.isRunningLocked()) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08007207 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08007208 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007209 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007210 }
7211 }
7212
7213 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7214 if (mFlashlightTurnedOnTimer != null) {
7215 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007216 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7217 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__OFF);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007218 }
7219 }
7220
7221 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7222 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007223 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7224 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007225 }
7226 return mCameraTurnedOnTimer;
7227 }
7228
7229 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7230 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007231 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7232 StatsLog.CAMERA_STATE_CHANGED__STATE__ON);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007233 }
7234
7235 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7236 if (mCameraTurnedOnTimer != null) {
7237 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007238 if (!mCameraTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08007239 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7240 StatsLog.CAMERA_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007241 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007242 }
7243 }
7244
7245 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7246 if (mCameraTurnedOnTimer != null) {
7247 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007248 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7249 StatsLog.CAMERA_STATE_CHANGED__STATE__OFF);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007250 }
7251 }
7252
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007253 public StopwatchTimer createForegroundActivityTimerLocked() {
7254 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007255 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7256 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007257 }
7258 return mForegroundActivityTimer;
7259 }
7260
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007261 public StopwatchTimer createForegroundServiceTimerLocked() {
7262 if (mForegroundServiceTimer == null) {
7263 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7264 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7265 }
7266 return mForegroundServiceTimer;
7267 }
7268
Bookatzc8c44962017-05-11 12:12:54 -07007269 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7270 if (mAggregatedPartialWakelockTimer == null) {
7271 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7272 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7273 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7274 }
7275 return mAggregatedPartialWakelockTimer;
7276 }
7277
Bookatz867c0d72017-03-07 18:23:42 -08007278 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007279 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007280 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7281 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7282 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007283 }
7284 return mBluetoothScanTimer;
7285 }
7286
Bookatzb1f04f32017-05-19 13:57:32 -07007287 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7288 if (mBluetoothUnoptimizedScanTimer == null) {
7289 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7290 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7291 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7292 }
7293 return mBluetoothUnoptimizedScanTimer;
7294 }
7295
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007296 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7297 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007298 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007299 if (isUnoptimized) {
7300 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7301 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007302 }
7303
Bookatz94c5a312017-07-11 16:49:17 -07007304 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007305 if (mBluetoothScanTimer != null) {
7306 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7307 }
Bookatz94c5a312017-07-11 16:49:17 -07007308 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007309 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7310 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007311 }
7312
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007313 public void addBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7314 if (mAllBluetoothChains == null) {
7315 mAllBluetoothChains = new ArrayList<WorkChain>(4);
7316 }
7317
7318 if (isUnoptimized && mUnoptimizedBluetoothChains == null) {
7319 mUnoptimizedBluetoothChains = new ArrayList<WorkChain>(4);
7320 }
7321
7322 mAllBluetoothChains.add(workChain);
7323 if (isUnoptimized) {
7324 mUnoptimizedBluetoothChains.add(workChain);
7325 }
7326 }
7327
7328 public void removeBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7329 if (mAllBluetoothChains != null) {
7330 mAllBluetoothChains.remove(workChain);
7331 }
7332
7333 if (isUnoptimized && mUnoptimizedBluetoothChains != null) {
7334 mUnoptimizedBluetoothChains.remove(workChain);
7335 }
7336 }
7337
7338 public List<WorkChain> getAllBluetoothWorkChains() {
7339 return mAllBluetoothChains;
7340 }
7341
7342 public List<WorkChain> getUnoptimizedBluetoothWorkChains() {
7343 return mUnoptimizedBluetoothChains;
7344 }
7345
7346
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007347 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7348 if (mBluetoothScanTimer != null) {
7349 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7350 }
Bookatzb1f04f32017-05-19 13:57:32 -07007351 if (mBluetoothUnoptimizedScanTimer != null) {
7352 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7353 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007354 }
7355
Bookatz956f36bf2017-04-28 09:48:17 -07007356 public Counter createBluetoothScanResultCounterLocked() {
7357 if (mBluetoothScanResultCounter == null) {
7358 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7359 }
7360 return mBluetoothScanResultCounter;
7361 }
7362
Bookatzb1f04f32017-05-19 13:57:32 -07007363 public Counter createBluetoothScanResultBgCounterLocked() {
7364 if (mBluetoothScanResultBgCounter == null) {
7365 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7366 }
7367 return mBluetoothScanResultBgCounter;
7368 }
7369
Bookatz4ebc0642017-05-11 12:21:19 -07007370 public void noteBluetoothScanResultsLocked(int numNewResults) {
7371 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007372 // Uses background timebase, so the count will only be incremented if uid in background.
7373 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007374 }
7375
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007376 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007377 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007378 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007379 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007380 }
7381
7382 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007383 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007384 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007385 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007386 }
7387 }
7388
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007389 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7390 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7391 }
7392
7393 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7394 if (mForegroundServiceTimer != null) {
7395 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7396 }
7397 }
7398
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007399 public BatchTimer createVibratorOnTimerLocked() {
7400 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007401 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7402 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007403 }
7404 return mVibratorOnTimer;
7405 }
7406
7407 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007408 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007409 }
7410
7411 public void noteVibratorOffLocked() {
7412 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007413 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007414 }
7415 }
7416
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007417 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007418 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007419 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007420 return 0;
7421 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007422 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007423 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007424
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007425 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007426 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007427 if (mFullWifiLockTimer == null) {
7428 return 0;
7429 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007430 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007431 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007432
7433 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007434 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007435 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007436 return 0;
7437 }
Bookatzaa4594a2017-03-24 12:39:56 -07007438 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007439 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007440
7441 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007442 public int getWifiScanCount(int which) {
7443 if (mWifiScanTimer == null) {
7444 return 0;
7445 }
Bookatzaa4594a2017-03-24 12:39:56 -07007446 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007447 }
7448
7449 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007450 public Timer getWifiScanTimer() {
7451 return mWifiScanTimer;
7452 }
7453
7454 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007455 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007456 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007457 return 0;
7458 }
7459 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7460 }
7461
7462 @Override
7463 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7464 if (mWifiScanTimer == null) {
7465 return 0;
7466 }
7467 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007468 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007469 }
7470
7471 @Override
7472 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007473 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007474 return 0;
7475 }
7476 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7477 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007478 }
7479
7480 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007481 public Timer getWifiScanBackgroundTimer() {
7482 if (mWifiScanTimer == null) {
7483 return null;
7484 }
7485 return mWifiScanTimer.getSubTimer();
7486 }
7487
7488 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007489 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007490 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7491 if (mWifiBatchedScanTimer[csphBin] == null) {
7492 return 0;
7493 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007494 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007495 }
7496
7497 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007498 public int getWifiBatchedScanCount(int csphBin, int which) {
7499 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7500 if (mWifiBatchedScanTimer[csphBin] == null) {
7501 return 0;
7502 }
7503 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7504 }
7505
7506 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007507 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007508 if (mWifiMulticastTimer == null) {
7509 return 0;
7510 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007511 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007512 }
7513
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007514 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007515 public Timer getAudioTurnedOnTimer() {
7516 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007517 }
7518
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007519 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007520 public Timer getVideoTurnedOnTimer() {
7521 return mVideoTurnedOnTimer;
7522 }
7523
7524 @Override
7525 public Timer getFlashlightTurnedOnTimer() {
7526 return mFlashlightTurnedOnTimer;
7527 }
7528
7529 @Override
7530 public Timer getCameraTurnedOnTimer() {
7531 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007532 }
7533
Dianne Hackborn617f8772009-03-31 15:04:46 -07007534 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007535 public Timer getForegroundActivityTimer() {
7536 return mForegroundActivityTimer;
7537 }
7538
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007539 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007540 public Timer getForegroundServiceTimer() {
7541 return mForegroundServiceTimer;
7542 }
7543
7544 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007545 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007546 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007547 }
7548
7549 @Override
7550 public Timer getBluetoothScanBackgroundTimer() {
7551 if (mBluetoothScanTimer == null) {
7552 return null;
7553 }
7554 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007555 }
7556
Bookatz956f36bf2017-04-28 09:48:17 -07007557 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007558 public Timer getBluetoothUnoptimizedScanTimer() {
7559 return mBluetoothUnoptimizedScanTimer;
7560 }
7561
7562 @Override
7563 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7564 if (mBluetoothUnoptimizedScanTimer == null) {
7565 return null;
7566 }
7567 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7568 }
7569
7570 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007571 public Counter getBluetoothScanResultCounter() {
7572 return mBluetoothScanResultCounter;
7573 }
7574
Bookatzb1f04f32017-05-19 13:57:32 -07007575 @Override
7576 public Counter getBluetoothScanResultBgCounter() {
7577 return mBluetoothScanResultBgCounter;
7578 }
7579
Dianne Hackborn61659e52014-07-09 16:13:01 -07007580 void makeProcessState(int i, Parcel in) {
7581 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7582
7583 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007584 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7585 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007586 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007587 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7588 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007589 }
7590 }
7591
7592 @Override
7593 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7594 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7595 if (mProcessStateTimer[state] == null) {
7596 return 0;
7597 }
7598 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7599 }
7600
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007601 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007602 public Timer getProcessStateTimer(int state) {
7603 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7604 return mProcessStateTimer[state];
7605 }
7606
7607 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007608 public Timer getVibratorOnTimer() {
7609 return mVibratorOnTimer;
7610 }
7611
7612 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007613 public void noteUserActivityLocked(int type) {
7614 if (mUserActivityCounters == null) {
7615 initUserActivityLocked();
7616 }
Jeff Browndf693de2012-07-27 12:03:38 -07007617 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7618 mUserActivityCounters[type].stepAtomic();
7619 } else {
7620 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7621 new Throwable());
7622 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007623 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007624
Dianne Hackborn617f8772009-03-31 15:04:46 -07007625 @Override
7626 public boolean hasUserActivity() {
7627 return mUserActivityCounters != null;
7628 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007629
Dianne Hackborn617f8772009-03-31 15:04:46 -07007630 @Override
7631 public int getUserActivityCount(int type, int which) {
7632 if (mUserActivityCounters == null) {
7633 return 0;
7634 }
Evan Millarc64edde2009-04-18 12:26:32 -07007635 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007636 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007637
Robert Greenwalta029ea12013-09-25 16:38:12 -07007638 void makeWifiBatchedScanBin(int i, Parcel in) {
7639 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7640
Joe Onoratoabded112016-02-08 16:49:39 -08007641 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007642 if (collected == null) {
7643 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007644 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007645 }
7646 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007647 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7648 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007649 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007650 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7651 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007652 }
7653 }
7654
7655
Dianne Hackborn617f8772009-03-31 15:04:46 -07007656 void initUserActivityLocked() {
7657 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7658 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007659 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007660 }
7661 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007662
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007663 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7664 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007665 initNetworkActivityLocked();
7666 }
7667 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007668 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7669 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007670 } else {
7671 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7672 new Throwable());
7673 }
7674 }
7675
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007676 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7677 if (mNetworkByteActivityCounters == null) {
7678 initNetworkActivityLocked();
7679 }
7680 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7681 mMobileRadioActiveCount.addCountLocked(1);
7682 }
7683
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007684 @Override
7685 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007686 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007687 }
7688
7689 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007690 public long getNetworkActivityBytes(int type, int which) {
7691 if (mNetworkByteActivityCounters != null && type >= 0
7692 && type < mNetworkByteActivityCounters.length) {
7693 return mNetworkByteActivityCounters[type].getCountLocked(which);
7694 } else {
7695 return 0;
7696 }
7697 }
7698
7699 @Override
7700 public long getNetworkActivityPackets(int type, int which) {
7701 if (mNetworkPacketActivityCounters != null && type >= 0
7702 && type < mNetworkPacketActivityCounters.length) {
7703 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007704 } else {
7705 return 0;
7706 }
7707 }
7708
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007709 @Override
7710 public long getMobileRadioActiveTime(int which) {
7711 return mMobileRadioActiveTime != null
7712 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7713 }
7714
7715 @Override
7716 public int getMobileRadioActiveCount(int which) {
7717 return mMobileRadioActiveCount != null
7718 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7719 }
7720
Adam Lesinskie08af192015-03-25 16:42:59 -07007721 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007722 public long getUserCpuTimeUs(int which) {
7723 return mUserCpuTime.getCountLocked(which);
7724 }
7725
7726 @Override
7727 public long getSystemCpuTimeUs(int which) {
7728 return mSystemCpuTime.getCountLocked(which);
7729 }
7730
7731 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007732 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007733 if (mCpuClusterSpeedTimesUs != null) {
7734 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7735 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7736 if (cpuSpeedTimesUs != null) {
7737 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7738 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007739 if (c != null) {
7740 return c.getCountLocked(which);
7741 }
7742 }
7743 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007744 }
7745 }
7746 return 0;
7747 }
7748
Adam Lesinski5f056f62016-07-14 16:56:08 -07007749 public void noteMobileRadioApWakeupLocked() {
7750 if (mMobileRadioApWakeupCount == null) {
7751 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7752 }
7753 mMobileRadioApWakeupCount.addCountLocked(1);
7754 }
7755
7756 @Override
7757 public long getMobileRadioApWakeupCount(int which) {
7758 if (mMobileRadioApWakeupCount != null) {
7759 return mMobileRadioApWakeupCount.getCountLocked(which);
7760 }
7761 return 0;
7762 }
7763
7764 public void noteWifiRadioApWakeupLocked() {
7765 if (mWifiRadioApWakeupCount == null) {
7766 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7767 }
7768 mWifiRadioApWakeupCount.addCountLocked(1);
7769 }
7770
7771 @Override
7772 public long getWifiRadioApWakeupCount(int which) {
7773 if (mWifiRadioApWakeupCount != null) {
7774 return mWifiRadioApWakeupCount.getCountLocked(which);
7775 }
7776 return 0;
7777 }
7778
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007779 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007780 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7781 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007782 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007783 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7784 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007785 }
Joe Onoratoabded112016-02-08 16:49:39 -08007786 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7787 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007789
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007790 /**
7791 * Clear all stats for this uid. Returns true if the uid is completely
7792 * inactive so can be dropped.
7793 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007794 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007795 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007796 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007797
Bookatz993a0be2017-07-21 09:03:23 -07007798 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7799 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7800
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007801 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007802 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007803 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007804 }
7805 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007806 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007807 active |= mFullWifiLockOut;
7808 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007809 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007810 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007811 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007812 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007813 if (mWifiBatchedScanTimer != null) {
7814 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7815 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007816 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007817 }
7818 }
7819 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7820 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007821 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007822 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007823 active |= mWifiMulticastEnabled;
7824 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007825
7826 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7827 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7828 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7829 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7830 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007831 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007832 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007833 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007834 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007835 if (mBluetoothScanResultCounter != null) {
7836 mBluetoothScanResultCounter.reset(false);
7837 }
Bookatzb1f04f32017-05-19 13:57:32 -07007838 if (mBluetoothScanResultBgCounter != null) {
7839 mBluetoothScanResultBgCounter.reset(false);
7840 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007841
Dianne Hackborn61659e52014-07-09 16:13:01 -07007842 if (mProcessStateTimer != null) {
7843 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7844 if (mProcessStateTimer[i] != null) {
7845 active |= !mProcessStateTimer[i].reset(false);
7846 }
7847 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007848 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007849 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007850 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007851 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007852 mVibratorOnTimer.detach();
7853 mVibratorOnTimer = null;
7854 } else {
7855 active = true;
7856 }
7857 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007858
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007859 if (mUserActivityCounters != null) {
7860 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7861 mUserActivityCounters[i].reset(false);
7862 }
7863 }
7864
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007865 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007866 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007867 mNetworkByteActivityCounters[i].reset(false);
7868 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007869 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007870 mMobileRadioActiveTime.reset(false);
7871 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007872 }
7873
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007874 if (mWifiControllerActivity != null) {
7875 mWifiControllerActivity.reset(false);
7876 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007877
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007878 if (mBluetoothControllerActivity != null) {
7879 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007880 }
7881
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007882 if (mModemControllerActivity != null) {
7883 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007884 }
7885
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007886 mUserCpuTime.reset(false);
7887 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007888
Sudheer Shankaaf857412017-07-21 00:14:24 -07007889 if (mCpuClusterSpeedTimesUs != null) {
7890 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007891 if (speeds != null) {
7892 for (LongSamplingCounter speed : speeds) {
7893 if (speed != null) {
7894 speed.reset(false);
7895 }
7896 }
7897 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007898 }
7899 }
7900
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007901 if (mCpuFreqTimeMs != null) {
7902 mCpuFreqTimeMs.reset(false);
7903 }
7904 if (mScreenOffCpuFreqTimeMs != null) {
7905 mScreenOffCpuFreqTimeMs.reset(false);
7906 }
7907
Mike Ma3d422c32017-10-25 11:08:57 -07007908 mCpuActiveTimeMs.reset(false);
7909 mCpuClusterTimesMs.reset(false);
7910
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007911 if (mProcStateTimeMs != null) {
7912 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7913 if (counters != null) {
7914 counters.reset(false);
7915 }
7916 }
7917 }
7918 if (mProcStateScreenOffTimeMs != null) {
7919 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7920 if (counters != null) {
7921 counters.reset(false);
7922 }
7923 }
7924 }
7925
Adam Lesinski5f056f62016-07-14 16:56:08 -07007926 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
7927 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
7928
Dianne Hackbornd953c532014-08-16 18:17:38 -07007929 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7930 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
7931 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007932 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007933 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007934 } else {
7935 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007936 }
7937 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007938 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07007939 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007940 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07007941 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007942 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007943 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007944 timer.detach();
7945 } else {
7946 active = true;
7947 }
7948 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007949 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07007950 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007951 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07007952 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007953 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007954 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007955 timer.detach();
7956 } else {
7957 active = true;
7958 }
7959 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007960 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007961 mJobCompletions.clear();
Dianne Hackborn61659e52014-07-09 16:13:01 -07007962 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
7963 Sensor s = mSensorStats.valueAt(ise);
7964 if (s.reset()) {
7965 mSensorStats.removeAt(ise);
7966 } else {
7967 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007968 }
7969 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07007970 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
7971 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08007972 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007973 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007974 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007975 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007976 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007977 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007978 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007979 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007980 } else {
7981 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007982 }
7983 }
7984 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007985 if (mPackageStats.size() > 0) {
7986 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
7987 while (it.hasNext()) {
7988 Map.Entry<String, Pkg> pkgEntry = it.next();
7989 Pkg p = pkgEntry.getValue();
7990 p.detach();
7991 if (p.mServiceStats.size() > 0) {
7992 Iterator<Map.Entry<String, Pkg.Serv>> it2
7993 = p.mServiceStats.entrySet().iterator();
7994 while (it2.hasNext()) {
7995 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
7996 servEntry.getValue().detach();
7997 }
7998 }
7999 }
8000 mPackageStats.clear();
8001 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008002
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008003 mLastStepUserTime = mLastStepSystemTime = 0;
8004 mCurStepUserTime = mCurStepSystemTime = 0;
8005
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008006 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008007 if (mWifiRunningTimer != null) {
8008 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008009 }
8010 if (mFullWifiLockTimer != null) {
8011 mFullWifiLockTimer.detach();
8012 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008013 if (mWifiScanTimer != null) {
8014 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008015 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008016 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8017 if (mWifiBatchedScanTimer[i] != null) {
8018 mWifiBatchedScanTimer[i].detach();
8019 }
8020 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008021 if (mWifiMulticastTimer != null) {
8022 mWifiMulticastTimer.detach();
8023 }
8024 if (mAudioTurnedOnTimer != null) {
8025 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008026 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008027 }
8028 if (mVideoTurnedOnTimer != null) {
8029 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008030 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008031 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008032 if (mFlashlightTurnedOnTimer != null) {
8033 mFlashlightTurnedOnTimer.detach();
8034 mFlashlightTurnedOnTimer = null;
8035 }
8036 if (mCameraTurnedOnTimer != null) {
8037 mCameraTurnedOnTimer.detach();
8038 mCameraTurnedOnTimer = null;
8039 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008040 if (mForegroundActivityTimer != null) {
8041 mForegroundActivityTimer.detach();
8042 mForegroundActivityTimer = null;
8043 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008044 if (mForegroundServiceTimer != null) {
8045 mForegroundServiceTimer.detach();
8046 mForegroundServiceTimer = null;
8047 }
Bookatzc8c44962017-05-11 12:12:54 -07008048 if (mAggregatedPartialWakelockTimer != null) {
8049 mAggregatedPartialWakelockTimer.detach();
8050 mAggregatedPartialWakelockTimer = null;
8051 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008052 if (mBluetoothScanTimer != null) {
8053 mBluetoothScanTimer.detach();
8054 mBluetoothScanTimer = null;
8055 }
Bookatzb1f04f32017-05-19 13:57:32 -07008056 if (mBluetoothUnoptimizedScanTimer != null) {
8057 mBluetoothUnoptimizedScanTimer.detach();
8058 mBluetoothUnoptimizedScanTimer = null;
8059 }
Bookatz956f36bf2017-04-28 09:48:17 -07008060 if (mBluetoothScanResultCounter != null) {
8061 mBluetoothScanResultCounter.detach();
8062 mBluetoothScanResultCounter = null;
8063 }
Bookatzb1f04f32017-05-19 13:57:32 -07008064 if (mBluetoothScanResultBgCounter != null) {
8065 mBluetoothScanResultBgCounter.detach();
8066 mBluetoothScanResultBgCounter = null;
8067 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008068 if (mUserActivityCounters != null) {
8069 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8070 mUserActivityCounters[i].detach();
8071 }
8072 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008073 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008074 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008075 mNetworkByteActivityCounters[i].detach();
8076 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008077 }
8078 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008079
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008080 if (mWifiControllerActivity != null) {
8081 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008082 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008083
8084 if (mBluetoothControllerActivity != null) {
8085 mBluetoothControllerActivity.detach();
8086 }
8087
8088 if (mModemControllerActivity != null) {
8089 mModemControllerActivity.detach();
8090 }
8091
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008092 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008093
8094 mUserCpuTime.detach();
8095 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008096
Sudheer Shankaaf857412017-07-21 00:14:24 -07008097 if (mCpuClusterSpeedTimesUs != null) {
8098 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008099 if (cpuSpeeds != null) {
8100 for (LongSamplingCounter c : cpuSpeeds) {
8101 if (c != null) {
8102 c.detach();
8103 }
8104 }
8105 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008106 }
8107 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008108
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008109 if (mCpuFreqTimeMs != null) {
8110 mCpuFreqTimeMs.detach();
8111 }
8112 if (mScreenOffCpuFreqTimeMs != null) {
8113 mScreenOffCpuFreqTimeMs.detach();
8114 }
Mike Ma3d422c32017-10-25 11:08:57 -07008115 mCpuActiveTimeMs.detach();
8116 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008117
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008118 if (mProcStateTimeMs != null) {
8119 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8120 if (counters != null) {
8121 counters.detach();
8122 }
8123 }
8124 }
8125 if (mProcStateScreenOffTimeMs != null) {
8126 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8127 if (counters != null) {
8128 counters.detach();
8129 }
8130 }
8131 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008132 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8133 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008134 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008135
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008136 return !active;
8137 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008138
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008139 void writeJobCompletionsToParcelLocked(Parcel out) {
8140 int NJC = mJobCompletions.size();
8141 out.writeInt(NJC);
8142 for (int ijc=0; ijc<NJC; ijc++) {
8143 out.writeString(mJobCompletions.keyAt(ijc));
8144 SparseIntArray types = mJobCompletions.valueAt(ijc);
8145 int NT = types.size();
8146 out.writeInt(NT);
8147 for (int it=0; it<NT; it++) {
8148 out.writeInt(types.keyAt(it));
8149 out.writeInt(types.valueAt(it));
8150 }
8151 }
8152 }
8153
Bookatz867c0d72017-03-07 18:23:42 -08008154 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8155 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008156 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008157
Dianne Hackbornd953c532014-08-16 18:17:38 -07008158 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8159 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008160 out.writeInt(NW);
8161 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008162 out.writeString(wakeStats.keyAt(iw));
8163 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008164 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 }
8166
Bookatz2bffb5b2017-04-13 11:59:33 -07008167 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008168 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008169 out.writeInt(NS);
8170 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008171 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008172 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008173 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8174 }
8175
Bookatzaa4594a2017-03-24 12:39:56 -07008176 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008177 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008178 out.writeInt(NJ);
8179 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008180 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008181 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008182 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8183 }
8184
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008185 writeJobCompletionsToParcelLocked(out);
8186
Dianne Hackborn61659e52014-07-09 16:13:01 -07008187 int NSE = mSensorStats.size();
8188 out.writeInt(NSE);
8189 for (int ise=0; ise<NSE; ise++) {
8190 out.writeInt(mSensorStats.keyAt(ise));
8191 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008192 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 }
8194
Dianne Hackborn61659e52014-07-09 16:13:01 -07008195 int NP = mProcessStats.size();
8196 out.writeInt(NP);
8197 for (int ip=0; ip<NP; ip++) {
8198 out.writeString(mProcessStats.keyAt(ip));
8199 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008200 proc.writeToParcelLocked(out);
8201 }
8202
8203 out.writeInt(mPackageStats.size());
8204 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8205 out.writeString(pkgEntry.getKey());
8206 Uid.Pkg pkg = pkgEntry.getValue();
8207 pkg.writeToParcelLocked(out);
8208 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008209
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008210 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008211 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008212 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008213 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008214 out.writeInt(0);
8215 }
8216 if (mFullWifiLockTimer != null) {
8217 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008218 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008219 } else {
8220 out.writeInt(0);
8221 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008222 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008223 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008224 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008225 } else {
8226 out.writeInt(0);
8227 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008228 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8229 if (mWifiBatchedScanTimer[i] != null) {
8230 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008231 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008232 } else {
8233 out.writeInt(0);
8234 }
8235 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008236 if (mWifiMulticastTimer != null) {
8237 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008238 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008239 } else {
8240 out.writeInt(0);
8241 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008242
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008243 if (mAudioTurnedOnTimer != null) {
8244 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008245 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008246 } else {
8247 out.writeInt(0);
8248 }
8249 if (mVideoTurnedOnTimer != null) {
8250 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008251 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008252 } else {
8253 out.writeInt(0);
8254 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008255 if (mFlashlightTurnedOnTimer != null) {
8256 out.writeInt(1);
8257 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8258 } else {
8259 out.writeInt(0);
8260 }
8261 if (mCameraTurnedOnTimer != null) {
8262 out.writeInt(1);
8263 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8264 } else {
8265 out.writeInt(0);
8266 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008267 if (mForegroundActivityTimer != null) {
8268 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008269 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008270 } else {
8271 out.writeInt(0);
8272 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008273 if (mForegroundServiceTimer != null) {
8274 out.writeInt(1);
8275 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8276 } else {
8277 out.writeInt(0);
8278 }
Bookatzc8c44962017-05-11 12:12:54 -07008279 if (mAggregatedPartialWakelockTimer != null) {
8280 out.writeInt(1);
8281 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8282 } else {
8283 out.writeInt(0);
8284 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008285 if (mBluetoothScanTimer != null) {
8286 out.writeInt(1);
8287 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8288 } else {
8289 out.writeInt(0);
8290 }
Bookatzb1f04f32017-05-19 13:57:32 -07008291 if (mBluetoothUnoptimizedScanTimer != null) {
8292 out.writeInt(1);
8293 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8294 } else {
8295 out.writeInt(0);
8296 }
Bookatz956f36bf2017-04-28 09:48:17 -07008297 if (mBluetoothScanResultCounter != null) {
8298 out.writeInt(1);
8299 mBluetoothScanResultCounter.writeToParcel(out);
8300 } else {
8301 out.writeInt(0);
8302 }
Bookatzb1f04f32017-05-19 13:57:32 -07008303 if (mBluetoothScanResultBgCounter != null) {
8304 out.writeInt(1);
8305 mBluetoothScanResultBgCounter.writeToParcel(out);
8306 } else {
8307 out.writeInt(0);
8308 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008309 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8310 if (mProcessStateTimer[i] != null) {
8311 out.writeInt(1);
8312 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8313 } else {
8314 out.writeInt(0);
8315 }
8316 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008317 if (mVibratorOnTimer != null) {
8318 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008319 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008320 } else {
8321 out.writeInt(0);
8322 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008323 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008324 out.writeInt(1);
8325 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8326 mUserActivityCounters[i].writeToParcel(out);
8327 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008328 } else {
8329 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008330 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008331 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008332 out.writeInt(1);
8333 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008334 mNetworkByteActivityCounters[i].writeToParcel(out);
8335 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008336 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008337 mMobileRadioActiveTime.writeToParcel(out);
8338 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008339 } else {
8340 out.writeInt(0);
8341 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008342
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008343 if (mWifiControllerActivity != null) {
8344 out.writeInt(1);
8345 mWifiControllerActivity.writeToParcel(out, 0);
8346 } else {
8347 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008348 }
8349
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008350 if (mBluetoothControllerActivity != null) {
8351 out.writeInt(1);
8352 mBluetoothControllerActivity.writeToParcel(out, 0);
8353 } else {
8354 out.writeInt(0);
8355 }
8356
8357 if (mModemControllerActivity != null) {
8358 out.writeInt(1);
8359 mModemControllerActivity.writeToParcel(out, 0);
8360 } else {
8361 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008362 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008363
8364 mUserCpuTime.writeToParcel(out);
8365 mSystemCpuTime.writeToParcel(out);
8366
Sudheer Shankaaf857412017-07-21 00:14:24 -07008367 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008368 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008369 out.writeInt(mCpuClusterSpeedTimesUs.length);
8370 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008371 if (cpuSpeeds != null) {
8372 out.writeInt(1);
8373 out.writeInt(cpuSpeeds.length);
8374 for (LongSamplingCounter c : cpuSpeeds) {
8375 if (c != null) {
8376 out.writeInt(1);
8377 c.writeToParcel(out);
8378 } else {
8379 out.writeInt(0);
8380 }
8381 }
8382 } else {
8383 out.writeInt(0);
8384 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008385 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008386 } else {
8387 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008388 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008389
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008390 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8391 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008392
8393 mCpuActiveTimeMs.writeToParcel(out);
8394 mCpuClusterTimesMs.writeToParcel(out);
8395
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008396 if (mProcStateTimeMs != null) {
8397 out.writeInt(mProcStateTimeMs.length);
8398 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8399 LongSamplingCounterArray.writeToParcel(out, counters);
8400 }
8401 } else {
8402 out.writeInt(0);
8403 }
8404 if (mProcStateScreenOffTimeMs != null) {
8405 out.writeInt(mProcStateScreenOffTimeMs.length);
8406 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8407 LongSamplingCounterArray.writeToParcel(out, counters);
8408 }
8409 } else {
8410 out.writeInt(0);
8411 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008412
Adam Lesinski5f056f62016-07-14 16:56:08 -07008413 if (mMobileRadioApWakeupCount != null) {
8414 out.writeInt(1);
8415 mMobileRadioApWakeupCount.writeToParcel(out);
8416 } else {
8417 out.writeInt(0);
8418 }
8419
8420 if (mWifiRadioApWakeupCount != null) {
8421 out.writeInt(1);
8422 mWifiRadioApWakeupCount.writeToParcel(out);
8423 } else {
8424 out.writeInt(0);
8425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008426 }
8427
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008428 void readJobCompletionsFromParcelLocked(Parcel in) {
8429 int numJobCompletions = in.readInt();
8430 mJobCompletions.clear();
8431 for (int j = 0; j < numJobCompletions; j++) {
8432 String jobName = in.readString();
8433 int numTypes = in.readInt();
8434 if (numTypes > 0) {
8435 SparseIntArray types = new SparseIntArray();
8436 for (int k = 0; k < numTypes; k++) {
8437 int type = in.readInt();
8438 int count = in.readInt();
8439 types.put(type, count);
8440 }
8441 mJobCompletions.put(jobName, types);
8442 }
8443 }
8444 }
8445
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008446 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008447 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008448 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008450 int numWakelocks = in.readInt();
8451 mWakelockStats.clear();
8452 for (int j = 0; j < numWakelocks; j++) {
8453 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008454 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008455 wakelock.readFromParcelLocked(
8456 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008457 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458 }
8459
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008460 int numSyncs = in.readInt();
8461 mSyncStats.clear();
8462 for (int j = 0; j < numSyncs; j++) {
8463 String syncName = in.readString();
8464 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008465 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8466 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008467 }
8468 }
8469
8470 int numJobs = in.readInt();
8471 mJobStats.clear();
8472 for (int j = 0; j < numJobs; j++) {
8473 String jobName = in.readString();
8474 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008475 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8476 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008477 }
8478 }
8479
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008480 readJobCompletionsFromParcelLocked(in);
8481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008482 int numSensors = in.readInt();
8483 mSensorStats.clear();
8484 for (int k = 0; k < numSensors; k++) {
8485 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008486 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008487 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8488 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008489 mSensorStats.put(sensorNumber, sensor);
8490 }
8491
8492 int numProcs = in.readInt();
8493 mProcessStats.clear();
8494 for (int k = 0; k < numProcs; k++) {
8495 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008496 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008497 proc.readFromParcelLocked(in);
8498 mProcessStats.put(processName, proc);
8499 }
8500
8501 int numPkgs = in.readInt();
8502 mPackageStats.clear();
8503 for (int l = 0; l < numPkgs; l++) {
8504 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008505 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 pkg.readFromParcelLocked(in);
8507 mPackageStats.put(packageName, pkg);
8508 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008509
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008510 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008511 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008512 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8513 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008514 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008515 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008516 }
8517 mFullWifiLockOut = false;
8518 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008519 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8520 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008521 } else {
8522 mFullWifiLockTimer = null;
8523 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008524 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008525 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008526 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8527 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8528 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008529 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008530 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008531 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008532 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8533 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8534 if (in.readInt() != 0) {
8535 makeWifiBatchedScanBin(i, in);
8536 } else {
8537 mWifiBatchedScanTimer[i] = null;
8538 }
8539 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008540 mWifiMulticastEnabled = false;
8541 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008542 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8543 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008544 } else {
8545 mWifiMulticastTimer = null;
8546 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008547 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008548 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8549 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008550 } else {
8551 mAudioTurnedOnTimer = null;
8552 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008553 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008554 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8555 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008556 } else {
8557 mVideoTurnedOnTimer = null;
8558 }
8559 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008560 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8561 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008562 } else {
8563 mFlashlightTurnedOnTimer = null;
8564 }
8565 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008566 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8567 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008568 } else {
8569 mCameraTurnedOnTimer = null;
8570 }
8571 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008572 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8573 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008574 } else {
8575 mForegroundActivityTimer = null;
8576 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008577 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008578 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8579 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8580 } else {
8581 mForegroundServiceTimer = null;
8582 }
8583 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008584 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8585 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8586 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8587 in);
8588 } else {
8589 mAggregatedPartialWakelockTimer = null;
8590 }
8591 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008592 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8593 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8594 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008595 } else {
8596 mBluetoothScanTimer = null;
8597 }
Bookatz956f36bf2017-04-28 09:48:17 -07008598 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008599 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8600 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8601 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8602 } else {
8603 mBluetoothUnoptimizedScanTimer = null;
8604 }
8605 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008606 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8607 } else {
8608 mBluetoothScanResultCounter = null;
8609 }
Bookatzb1f04f32017-05-19 13:57:32 -07008610 if (in.readInt() != 0) {
8611 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8612 } else {
8613 mBluetoothScanResultBgCounter = null;
8614 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008615 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008616 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8617 if (in.readInt() != 0) {
8618 makeProcessState(i, in);
8619 } else {
8620 mProcessStateTimer[i] = null;
8621 }
8622 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008623 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008624 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8625 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008626 } else {
8627 mVibratorOnTimer = null;
8628 }
8629 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008630 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8631 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008632 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008633 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008634 } else {
8635 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008636 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008637 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008638 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8639 mNetworkPacketActivityCounters
8640 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008641 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008642 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008643 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008644 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008645 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008646 }
Joe Onoratoabded112016-02-08 16:49:39 -08008647 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8648 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008649 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008650 mNetworkByteActivityCounters = null;
8651 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008652 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008653
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008654 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008655 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008656 NUM_WIFI_TX_LEVELS, in);
8657 } else {
8658 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008659 }
8660
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008661 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008662 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008663 NUM_BT_TX_LEVELS, in);
8664 } else {
8665 mBluetoothControllerActivity = null;
8666 }
8667
8668 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008669 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008670 ModemActivityInfo.TX_POWER_LEVELS, in);
8671 } else {
8672 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008673 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008674
Joe Onoratoabded112016-02-08 16:49:39 -08008675 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8676 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008677
Adam Lesinski6832f392015-09-05 18:05:40 -07008678 if (in.readInt() != 0) {
8679 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008680 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008681 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008682 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008683
Sudheer Shankaaf857412017-07-21 00:14:24 -07008684 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008685 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8686 if (in.readInt() != 0) {
8687 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008688 if (mBsi.mPowerProfile != null &&
8689 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008690 throw new ParcelFormatException("Incompatible number of cpu speeds");
8691 }
8692
8693 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008694 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008695 for (int speed = 0; speed < numSpeeds; speed++) {
8696 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008697 cpuSpeeds[speed] = new LongSamplingCounter(
8698 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008699 }
8700 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008701 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008702 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008703 }
8704 }
8705 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008706 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008707 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008708
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008709 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8710 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8711 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008712
Mike Ma3d422c32017-10-25 11:08:57 -07008713 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8714 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8715
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008716 int length = in.readInt();
8717 if (length == NUM_PROCESS_STATE) {
8718 mProcStateTimeMs = new LongSamplingCounterArray[length];
8719 for (int procState = 0; procState < length; ++procState) {
8720 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8721 in, mBsi.mOnBatteryTimeBase);
8722 }
8723 } else {
8724 mProcStateTimeMs = null;
8725 }
8726 length = in.readInt();
8727 if (length == NUM_PROCESS_STATE) {
8728 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8729 for (int procState = 0; procState < length; ++procState) {
8730 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8731 in, mBsi.mOnBatteryScreenOffTimeBase);
8732 }
8733 } else {
8734 mProcStateScreenOffTimeMs = null;
8735 }
8736
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008737 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008738 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8739 } else {
8740 mMobileRadioApWakeupCount = null;
8741 }
8742
8743 if (in.readInt() != 0) {
8744 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8745 } else {
8746 mWifiRadioApWakeupCount = null;
8747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008748 }
8749
8750 /**
8751 * The statistics associated with a particular wake lock.
8752 */
Joe Onoratoabded112016-02-08 16:49:39 -08008753 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8754 /**
8755 * BatteryStatsImpl that we are associated with.
8756 */
8757 protected BatteryStatsImpl mBsi;
8758
8759 /**
8760 * BatteryStatsImpl that we are associated with.
8761 */
8762 protected Uid mUid;
8763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008764 /**
8765 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008766 * 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 -08008767 */
Bookatz5b5ec322017-05-26 09:40:38 -07008768 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769
8770 /**
8771 * How long (in ms) this uid has been keeping the device fully awake.
8772 */
Evan Millarc64edde2009-04-18 12:26:32 -07008773 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774
8775 /**
8776 * How long (in ms) this uid has had a window keeping the device awake.
8777 */
Evan Millarc64edde2009-04-18 12:26:32 -07008778 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779
8780 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008781 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008782 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008783 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008784
Joe Onoratoabded112016-02-08 16:49:39 -08008785 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8786 mBsi = bsi;
8787 mUid = uid;
8788 }
8789
Adam Lesinski9425fe22015-06-19 12:02:13 -07008790 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008791 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8792 * proper timer pool from the given BatteryStatsImpl object.
8793 *
8794 * @param in the Parcel to be read from.
8795 * return a new Timer, or null.
8796 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008797 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8798 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 if (in.readInt() == 0) {
8800 return null;
8801 }
8802
Joe Onoratoabded112016-02-08 16:49:39 -08008803 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008804 }
8805
Joe Onorato92fd23f2016-07-25 11:18:42 -07008806 /**
8807 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8808 * proper timer pool from the given BatteryStatsImpl object.
8809 *
8810 * @param in the Parcel to be read from.
8811 * return a new Timer, or null.
8812 */
Bookatz5b5ec322017-05-26 09:40:38 -07008813 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8814 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008815 if (in.readInt() == 0) {
8816 return null;
8817 }
8818
Bookatz5b5ec322017-05-26 09:40:38 -07008819 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008820 }
8821
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008822 boolean reset() {
8823 boolean wlactive = false;
8824 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008825 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008826 }
8827 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008828 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008829 }
8830 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008831 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008832 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008833 if (mTimerDraw != null) {
8834 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008835 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008836 if (!wlactive) {
8837 if (mTimerFull != null) {
8838 mTimerFull.detach();
8839 mTimerFull = null;
8840 }
8841 if (mTimerPartial != null) {
8842 mTimerPartial.detach();
8843 mTimerPartial = null;
8844 }
8845 if (mTimerWindow != null) {
8846 mTimerWindow.detach();
8847 mTimerWindow = null;
8848 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008849 if (mTimerDraw != null) {
8850 mTimerDraw.detach();
8851 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008852 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008853 }
8854 return !wlactive;
8855 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008856
Bookatz5b5ec322017-05-26 09:40:38 -07008857 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
8858 TimeBase screenOffBgTimeBase, Parcel in) {
8859 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
8860 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008861 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
8862 mBsi.mFullTimers, timeBase, in);
8863 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
8864 mBsi.mWindowTimers, timeBase, in);
8865 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
8866 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 }
8868
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008869 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
8870 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
8871 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
8872 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008873 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008874 }
8875
8876 @Override
8877 public Timer getWakeTime(int type) {
8878 switch (type) {
8879 case WAKE_TYPE_FULL: return mTimerFull;
8880 case WAKE_TYPE_PARTIAL: return mTimerPartial;
8881 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008882 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 default: throw new IllegalArgumentException("type = " + type);
8884 }
8885 }
8886 }
8887
Joe Onoratoabded112016-02-08 16:49:39 -08008888 public static class Sensor extends BatteryStats.Uid.Sensor {
8889 /**
8890 * BatteryStatsImpl that we are associated with.
8891 */
8892 protected BatteryStatsImpl mBsi;
8893
8894 /**
Bookatz867c0d72017-03-07 18:23:42 -08008895 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08008896 */
8897 protected Uid mUid;
8898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008899 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08008900 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008901
Joe Onoratoabded112016-02-08 16:49:39 -08008902 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
8903 mBsi = bsi;
8904 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008905 mHandle = handle;
8906 }
8907
Bookatz867c0d72017-03-07 18:23:42 -08008908 private DualTimer readTimersFromParcel(
8909 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 if (in.readInt() == 0) {
8911 return null;
8912 }
8913
Joe Onoratoabded112016-02-08 16:49:39 -08008914 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07008916 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08008917 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008918 }
Bookatz867c0d72017-03-07 18:23:42 -08008919 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008920 }
8921
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008922 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008923 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008924 mTimer = null;
8925 return true;
8926 }
8927 return false;
8928 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008929
Bookatz867c0d72017-03-07 18:23:42 -08008930 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
8931 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 }
8933
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008934 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07008935 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 }
8937
8938 @Override
8939 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07008940 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008942
8943 @Override
Bookatz867c0d72017-03-07 18:23:42 -08008944 public Timer getSensorBackgroundTime() {
8945 if (mTimer == null) {
8946 return null;
8947 }
8948 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008949 }
8950
8951 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 public int getHandle() {
8953 return mHandle;
8954 }
8955 }
8956
8957 /**
8958 * The statistics associated with a particular process.
8959 */
Joe Onoratoabded112016-02-08 16:49:39 -08008960 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
8961 /**
8962 * BatteryStatsImpl that we are associated with.
8963 */
8964 protected BatteryStatsImpl mBsi;
8965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008966 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008967 * The name of this process.
8968 */
8969 final String mName;
8970
8971 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08008972 * Remains true until removed from the stats.
8973 */
8974 boolean mActive = true;
8975
8976 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008977 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008978 */
8979 long mUserTime;
8980
8981 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008982 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008983 */
8984 long mSystemTime;
8985
8986 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008987 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008988 */
8989 long mForegroundTime;
8990
8991 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008992 * Number of times the process has been started.
8993 */
8994 int mStarts;
8995
8996 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008997 * Number of times the process has crashed.
8998 */
8999 int mNumCrashes;
9000
9001 /**
9002 * Number of times the process has had an ANR.
9003 */
9004 int mNumAnrs;
9005
9006 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009007 * The amount of user time loaded from a previous save.
9008 */
9009 long mLoadedUserTime;
9010
9011 /**
9012 * The amount of system time loaded from a previous save.
9013 */
9014 long mLoadedSystemTime;
9015
9016 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009017 * The amount of foreground time loaded from a previous save.
9018 */
9019 long mLoadedForegroundTime;
9020
9021 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009022 * The number of times the process has started from a previous save.
9023 */
9024 int mLoadedStarts;
9025
9026 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009027 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009029 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009030
9031 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009032 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009033 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009034 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009035
9036 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009037 * The amount of user time when last unplugged.
9038 */
9039 long mUnpluggedUserTime;
9040
9041 /**
9042 * The amount of system time when last unplugged.
9043 */
9044 long mUnpluggedSystemTime;
9045
9046 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009047 * The amount of foreground time since unplugged.
9048 */
9049 long mUnpluggedForegroundTime;
9050
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009051 /**
9052 * The number of times the process has started before unplugged.
9053 */
9054 int mUnpluggedStarts;
9055
Dianne Hackborn61659e52014-07-09 16:13:01 -07009056 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009057 * Number of times the process has crashed before unplugged.
9058 */
9059 int mUnpluggedNumCrashes;
9060
9061 /**
9062 * Number of times the process has had an ANR before unplugged.
9063 */
9064 int mUnpluggedNumAnrs;
9065
Dianne Hackborn287952c2010-09-22 22:34:31 -07009066 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009067
Joe Onoratoabded112016-02-08 16:49:39 -08009068 public Proc(BatteryStatsImpl bsi, String name) {
9069 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009070 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08009071 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009072 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009073
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009074 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009075 mUnpluggedUserTime = mUserTime;
9076 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009077 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009078 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009079 mUnpluggedNumCrashes = mNumCrashes;
9080 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009081 }
9082
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009083 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009085
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009086 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009087 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009088 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009089 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009090
Dianne Hackborn287952c2010-09-22 22:34:31 -07009091 public int countExcessivePowers() {
9092 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009093 }
9094
Dianne Hackborn287952c2010-09-22 22:34:31 -07009095 public ExcessivePower getExcessivePower(int i) {
9096 if (mExcessivePower != null) {
9097 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009098 }
9099 return null;
9100 }
9101
Dianne Hackborn287952c2010-09-22 22:34:31 -07009102 public void addExcessiveCpu(long overTime, long usedTime) {
9103 if (mExcessivePower == null) {
9104 mExcessivePower = new ArrayList<ExcessivePower>();
9105 }
9106 ExcessivePower ew = new ExcessivePower();
9107 ew.type = ExcessivePower.TYPE_CPU;
9108 ew.overTime = overTime;
9109 ew.usedTime = usedTime;
9110 mExcessivePower.add(ew);
9111 }
9112
9113 void writeExcessivePowerToParcelLocked(Parcel out) {
9114 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009115 out.writeInt(0);
9116 return;
9117 }
9118
Dianne Hackborn287952c2010-09-22 22:34:31 -07009119 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009120 out.writeInt(N);
9121 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009122 ExcessivePower ew = mExcessivePower.get(i);
9123 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009124 out.writeLong(ew.overTime);
9125 out.writeLong(ew.usedTime);
9126 }
9127 }
9128
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009129 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009130 final int N = in.readInt();
9131 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009132 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009133 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009134 }
9135
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009136 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009137 throw new ParcelFormatException(
9138 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009139 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009140
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009141 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009142 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009143 ExcessivePower ew = new ExcessivePower();
9144 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009145 ew.overTime = in.readLong();
9146 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009147 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009148 }
9149 }
9150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009151 void writeToParcelLocked(Parcel out) {
9152 out.writeLong(mUserTime);
9153 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009154 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009155 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009156 out.writeInt(mNumCrashes);
9157 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009158 out.writeLong(mLoadedUserTime);
9159 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009160 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009161 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009162 out.writeInt(mLoadedNumCrashes);
9163 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009164 out.writeLong(mUnpluggedUserTime);
9165 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009166 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009167 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009168 out.writeInt(mUnpluggedNumCrashes);
9169 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009170 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009171 }
9172
9173 void readFromParcelLocked(Parcel in) {
9174 mUserTime = in.readLong();
9175 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009176 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009177 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009178 mNumCrashes = in.readInt();
9179 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009180 mLoadedUserTime = in.readLong();
9181 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009182 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009183 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009184 mLoadedNumCrashes = in.readInt();
9185 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009186 mUnpluggedUserTime = in.readLong();
9187 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009188 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009189 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009190 mUnpluggedNumCrashes = in.readInt();
9191 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009192 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 }
9194
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009195 public void addCpuTimeLocked(int utime, int stime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009196 mUserTime += utime;
9197 mSystemTime += stime;
9198 }
9199
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009200 public void addForegroundTimeLocked(long ttime) {
9201 mForegroundTime += ttime;
9202 }
9203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009204 public void incStartsLocked() {
9205 mStarts++;
9206 }
9207
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009208 public void incNumCrashesLocked() {
9209 mNumCrashes++;
9210 }
9211
9212 public void incNumAnrsLocked() {
9213 mNumAnrs++;
9214 }
9215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009216 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009217 public boolean isActive() {
9218 return mActive;
9219 }
9220
9221 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009222 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009223 long val = mUserTime;
9224 if (which == STATS_CURRENT) {
9225 val -= mLoadedUserTime;
9226 } else if (which == STATS_SINCE_UNPLUGGED) {
9227 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009228 }
9229 return val;
9230 }
9231
9232 @Override
9233 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009234 long val = mSystemTime;
9235 if (which == STATS_CURRENT) {
9236 val -= mLoadedSystemTime;
9237 } else if (which == STATS_SINCE_UNPLUGGED) {
9238 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009239 }
9240 return val;
9241 }
9242
9243 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009244 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009245 long val = mForegroundTime;
9246 if (which == STATS_CURRENT) {
9247 val -= mLoadedForegroundTime;
9248 } else if (which == STATS_SINCE_UNPLUGGED) {
9249 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009250 }
9251 return val;
9252 }
9253
9254 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009255 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009256 int val = mStarts;
9257 if (which == STATS_CURRENT) {
9258 val -= mLoadedStarts;
9259 } else if (which == STATS_SINCE_UNPLUGGED) {
9260 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009261 }
9262 return val;
9263 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009264
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009265 @Override
9266 public int getNumCrashes(int which) {
9267 int val = mNumCrashes;
9268 if (which == STATS_CURRENT) {
9269 val -= mLoadedNumCrashes;
9270 } else if (which == STATS_SINCE_UNPLUGGED) {
9271 val -= mUnpluggedNumCrashes;
9272 }
9273 return val;
9274 }
9275
9276 @Override
9277 public int getNumAnrs(int which) {
9278 int val = mNumAnrs;
9279 if (which == STATS_CURRENT) {
9280 val -= mLoadedNumAnrs;
9281 } else if (which == STATS_SINCE_UNPLUGGED) {
9282 val -= mUnpluggedNumAnrs;
9283 }
9284 return val;
9285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286 }
9287
9288 /**
9289 * The statistics associated with a particular package.
9290 */
Joe Onoratoabded112016-02-08 16:49:39 -08009291 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9292 /**
9293 * BatteryStatsImpl that we are associated with.
9294 */
9295 protected BatteryStatsImpl mBsi;
9296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009298 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009299 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009300 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009301 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009302
9303 /**
9304 * The statics we have collected for this package's services.
9305 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009306 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009307
Joe Onoratoabded112016-02-08 16:49:39 -08009308 public Pkg(BatteryStatsImpl bsi) {
9309 mBsi = bsi;
9310 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009311 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009312
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009313 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009314 }
9315
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009316 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009318
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009319 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009320 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009321 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009323 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009324 int numWA = in.readInt();
9325 mWakeupAlarms.clear();
9326 for (int i=0; i<numWA; i++) {
9327 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009328 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009330
9331 int numServs = in.readInt();
9332 mServiceStats.clear();
9333 for (int m = 0; m < numServs; m++) {
9334 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009335 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009336 mServiceStats.put(serviceName, serv);
9337
9338 serv.readFromParcelLocked(in);
9339 }
9340 }
9341
9342 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009343 int numWA = mWakeupAlarms.size();
9344 out.writeInt(numWA);
9345 for (int i=0; i<numWA; i++) {
9346 out.writeString(mWakeupAlarms.keyAt(i));
9347 mWakeupAlarms.valueAt(i).writeToParcel(out);
9348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009349
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009350 final int NS = mServiceStats.size();
9351 out.writeInt(NS);
9352 for (int i=0; i<NS; i++) {
9353 out.writeString(mServiceStats.keyAt(i));
9354 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009355 serv.writeToParcelLocked(out);
9356 }
9357 }
9358
9359 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009360 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9361 return mWakeupAlarms;
9362 }
9363
9364 public void noteWakeupAlarmLocked(String tag) {
9365 Counter c = mWakeupAlarms.get(tag);
9366 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009367 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009368 mWakeupAlarms.put(tag, c);
9369 }
9370 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009371 }
9372
9373 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009374 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9375 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009376 }
9377
9378 /**
9379 * The statistics associated with a particular service.
9380 */
Joe Onoratoabded112016-02-08 16:49:39 -08009381 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9382 /**
9383 * BatteryStatsImpl that we are associated with.
9384 */
9385 protected BatteryStatsImpl mBsi;
9386
9387 /**
9388 * The android package in which this service resides.
9389 */
9390 protected Pkg mPkg;
9391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009392 /**
9393 * Total time (ms in battery uptime) the service has been left started.
9394 */
Joe Onoratoabded112016-02-08 16:49:39 -08009395 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009396
9397 /**
9398 * If service has been started and not yet stopped, this is
9399 * when it was started.
9400 */
Joe Onoratoabded112016-02-08 16:49:39 -08009401 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009402
9403 /**
9404 * True if we are currently running.
9405 */
Joe Onoratoabded112016-02-08 16:49:39 -08009406 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009407
9408 /**
9409 * Total number of times startService() has been called.
9410 */
Joe Onoratoabded112016-02-08 16:49:39 -08009411 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009412
9413 /**
9414 * Total time (ms in battery uptime) the service has been left launched.
9415 */
Joe Onoratoabded112016-02-08 16:49:39 -08009416 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009417
9418 /**
9419 * If service has been launched and not yet exited, this is
9420 * when it was launched (ms in battery uptime).
9421 */
Joe Onoratoabded112016-02-08 16:49:39 -08009422 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423
9424 /**
9425 * True if we are currently launched.
9426 */
Joe Onoratoabded112016-02-08 16:49:39 -08009427 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009428
9429 /**
9430 * Total number times the service has been launched.
9431 */
Joe Onoratoabded112016-02-08 16:49:39 -08009432 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009433
9434 /**
9435 * The amount of time spent started loaded from a previous save
9436 * (ms in battery uptime).
9437 */
Joe Onoratoabded112016-02-08 16:49:39 -08009438 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009439
9440 /**
9441 * The number of starts loaded from a previous save.
9442 */
Joe Onoratoabded112016-02-08 16:49:39 -08009443 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009444
9445 /**
9446 * The number of launches loaded from a previous save.
9447 */
Joe Onoratoabded112016-02-08 16:49:39 -08009448 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009449
9450 /**
9451 * The amount of time spent started as of the last run (ms
9452 * in battery uptime).
9453 */
Joe Onoratoabded112016-02-08 16:49:39 -08009454 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009455
9456 /**
9457 * The number of starts as of the last run.
9458 */
Joe Onoratoabded112016-02-08 16:49:39 -08009459 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009460
9461 /**
9462 * The number of launches as of the last run.
9463 */
Joe Onoratoabded112016-02-08 16:49:39 -08009464 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009465
9466 /**
9467 * The amount of time spent started when last unplugged (ms
9468 * in battery uptime).
9469 */
Joe Onoratoabded112016-02-08 16:49:39 -08009470 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009471
9472 /**
9473 * The number of starts when last unplugged.
9474 */
Joe Onoratoabded112016-02-08 16:49:39 -08009475 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476
9477 /**
9478 * The number of launches when last unplugged.
9479 */
Joe Onoratoabded112016-02-08 16:49:39 -08009480 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009481
Joe Onoratoabded112016-02-08 16:49:39 -08009482 /**
9483 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9484 */
9485 public Serv(BatteryStatsImpl bsi) {
9486 mBsi = bsi;
9487 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009488 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009489
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009490 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9491 long baseRealtime) {
9492 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009493 mUnpluggedStarts = mStarts;
9494 mUnpluggedLaunches = mLaunches;
9495 }
9496
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009497 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9498 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009499 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009500
Joe Onoratoabded112016-02-08 16:49:39 -08009501 /**
9502 * Remove this Serv as a listener from the time base.
9503 */
9504 public void detach() {
9505 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009506 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009507
Joe Onoratoabded112016-02-08 16:49:39 -08009508 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009509 mStartTime = in.readLong();
9510 mRunningSince = in.readLong();
9511 mRunning = in.readInt() != 0;
9512 mStarts = in.readInt();
9513 mLaunchedTime = in.readLong();
9514 mLaunchedSince = in.readLong();
9515 mLaunched = in.readInt() != 0;
9516 mLaunches = in.readInt();
9517 mLoadedStartTime = in.readLong();
9518 mLoadedStarts = in.readInt();
9519 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009520 mLastStartTime = 0;
9521 mLastStarts = 0;
9522 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009523 mUnpluggedStartTime = in.readLong();
9524 mUnpluggedStarts = in.readInt();
9525 mUnpluggedLaunches = in.readInt();
9526 }
9527
Joe Onoratoabded112016-02-08 16:49:39 -08009528 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009529 out.writeLong(mStartTime);
9530 out.writeLong(mRunningSince);
9531 out.writeInt(mRunning ? 1 : 0);
9532 out.writeInt(mStarts);
9533 out.writeLong(mLaunchedTime);
9534 out.writeLong(mLaunchedSince);
9535 out.writeInt(mLaunched ? 1 : 0);
9536 out.writeInt(mLaunches);
9537 out.writeLong(mLoadedStartTime);
9538 out.writeInt(mLoadedStarts);
9539 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009540 out.writeLong(mUnpluggedStartTime);
9541 out.writeInt(mUnpluggedStarts);
9542 out.writeInt(mUnpluggedLaunches);
9543 }
9544
Joe Onoratoabded112016-02-08 16:49:39 -08009545 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009546 if (!mLaunched) return mLaunchedTime;
9547 return mLaunchedTime + batteryUptime - mLaunchedSince;
9548 }
9549
Joe Onoratoabded112016-02-08 16:49:39 -08009550 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009551 if (!mRunning) return mStartTime;
9552 return mStartTime + batteryUptime - mRunningSince;
9553 }
9554
9555 public void startLaunchedLocked() {
9556 if (!mLaunched) {
9557 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009558 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009559 mLaunched = true;
9560 }
9561 }
9562
9563 public void stopLaunchedLocked() {
9564 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009565 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009566 if (time > 0) {
9567 mLaunchedTime += time;
9568 } else {
9569 mLaunches--;
9570 }
9571 mLaunched = false;
9572 }
9573 }
9574
9575 public void startRunningLocked() {
9576 if (!mRunning) {
9577 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009578 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009579 mRunning = true;
9580 }
9581 }
9582
9583 public void stopRunningLocked() {
9584 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009585 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009586 if (time > 0) {
9587 mStartTime += time;
9588 } else {
9589 mStarts--;
9590 }
9591 mRunning = false;
9592 }
9593 }
9594
9595 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009596 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009597 }
9598
9599 @Override
9600 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009601 int val = mLaunches;
9602 if (which == STATS_CURRENT) {
9603 val -= mLoadedLaunches;
9604 } else if (which == STATS_SINCE_UNPLUGGED) {
9605 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009607 return val;
9608 }
9609
9610 @Override
9611 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009612 long val = getStartTimeToNowLocked(now);
9613 if (which == STATS_CURRENT) {
9614 val -= mLoadedStartTime;
9615 } else if (which == STATS_SINCE_UNPLUGGED) {
9616 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009618 return val;
9619 }
9620
9621 @Override
9622 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009623 int val = mStarts;
9624 if (which == STATS_CURRENT) {
9625 val -= mLoadedStarts;
9626 } else if (which == STATS_SINCE_UNPLUGGED) {
9627 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009628 }
9629
9630 return val;
9631 }
9632 }
9633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009634 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009635 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009636 }
9637 }
9638
9639 /**
9640 * Retrieve the statistics object for a particular process, creating
9641 * if needed.
9642 */
9643 public Proc getProcessStatsLocked(String name) {
9644 Proc ps = mProcessStats.get(name);
9645 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009646 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009647 mProcessStats.put(name, ps);
9648 }
9649
9650 return ps;
9651 }
9652
Dianne Hackborna8d10942015-11-19 17:55:19 -08009653 public void updateUidProcessStateLocked(int procState) {
9654 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009655 // Make special note of Foreground Services
9656 final boolean userAwareService =
9657 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009658 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009659
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009660 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9661 return;
9662 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009663
Bookatz867c0d72017-03-07 18:23:42 -08009664 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009665 if (mProcessState != uidRunningState) {
9666 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009667
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009668 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9669 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009670
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009671 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009672 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009673 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9674 mBsi.mOnBatteryTimeBase.isRunning(),
9675 mBsi.mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009676 }
9677 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9678 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9679 mBsi.mPendingUids.put(mUid, mProcessState);
9680 }
9681 } else {
9682 mBsi.mPendingUids.clear();
9683 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009684 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009685 mProcessState = uidRunningState;
9686 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9687 if (mProcessStateTimer[uidRunningState] == null) {
9688 makeProcessState(uidRunningState, null);
9689 }
9690 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9691 }
9692
9693 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9694 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009695 }
Bookatz867c0d72017-03-07 18:23:42 -08009696
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009697 if (userAwareService != mInForegroundService) {
9698 if (userAwareService) {
9699 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9700 } else {
9701 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9702 }
9703 mInForegroundService = userAwareService;
9704 }
Bookatz867c0d72017-03-07 18:23:42 -08009705 }
9706
Bookatzc8c44962017-05-11 12:12:54 -07009707 /** Whether to consider Uid to be in the background for background timebase purposes. */
9708 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009709 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9710 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009711 return mProcessState >= PROCESS_STATE_BACKGROUND;
9712 }
9713
9714 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9715 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9716 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9717 }
9718
9719 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9720 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9721 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009722 }
9723
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009724 public SparseArray<? extends Pid> getPidStats() {
9725 return mPids;
9726 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009727
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009728 public Pid getPidStatsLocked(int pid) {
9729 Pid p = mPids.get(pid);
9730 if (p == null) {
9731 p = new Pid();
9732 mPids.put(pid, p);
9733 }
9734 return p;
9735 }
9736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009737 /**
9738 * Retrieve the statistics object for a particular service, creating
9739 * if needed.
9740 */
9741 public Pkg getPackageStatsLocked(String name) {
9742 Pkg ps = mPackageStats.get(name);
9743 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009744 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009745 mPackageStats.put(name, ps);
9746 }
9747
9748 return ps;
9749 }
9750
9751 /**
9752 * Retrieve the statistics object for a particular service, creating
9753 * if needed.
9754 */
9755 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9756 Pkg ps = getPackageStatsLocked(pkg);
9757 Pkg.Serv ss = ps.mServiceStats.get(serv);
9758 if (ss == null) {
9759 ss = ps.newServiceStatsLocked();
9760 ps.mServiceStats.put(serv, ss);
9761 }
9762
9763 return ss;
9764 }
9765
Dianne Hackbornd953c532014-08-16 18:17:38 -07009766 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009767 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009768 timer.readSummaryFromParcelLocked(in);
9769 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009770 }
9771
Dianne Hackbornd953c532014-08-16 18:17:38 -07009772 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009773 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009774 timer.readSummaryFromParcelLocked(in);
9775 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009776 }
9777
Dianne Hackbornd953c532014-08-16 18:17:38 -07009778 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009779 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009780 mWakelockStats.add(wlName, wl);
9781 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009782 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009783 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009784 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009785 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009786 }
9787 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009788 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009789 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009790 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009791 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009792 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009793 }
9794
Bookatz867c0d72017-03-07 18:23:42 -08009795 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009796 Sensor se = mSensorStats.get(sensor);
9797 if (se == null) {
9798 if (!create) {
9799 return null;
9800 }
Joe Onoratoabded112016-02-08 16:49:39 -08009801 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009802 mSensorStats.put(sensor, se);
9803 }
Bookatz867c0d72017-03-07 18:23:42 -08009804 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009805 if (t != null) {
9806 return t;
9807 }
Joe Onoratoabded112016-02-08 16:49:39 -08009808 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009809 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009810 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009811 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009812 }
Bookatz867c0d72017-03-07 18:23:42 -08009813 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9814 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009815 se.mTimer = t;
9816 return t;
9817 }
9818
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009819 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009820 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009821 if (t != null) {
9822 t.startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08009823 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name,
9824 StatsLog.SYNC_STATE_CHANGED__STATE__ON);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009825 }
9826 }
9827
9828 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009829 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009830 if (t != null) {
9831 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009832 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08009833 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name,
9834 StatsLog.SYNC_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07009835 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009836 }
9837 }
9838
9839 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009840 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009841 if (t != null) {
9842 t.startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08009843 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08009844 name, StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__STARTED);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009845 }
9846 }
9847
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009848 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07009849 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009850 if (t != null) {
9851 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009852 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08009853 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08009854 name, StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__FINISHED);
Bookatzc1a050a2017-10-10 15:49:28 -07009855 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009856 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009857 if (mBsi.mOnBatteryTimeBase.isRunning()) {
9858 SparseIntArray types = mJobCompletions.get(name);
9859 if (types == null) {
9860 types = new SparseIntArray();
9861 mJobCompletions.put(name, types);
9862 }
9863 int last = types.get(stopReason, 0);
9864 types.put(stopReason, last + 1);
9865 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009866 }
9867
Bookatz5b5ec322017-05-26 09:40:38 -07009868 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
9869 if (wl == null) {
9870 return null;
9871 }
9872 switch (type) {
9873 case WAKE_TYPE_PARTIAL: {
9874 DualTimer t = wl.mTimerPartial;
9875 if (t == null) {
9876 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
9877 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
9878 mOnBatteryScreenOffBackgroundTimeBase);
9879 wl.mTimerPartial = t;
9880 }
9881 return t;
9882 }
9883 case WAKE_TYPE_FULL: {
9884 StopwatchTimer t = wl.mTimerFull;
9885 if (t == null) {
9886 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
9887 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
9888 wl.mTimerFull = t;
9889 }
9890 return t;
9891 }
9892 case WAKE_TYPE_WINDOW: {
9893 StopwatchTimer t = wl.mTimerWindow;
9894 if (t == null) {
9895 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
9896 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
9897 wl.mTimerWindow = t;
9898 }
9899 return t;
9900 }
9901 case WAKE_TYPE_DRAW: {
9902 StopwatchTimer t = wl.mTimerDraw;
9903 if (t == null) {
9904 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
9905 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
9906 wl.mTimerDraw = t;
9907 }
9908 return t;
9909 }
9910 default:
9911 throw new IllegalArgumentException("type=" + type);
9912 }
9913 }
9914
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009915 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009916 Wakelock wl = mWakelockStats.startObject(name);
9917 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07009918 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009919 }
Bookatzc8c44962017-05-11 12:12:54 -07009920 if (type == WAKE_TYPE_PARTIAL) {
9921 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
9922 if (pid >= 0) {
9923 Pid p = getPidStatsLocked(pid);
9924 if (p.mWakeNesting++ == 0) {
9925 p.mWakeStartMs = elapsedRealtimeMs;
9926 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -07009927 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009929 }
9930
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009931 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009932 Wakelock wl = mWakelockStats.stopObject(name);
9933 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -07009934 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
9935 wlt.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009936 }
Bookatzc8c44962017-05-11 12:12:54 -07009937 if (type == WAKE_TYPE_PARTIAL) {
9938 if (mAggregatedPartialWakelockTimer != null) {
9939 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
9940 }
9941 if (pid >= 0) {
9942 Pid p = mPids.get(pid);
9943 if (p != null && p.mWakeNesting > 0) {
9944 if (p.mWakeNesting-- == 1) {
9945 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
9946 p.mWakeStartMs = 0;
9947 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08009948 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009949 }
9950 }
9951 }
9952
Dianne Hackborn287952c2010-09-22 22:34:31 -07009953 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
9954 Proc p = getProcessStatsLocked(proc);
9955 if (p != null) {
9956 p.addExcessiveCpu(overTime, usedTime);
9957 }
9958 }
9959
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009960 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009961 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -08009962 t.startRunningLocked(elapsedRealtimeMs);
Narayan Kamath32684dd2018-01-08 17:32:51 +00009963 if (sensor != Sensor.GPS) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08009964 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null, sensor,
Bookatz90867622018-01-31 15:05:57 -08009965 StatsLog.SENSOR_STATE_CHANGED__STATE__ON);
Bookatzc1a050a2017-10-10 15:49:28 -07009966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009967 }
9968
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009969 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009970 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -08009971 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009972 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009973 t.stopRunningLocked(elapsedRealtimeMs);
Narayan Kamath32684dd2018-01-08 17:32:51 +00009974 if (sensor != Sensor.GPS) {
9975 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08009976 sensor, StatsLog.SENSOR_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07009977 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009979 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009980
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009981 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009982 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009983 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009984
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009985 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009986 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009987 }
9988
9989 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009990 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009991 }
9992 }
9993
Sudheer Shanka9b735c52017-05-09 18:26:18 -07009994 public long[] getCpuFreqs() {
9995 return mCpuFreqs;
9996 }
9997
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009998 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
9999 UserInfoProvider userInfoProvider) {
10000 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010001 }
10002
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010003 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
10004 PlatformIdleStateCallback cb,
10005 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -080010006 init(clocks);
10007
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010008 if (systemDir != null) {
10009 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
10010 new File(systemDir, "batterystats.bin.tmp"));
10011 } else {
10012 mFile = null;
10013 }
10014 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010015 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -080010016 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010017 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010018 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -080010019 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010020 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010021 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010022 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010023 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010024 }
Joe Onoratoabded112016-02-08 16:49:39 -080010025 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
10026 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
10027 mOnBatteryTimeBase);
10028 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
10029 mOnBatteryTimeBase);
10030 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
10031 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
10032 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
10033 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
10034 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10035 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
10036 mOnBatteryTimeBase);
10037 }
10038 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
10039 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010040 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010041 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010042 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010043 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010044 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010045 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
10046 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010047 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010048 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
10049 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10050 NUM_BT_TX_LEVELS);
10051 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10052 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -080010053 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
10054 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
10055 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010056 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010057 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
10058 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010059 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
10060 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -080010061 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
10062 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010063 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010064 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -070010065 mOnBatteryTimeBase);
10066 }
Joe Onoratoabded112016-02-08 16:49:39 -080010067 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10068 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
10069 mOnBatteryTimeBase);
10070 }
10071 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10072 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
10073 mOnBatteryTimeBase);
10074 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010075 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010076 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10077 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10078 mOnBatteryTimeBase);
10079 }
Joe Onoratoabded112016-02-08 16:49:39 -080010080 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10081 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10082 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10083 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10084 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010085 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010086 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010087 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10088 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010089 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010090 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010091 long uptime = mClocks.uptimeMillis() * 1000;
10092 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010093 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010094 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010095 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010096 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010097 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010098 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010099 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010100 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010101 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010102 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010103 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010104 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010105 }
10106
10107 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010108 this(new SystemClocks(), p);
10109 }
10110
10111 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10112 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010113 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010114 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010115 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010116 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010117 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010118 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010119 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010120 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010121 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010122 }
10123
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010124 public void setPowerProfileLocked(PowerProfile profile) {
10125 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010126
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010127 // We need to initialize the KernelCpuSpeedReaders to read from
10128 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10129 // information.
10130 final int numClusters = mPowerProfile.getNumCpuClusters();
10131 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10132 int firstCpuOfCluster = 0;
10133 for (int i = 0; i < numClusters; i++) {
10134 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10135 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10136 numSpeedSteps);
10137 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10138 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010139
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010140 if (mEstimatedBatteryCapacity == -1) {
10141 // Initialize the estimated battery capacity to a known preset one.
10142 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010143 }
10144 }
10145
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010146 public void setCallback(BatteryCallback cb) {
10147 mCallback = cb;
10148 }
10149
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010150 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010151 if (mPhoneSignalScanningTimer != null) {
10152 mPhoneSignalScanningTimer.setTimeout(timeout);
10153 }
10154 }
10155
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010156 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10157 mExternalSync = sync;
10158 }
10159
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010160 public void updateDailyDeadlineLocked() {
10161 // Get the current time.
10162 long currentTime = mDailyStartTime = System.currentTimeMillis();
10163 Calendar calDeadline = Calendar.getInstance();
10164 calDeadline.setTimeInMillis(currentTime);
10165
10166 // Move time up to the next day, ranging from 1am to 3pm.
10167 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10168 calDeadline.set(Calendar.MILLISECOND, 0);
10169 calDeadline.set(Calendar.SECOND, 0);
10170 calDeadline.set(Calendar.MINUTE, 0);
10171 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10172 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10173 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10174 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10175 }
10176
10177 public void recordDailyStatsIfNeededLocked(boolean settled) {
10178 long currentTime = System.currentTimeMillis();
10179 if (currentTime >= mNextMaxDailyDeadline) {
10180 recordDailyStatsLocked();
10181 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10182 recordDailyStatsLocked();
10183 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10184 recordDailyStatsLocked();
10185 }
10186 }
10187
10188 public void recordDailyStatsLocked() {
10189 DailyItem item = new DailyItem();
10190 item.mStartTime = mDailyStartTime;
10191 item.mEndTime = System.currentTimeMillis();
10192 boolean hasData = false;
10193 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10194 hasData = true;
10195 item.mDischargeSteps = new LevelStepTracker(
10196 mDailyDischargeStepTracker.mNumStepDurations,
10197 mDailyDischargeStepTracker.mStepDurations);
10198 }
10199 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10200 hasData = true;
10201 item.mChargeSteps = new LevelStepTracker(
10202 mDailyChargeStepTracker.mNumStepDurations,
10203 mDailyChargeStepTracker.mStepDurations);
10204 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010205 if (mDailyPackageChanges != null) {
10206 hasData = true;
10207 item.mPackageChanges = mDailyPackageChanges;
10208 mDailyPackageChanges = null;
10209 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010210 mDailyDischargeStepTracker.init();
10211 mDailyChargeStepTracker.init();
10212 updateDailyDeadlineLocked();
10213
10214 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010215 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010216 mDailyItems.add(item);
10217 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10218 mDailyItems.remove(0);
10219 }
10220 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10221 try {
10222 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010223 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010224 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010225 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010226 BackgroundThread.getHandler().post(new Runnable() {
10227 @Override
10228 public void run() {
10229 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010230 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010231 FileOutputStream stream = null;
10232 try {
10233 stream = mDailyFile.startWrite();
10234 memStream.writeTo(stream);
10235 stream.flush();
10236 FileUtils.sync(stream);
10237 stream.close();
10238 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010239 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
10240 "batterystats-daily",
10241 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010242 } catch (IOException e) {
10243 Slog.w("BatteryStats",
10244 "Error writing battery daily items", e);
10245 mDailyFile.failWrite(stream);
10246 }
10247 }
10248 }
10249 });
10250 } catch (IOException e) {
10251 }
10252 }
10253 }
10254
10255 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10256 StringBuilder sb = new StringBuilder(64);
10257 out.startDocument(null, true);
10258 out.startTag(null, "daily-items");
10259 for (int i=0; i<mDailyItems.size(); i++) {
10260 final DailyItem dit = mDailyItems.get(i);
10261 out.startTag(null, "item");
10262 out.attribute(null, "start", Long.toString(dit.mStartTime));
10263 out.attribute(null, "end", Long.toString(dit.mEndTime));
10264 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10265 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010266 if (dit.mPackageChanges != null) {
10267 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10268 PackageChange pc = dit.mPackageChanges.get(j);
10269 if (pc.mUpdate) {
10270 out.startTag(null, "upd");
10271 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010272 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010273 out.endTag(null, "upd");
10274 } else {
10275 out.startTag(null, "rem");
10276 out.attribute(null, "pkg", pc.mPackageName);
10277 out.endTag(null, "rem");
10278 }
10279 }
10280 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010281 out.endTag(null, "item");
10282 }
10283 out.endTag(null, "daily-items");
10284 out.endDocument();
10285 }
10286
10287 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10288 StringBuilder tmpBuilder) throws IOException {
10289 if (steps != null) {
10290 out.startTag(null, tag);
10291 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10292 for (int i=0; i<steps.mNumStepDurations; i++) {
10293 out.startTag(null, "s");
10294 tmpBuilder.setLength(0);
10295 steps.encodeEntryAt(i, tmpBuilder);
10296 out.attribute(null, "v", tmpBuilder.toString());
10297 out.endTag(null, "s");
10298 }
10299 out.endTag(null, tag);
10300 }
10301 }
10302
10303 public void readDailyStatsLocked() {
10304 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10305 mDailyItems.clear();
10306 FileInputStream stream;
10307 try {
10308 stream = mDailyFile.openRead();
10309 } catch (FileNotFoundException e) {
10310 return;
10311 }
10312 try {
10313 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010314 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010315 readDailyItemsLocked(parser);
10316 } catch (XmlPullParserException e) {
10317 } finally {
10318 try {
10319 stream.close();
10320 } catch (IOException e) {
10321 }
10322 }
10323 }
10324
10325 private void readDailyItemsLocked(XmlPullParser parser) {
10326 try {
10327 int type;
10328 while ((type = parser.next()) != XmlPullParser.START_TAG
10329 && type != XmlPullParser.END_DOCUMENT) {
10330 ;
10331 }
10332
10333 if (type != XmlPullParser.START_TAG) {
10334 throw new IllegalStateException("no start tag found");
10335 }
10336
10337 int outerDepth = parser.getDepth();
10338 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10339 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10340 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10341 continue;
10342 }
10343
10344 String tagName = parser.getName();
10345 if (tagName.equals("item")) {
10346 readDailyItemTagLocked(parser);
10347 } else {
10348 Slog.w(TAG, "Unknown element under <daily-items>: "
10349 + parser.getName());
10350 XmlUtils.skipCurrentTag(parser);
10351 }
10352 }
10353
10354 } catch (IllegalStateException e) {
10355 Slog.w(TAG, "Failed parsing daily " + e);
10356 } catch (NullPointerException e) {
10357 Slog.w(TAG, "Failed parsing daily " + e);
10358 } catch (NumberFormatException e) {
10359 Slog.w(TAG, "Failed parsing daily " + e);
10360 } catch (XmlPullParserException e) {
10361 Slog.w(TAG, "Failed parsing daily " + e);
10362 } catch (IOException e) {
10363 Slog.w(TAG, "Failed parsing daily " + e);
10364 } catch (IndexOutOfBoundsException e) {
10365 Slog.w(TAG, "Failed parsing daily " + e);
10366 }
10367 }
10368
10369 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10370 XmlPullParserException, IOException {
10371 DailyItem dit = new DailyItem();
10372 String attr = parser.getAttributeValue(null, "start");
10373 if (attr != null) {
10374 dit.mStartTime = Long.parseLong(attr);
10375 }
10376 attr = parser.getAttributeValue(null, "end");
10377 if (attr != null) {
10378 dit.mEndTime = Long.parseLong(attr);
10379 }
10380 int outerDepth = parser.getDepth();
10381 int type;
10382 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10383 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10384 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10385 continue;
10386 }
10387
10388 String tagName = parser.getName();
10389 if (tagName.equals("dis")) {
10390 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10391 } else if (tagName.equals("chg")) {
10392 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010393 } else if (tagName.equals("upd")) {
10394 if (dit.mPackageChanges == null) {
10395 dit.mPackageChanges = new ArrayList<>();
10396 }
10397 PackageChange pc = new PackageChange();
10398 pc.mUpdate = true;
10399 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10400 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010401 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010402 dit.mPackageChanges.add(pc);
10403 XmlUtils.skipCurrentTag(parser);
10404 } else if (tagName.equals("rem")) {
10405 if (dit.mPackageChanges == null) {
10406 dit.mPackageChanges = new ArrayList<>();
10407 }
10408 PackageChange pc = new PackageChange();
10409 pc.mUpdate = false;
10410 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10411 dit.mPackageChanges.add(pc);
10412 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010413 } else {
10414 Slog.w(TAG, "Unknown element under <item>: "
10415 + parser.getName());
10416 XmlUtils.skipCurrentTag(parser);
10417 }
10418 }
10419 mDailyItems.add(dit);
10420 }
10421
10422 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10423 String tag)
10424 throws NumberFormatException, XmlPullParserException, IOException {
10425 final String numAttr = parser.getAttributeValue(null, "n");
10426 if (numAttr == null) {
10427 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10428 XmlUtils.skipCurrentTag(parser);
10429 return;
10430 }
10431 final int num = Integer.parseInt(numAttr);
10432 LevelStepTracker steps = new LevelStepTracker(num);
10433 if (isCharge) {
10434 dit.mChargeSteps = steps;
10435 } else {
10436 dit.mDischargeSteps = steps;
10437 }
10438 int i = 0;
10439 int outerDepth = parser.getDepth();
10440 int type;
10441 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10442 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10443 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10444 continue;
10445 }
10446
10447 String tagName = parser.getName();
10448 if ("s".equals(tagName)) {
10449 if (i < num) {
10450 String valueAttr = parser.getAttributeValue(null, "v");
10451 if (valueAttr != null) {
10452 steps.decodeEntryAt(i, valueAttr);
10453 i++;
10454 }
10455 }
10456 } else {
10457 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10458 + parser.getName());
10459 XmlUtils.skipCurrentTag(parser);
10460 }
10461 }
10462 steps.mNumStepDurations = i;
10463 }
10464
10465 @Override
10466 public DailyItem getDailyItemLocked(int daysAgo) {
10467 int index = mDailyItems.size()-1-daysAgo;
10468 return index >= 0 ? mDailyItems.get(index) : null;
10469 }
10470
10471 @Override
10472 public long getCurrentDailyStartTime() {
10473 return mDailyStartTime;
10474 }
10475
10476 @Override
10477 public long getNextMinDailyDeadline() {
10478 return mNextMinDailyDeadline;
10479 }
10480
10481 @Override
10482 public long getNextMaxDailyDeadline() {
10483 return mNextMaxDailyDeadline;
10484 }
10485
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010486 @Override
10487 public boolean startIteratingOldHistoryLocked() {
10488 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10489 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010490 if ((mHistoryIterator = mHistory) == null) {
10491 return false;
10492 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010493 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010494 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010495 mReadOverflow = false;
10496 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010497 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010498 }
10499
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010500 @Override
10501 public boolean getNextOldHistoryLocked(HistoryItem out) {
10502 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10503 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010504 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010505 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010506 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010507 HistoryItem cur = mHistoryIterator;
10508 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010509 if (!mReadOverflow && !end) {
10510 Slog.w(TAG, "Old history ends before new history!");
10511 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010512 return false;
10513 }
10514 out.setTo(cur);
10515 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010516 if (!mReadOverflow) {
10517 if (end) {
10518 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010519 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010520 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010521 pw.println("Histories differ!");
10522 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010523 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010524 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010525 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10526 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010527 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010528 }
10529 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010530 return true;
10531 }
10532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010533 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010534 public void finishIteratingOldHistoryLocked() {
10535 mIteratingHistory = false;
10536 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010537 mHistoryIterator = null;
10538 }
10539
10540 public int getHistoryTotalSize() {
10541 return MAX_HISTORY_BUFFER;
10542 }
10543
10544 public int getHistoryUsedSize() {
10545 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010546 }
10547
10548 @Override
10549 public boolean startIteratingHistoryLocked() {
10550 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10551 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010552 if (mHistoryBuffer.dataSize() <= 0) {
10553 return false;
10554 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010555 mHistoryBuffer.setDataPosition(0);
10556 mReadOverflow = false;
10557 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010558 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10559 mReadHistoryUids = new int[mHistoryTagPool.size()];
10560 mReadHistoryChars = 0;
10561 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10562 final HistoryTag tag = ent.getKey();
10563 final int idx = ent.getValue();
10564 mReadHistoryStrings[idx] = tag.string;
10565 mReadHistoryUids[idx] = tag.uid;
10566 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010567 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010568 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010569 }
10570
10571 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010572 public int getHistoryStringPoolSize() {
10573 return mReadHistoryStrings.length;
10574 }
10575
10576 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010577 public int getHistoryStringPoolBytes() {
10578 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10579 // Each string character is 2 bytes.
10580 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10581 }
10582
10583 @Override
10584 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010585 return mReadHistoryStrings[index];
10586 }
10587
10588 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010589 public int getHistoryTagPoolUid(int index) {
10590 return mReadHistoryUids[index];
10591 }
10592
10593 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010594 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010595 final int pos = mHistoryBuffer.dataPosition();
10596 if (pos == 0) {
10597 out.clear();
10598 }
10599 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010600 if (end) {
10601 return false;
10602 }
10603
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010604 final long lastRealtime = out.time;
10605 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010606 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010607 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10608 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010609 out.currentTime = lastWalltime + (out.time - lastRealtime);
10610 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010611 return true;
10612 }
10613
10614 @Override
10615 public void finishIteratingHistoryLocked() {
10616 mIteratingHistory = false;
10617 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010618 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010619 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010620
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010621 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010622 public long getHistoryBaseTime() {
10623 return mHistoryBaseTime;
10624 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010625
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010626 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010627 public int getStartCount() {
10628 return mStartCount;
10629 }
10630
10631 public boolean isOnBattery() {
10632 return mOnBattery;
10633 }
10634
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010635 public boolean isCharging() {
10636 return mCharging;
10637 }
10638
Mike Mac2f518a2017-09-19 16:06:03 -070010639 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010640 return state == Display.STATE_ON || state == Display.STATE_VR
10641 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010642 }
10643
10644 public boolean isScreenOff(int state) {
10645 return state == Display.STATE_OFF;
10646 }
10647
10648 public boolean isScreenDoze(int state) {
10649 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010650 }
10651
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010652 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010653 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010654 mOnBatteryTimeBase.init(uptime, realtime);
10655 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010656 mRealtime = 0;
10657 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010658 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010659 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010660 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010661
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010662 void initDischarge() {
10663 mLowDischargeAmountSinceCharge = 0;
10664 mHighDischargeAmountSinceCharge = 0;
10665 mDischargeAmountScreenOn = 0;
10666 mDischargeAmountScreenOnSinceCharge = 0;
10667 mDischargeAmountScreenOff = 0;
10668 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010669 mDischargeAmountScreenDoze = 0;
10670 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010671 mDischargeStepTracker.init();
10672 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010673 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010674 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010675 mDischargeLightDozeCounter.reset(false);
10676 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010677 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010678 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010679
10680 public void resetAllStatsCmdLocked() {
10681 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010682 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010683 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010684 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010685 long realtime = mSecRealtime * 1000;
10686 mDischargeStartLevel = mHistoryCur.batteryLevel;
10687 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010688 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010689 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10690 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010691 mOnBatteryTimeBase.reset(uptime, realtime);
10692 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10693 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010694 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010695 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010696 mDischargeScreenDozeUnplugLevel = 0;
10697 mDischargeScreenOffUnplugLevel = 0;
10698 } else if (isScreenDoze(mScreenState)) {
10699 mDischargeScreenOnUnplugLevel = 0;
10700 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010701 mDischargeScreenOffUnplugLevel = 0;
10702 } else {
10703 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010704 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010705 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10706 }
10707 mDischargeAmountScreenOn = 0;
10708 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010709 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010710 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010711 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010712 }
10713
10714 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010715 final long uptimeMillis = mClocks.uptimeMillis();
10716 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010717 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010718 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010719 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010720 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010721 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010722 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010723 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010724
10725 if (mPowerProfile != null) {
10726 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10727 } else {
10728 mEstimatedBatteryCapacity = -1;
10729 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010730 mMinLearnedBatteryCapacity = -1;
10731 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010732 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010733 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010734 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010735 mLongestLightIdleTime = 0;
10736 mLongestFullIdleTime = 0;
10737 mDeviceIdleModeLightTimer.reset(false);
10738 mDeviceIdleModeFullTimer.reset(false);
10739 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010740 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010741 mPhoneOnTimer.reset(false);
10742 mAudioOnTimer.reset(false);
10743 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010744 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010745 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010746 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010747 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010748 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010749 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010750 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010751 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010752 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010753 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010754 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010755 mNetworkByteActivityCounters[i].reset(false);
10756 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010757 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010758 mMobileRadioActiveTimer.reset(false);
10759 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010760 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010761 mMobileRadioActiveUnknownTime.reset(false);
10762 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010763 mWifiOnTimer.reset(false);
10764 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010765 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010766 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010767 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010768 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10769 mWifiSupplStateTimer[i].reset(false);
10770 }
10771 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10772 mWifiSignalStrengthsTimer[i].reset(false);
10773 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010774 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010775 mWifiActiveTimer.reset(false);
10776 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010777 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10778 mGpsSignalQualityTimer[i].reset(false);
10779 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010780 mBluetoothActivity.reset(false);
10781 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010782 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010783
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010784 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010785 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010786 mUidStats.remove(mUidStats.keyAt(i));
10787 i--;
10788 }
10789 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010790
Bookatz50df7112017-08-04 14:53:26 -070010791 if (mRpmStats.size() > 0) {
10792 for (SamplingTimer timer : mRpmStats.values()) {
10793 mOnBatteryTimeBase.remove(timer);
10794 }
10795 mRpmStats.clear();
10796 }
10797 if (mScreenOffRpmStats.size() > 0) {
10798 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10799 mOnBatteryScreenOffTimeBase.remove(timer);
10800 }
10801 mScreenOffRpmStats.clear();
10802 }
10803
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010804 if (mKernelWakelockStats.size() > 0) {
10805 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010806 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010807 }
10808 mKernelWakelockStats.clear();
10809 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010810
James Carr3a226052016-07-01 14:49:52 -070010811 if (mKernelMemoryStats.size() > 0) {
10812 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10813 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10814 }
10815 mKernelMemoryStats.clear();
10816 }
10817
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010818 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010819 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10820 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010821 }
10822 mWakeupReasonStats.clear();
10823 }
10824
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010825 mLastHistoryStepDetails = null;
10826 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10827 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10828 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10829 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10830 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10831 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10832 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
10833 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
10834 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
10835 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
10836
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010837 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010838
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010839 clearHistoryLocked();
10840 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010841
Dianne Hackborn40c87252014-03-19 16:55:40 -070010842 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010843 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010844 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
10845 // Not recording process starts/stops.
10846 continue;
10847 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010848 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010849 if (active == null) {
10850 continue;
10851 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010852 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
10853 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010854 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070010855 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
10856 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010857 }
10858 }
10859 }
10860 }
10861
Mike Mac2f518a2017-09-19 16:06:03 -070010862 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
10863 updateOldDischargeScreenLevelLocked(oldState);
10864 updateNewDischargeScreenLevelLocked(newState);
10865 }
10866
10867 private void updateOldDischargeScreenLevelLocked(int state) {
10868 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010869 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
10870 if (diff > 0) {
10871 mDischargeAmountScreenOn += diff;
10872 mDischargeAmountScreenOnSinceCharge += diff;
10873 }
Mike Mac2f518a2017-09-19 16:06:03 -070010874 } else if (isScreenDoze(state)) {
10875 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
10876 if (diff > 0) {
10877 mDischargeAmountScreenDoze += diff;
10878 mDischargeAmountScreenDozeSinceCharge += diff;
10879 }
10880 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010881 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
10882 if (diff > 0) {
10883 mDischargeAmountScreenOff += diff;
10884 mDischargeAmountScreenOffSinceCharge += diff;
10885 }
10886 }
Mike Mac2f518a2017-09-19 16:06:03 -070010887 }
10888
10889 private void updateNewDischargeScreenLevelLocked(int state) {
10890 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010891 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
10892 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010893 mDischargeScreenDozeUnplugLevel = 0;
10894 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010895 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010896 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
10897 mDischargeScreenOffUnplugLevel = 0;
10898 } else if (isScreenOff(state)) {
10899 mDischargeScreenOnUnplugLevel = 0;
10900 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010901 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
10902 }
10903 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010904
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010905 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010906 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070010907 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010908 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010909 }
10910
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010911 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
10912 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
10913
10914 private final Object mWifiNetworkLock = new Object();
10915
10916 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010917 private String[] mWifiIfaces = EmptyArray.STRING;
10918
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010919 @GuardedBy("mWifiNetworkLock")
10920 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010921
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010922 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010923
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010924 @GuardedBy("mModemNetworkLock")
10925 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010926
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010927 @GuardedBy("mModemNetworkLock")
10928 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
10929
10930 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
10931 try {
10932 if (!ArrayUtils.isEmpty(ifaces)) {
10933 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
10934 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
10935 }
10936 } catch (IOException e) {
10937 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010938 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010939 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010940 }
10941
Chenjie Yu89083392018-01-11 14:53:31 -080010942 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010943 * Distribute WiFi energy info and network traffic to apps.
10944 * @param info The energy information from the WiFi controller.
10945 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010946 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010947 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010948 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010949 }
10950
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010951 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070010952 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010953 synchronized (mWifiNetworkLock) {
10954 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
10955 if (latestStats != null) {
10956 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
10957 mNetworkStatsPool.acquire());
10958 mNetworkStatsPool.release(mLastWifiNetworkStats);
10959 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070010960 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010961 }
10962
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010963 synchronized (this) {
10964 if (!mOnBatteryInternal) {
10965 if (delta != null) {
10966 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010967 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010968 return;
10969 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010970
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010971 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
10972 SparseLongArray rxPackets = new SparseLongArray();
10973 SparseLongArray txPackets = new SparseLongArray();
10974 long totalTxPackets = 0;
10975 long totalRxPackets = 0;
10976 if (delta != null) {
10977 NetworkStats.Entry entry = new NetworkStats.Entry();
10978 final int size = delta.size();
10979 for (int i = 0; i < size; i++) {
10980 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010981
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010982 if (DEBUG_ENERGY) {
10983 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
10984 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
10985 + " txPackets=" + entry.txPackets);
10986 }
10987
10988 if (entry.rxBytes == 0 && entry.txBytes == 0) {
10989 // Skip the lookup below since there is no work to do.
10990 continue;
10991 }
10992
10993 final Uid u = getUidStatsLocked(mapUid(entry.uid));
10994 if (entry.rxBytes != 0) {
10995 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080010996 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010997 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10998 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
10999 entry.rxPackets);
11000 }
11001 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11002 entry.rxBytes);
11003 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11004 entry.rxPackets);
11005
11006 rxPackets.put(u.getUid(), entry.rxPackets);
11007
11008 // Sum the total number of packets so that the Rx Power can
11009 // be evenly distributed amongst the apps.
11010 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011011 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011012
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011013 if (entry.txBytes != 0) {
11014 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011015 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011016 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11017 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
11018 entry.txPackets);
11019 }
11020 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11021 entry.txBytes);
11022 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11023 entry.txPackets);
11024
11025 txPackets.put(u.getUid(), entry.txPackets);
11026
11027 // Sum the total number of packets so that the Tx Power can
11028 // be evenly distributed amongst the apps.
11029 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011030 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080011031 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011032 mNetworkStatsPool.release(delta);
11033 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070011034 }
11035
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011036 if (info != null) {
11037 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070011038
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011039 // Measured in mAms
11040 final long txTimeMs = info.getControllerTxTimeMillis();
11041 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080011042 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011043 final long idleTimeMs = info.getControllerIdleTimeMillis();
11044 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011045
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011046 long leftOverRxTimeMs = rxTimeMs;
11047 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011048
Adam Lesinskie08af192015-03-25 16:42:59 -070011049 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011050 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
11051 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11052 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11053 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
11054 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080011055 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011056 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011057
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011058 long totalWifiLockTimeMs = 0;
11059 long totalScanTimeMs = 0;
11060
11061 // On the first pass, collect some totals so that we can normalize power
11062 // calculations if we need to.
11063 final int uidStatsSize = mUidStats.size();
11064 for (int i = 0; i < uidStatsSize; i++) {
11065 final Uid uid = mUidStats.valueAt(i);
11066
11067 // Sum the total scan power for all apps.
11068 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
11069 elapsedRealtimeMs * 1000) / 1000;
11070
11071 // Sum the total time holding wifi lock for all apps.
11072 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11073 elapsedRealtimeMs * 1000) / 1000;
11074 }
11075
11076 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
11077 Slog.d(TAG,
11078 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
11079 + rxTimeMs + " ms). Normalizing scan time.");
11080 }
11081 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11082 Slog.d(TAG,
11083 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11084 + txTimeMs + " ms). Normalizing scan time.");
11085 }
11086
11087 // Actually assign and distribute power usage to apps.
11088 for (int i = 0; i < uidStatsSize; i++) {
11089 final Uid uid = mUidStats.valueAt(i);
11090
11091 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11092 elapsedRealtimeMs * 1000) / 1000;
11093 if (scanTimeSinceMarkMs > 0) {
11094 // Set the new mark so that next time we get new data since this point.
11095 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11096
11097 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11098 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11099
11100 // Our total scan time is more than the reported Tx/Rx time.
11101 // This is possible because the cost of a scan is approximate.
11102 // Let's normalize the result so that we evenly blame each app
11103 // scanning.
11104 //
11105 // This means that we may have apps that transmitted/received packets not be
11106 // blamed for this, but this is fine as scans are relatively more expensive.
11107 if (totalScanTimeMs > rxTimeMs) {
11108 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11109 totalScanTimeMs;
11110 }
11111 if (totalScanTimeMs > txTimeMs) {
11112 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11113 totalScanTimeMs;
11114 }
11115
11116 if (DEBUG_ENERGY) {
11117 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11118 + scanRxTimeSinceMarkMs + " ms Tx:"
11119 + scanTxTimeSinceMarkMs + " ms)");
11120 }
11121
11122 ControllerActivityCounterImpl activityCounter =
11123 uid.getOrCreateWifiControllerActivityLocked();
11124 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11125 activityCounter.getTxTimeCounters()[0].addCountLocked(
11126 scanTxTimeSinceMarkMs);
11127 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11128 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11129 }
11130
11131 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11132 // lock.
11133 final long wifiLockTimeSinceMarkMs =
11134 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11135 elapsedRealtimeMs * 1000) / 1000;
11136 if (wifiLockTimeSinceMarkMs > 0) {
11137 // Set the new mark so that next time we get new data since this point.
11138 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11139
11140 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11141 / totalWifiLockTimeMs;
11142 if (DEBUG_ENERGY) {
11143 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11144 + myIdleTimeMs + " ms");
11145 }
11146 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11147 .addCountLocked(myIdleTimeMs);
11148 }
11149 }
11150
Adam Lesinskie08af192015-03-25 16:42:59 -070011151 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011152 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11153 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011154 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011155
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011156 // Distribute the remaining Tx power appropriately between all apps that transmitted
11157 // packets.
11158 for (int i = 0; i < txPackets.size(); i++) {
11159 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11160 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11161 / totalTxPackets;
11162 if (DEBUG_ENERGY) {
11163 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11164 }
11165 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11166 .addCountLocked(myTxTimeMs);
11167 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011168
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011169 // Distribute the remaining Rx power appropriately between all apps that received
11170 // packets.
11171 for (int i = 0; i < rxPackets.size(); i++) {
11172 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11173 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11174 / totalRxPackets;
11175 if (DEBUG_ENERGY) {
11176 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11177 }
11178 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11179 .addCountLocked(myRxTimeMs);
11180 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011181
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011182 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11183
11184
11185 // Update WiFi controller stats.
11186 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11187 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11188 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011189 mWifiActivity.getScanTimeCounter().addCountLocked(
11190 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011191 mWifiActivity.getIdleTimeCounter().addCountLocked(
11192 info.getControllerIdleTimeMillis());
11193
11194 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11195 final double opVolt = mPowerProfile.getAveragePower(
11196 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11197 if (opVolt != 0) {
11198 // We store the power drain as mAms.
11199 mWifiActivity.getPowerCounter().addCountLocked(
11200 (long) (info.getControllerEnergyUsed() / opVolt));
11201 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011202 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011203 }
11204 }
11205
Chenjie Yu89083392018-01-11 14:53:31 -080011206 private ModemActivityInfo mLastModemActivityInfo =
11207 new ModemActivityInfo(0, 0, 0, new int[0], 0, 0);
11208
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011209 /**
11210 * Distribute Cell radio energy info and network traffic to apps.
11211 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011212 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011213 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011214 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011215 }
11216
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011217 // Add modem tx power to history.
11218 addModemTxPowerToHistory(activityInfo);
11219
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011220 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011221 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011222 synchronized (mModemNetworkLock) {
11223 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11224 if (latestStats != null) {
11225 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11226 mNetworkStatsPool.acquire());
11227 mNetworkStatsPool.release(mLastModemNetworkStats);
11228 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011229 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011230 }
11231
Chenjie Yu89083392018-01-11 14:53:31 -080011232 int rxTimeMs = 0;
11233 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
11234 int idleTimeMs = 0;
11235 int sleepTimeMs = 0;
11236 if (activityInfo != null) {
11237 rxTimeMs = activityInfo.getRxTimeMillis() - mLastModemActivityInfo.getRxTimeMillis();
11238 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
11239 txTimeMs[i] = activityInfo.getTxTimeMillis()[i]
11240 - mLastModemActivityInfo.getTxTimeMillis()[i];
11241 }
11242 idleTimeMs =
11243 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis();
11244 sleepTimeMs =
11245 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis();
11246 }
11247
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011248 synchronized (this) {
11249 if (!mOnBatteryInternal) {
11250 if (delta != null) {
11251 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011252 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011253 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011254 }
11255
Siddharth Ray2038af82018-01-17 17:40:26 -080011256 if (activityInfo != null) {
11257 mHasModemReporting = true;
11258 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yu89083392018-01-11 14:53:31 -080011259 idleTimeMs);
11260 mModemActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
Siddharth Ray2038af82018-01-17 17:40:26 -080011261 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11262 mModemActivity.getTxTimeCounters()[lvl]
Chenjie Yu89083392018-01-11 14:53:31 -080011263 .addCountLocked(txTimeMs[lvl]);
Siddharth Ray2038af82018-01-17 17:40:26 -080011264 }
11265
11266 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11267 final double opVolt = mPowerProfile.getAveragePower(
11268 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11269 if (opVolt != 0) {
11270 double energyUsed =
Chenjie Yu89083392018-01-11 14:53:31 -080011271 sleepTimeMs *
Siddharth Ray2038af82018-01-17 17:40:26 -080011272 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yu89083392018-01-11 14:53:31 -080011273 + idleTimeMs *
Siddharth Ray2038af82018-01-17 17:40:26 -080011274 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chenjie Yu89083392018-01-11 14:53:31 -080011275 + rxTimeMs *
Siddharth Ray2038af82018-01-17 17:40:26 -080011276 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chenjie Yu89083392018-01-11 14:53:31 -080011277 for (int i = 0; i < Math.min(txTimeMs.length,
Siddharth Ray2038af82018-01-17 17:40:26 -080011278 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chenjie Yu89083392018-01-11 14:53:31 -080011279 energyUsed += txTimeMs[i] * mPowerProfile.getAveragePower(
Siddharth Ray2038af82018-01-17 17:40:26 -080011280 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
11281 }
11282
11283 // We store the power drain as mAms.
11284 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11285 }
11286 }
11287
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011288 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011289 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11290 elapsedRealtimeMs * 1000);
11291 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11292
11293 long totalRxPackets = 0;
11294 long totalTxPackets = 0;
11295 if (delta != null) {
11296 NetworkStats.Entry entry = new NetworkStats.Entry();
11297 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011298 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011299 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011300 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11301 continue;
11302 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011303
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011304 if (DEBUG_ENERGY) {
11305 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11306 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11307 + " txPackets=" + entry.txPackets);
11308 }
11309
11310 totalRxPackets += entry.rxPackets;
11311 totalTxPackets += entry.txPackets;
11312
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011313 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011314 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11315 entry.rxPackets);
11316 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11317 entry.txPackets);
11318 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11319 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11320 entry.rxBytes, entry.rxPackets);
11321 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11322 entry.txBytes, entry.txPackets);
11323 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011324
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011325 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11326 entry.rxBytes);
11327 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11328 entry.txBytes);
11329 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11330 entry.rxPackets);
11331 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11332 entry.txPackets);
11333 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011334
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011335 // Now distribute proportional blame to the apps that did networking.
11336 long totalPackets = totalRxPackets + totalTxPackets;
11337 if (totalPackets > 0) {
11338 for (int i = 0; i < size; i++) {
11339 entry = delta.getValues(i, entry);
11340 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11341 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011342 }
11343
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011344 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11345
11346 // Distribute total radio active time in to this app.
11347 final long appPackets = entry.rxPackets + entry.txPackets;
11348 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11349 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11350
11351 // Remove this app from the totals, so that we don't lose any time
11352 // due to rounding.
11353 radioTime -= appRadioTime;
11354 totalPackets -= appPackets;
11355
11356 if (activityInfo != null) {
11357 ControllerActivityCounterImpl activityCounter =
11358 u.getOrCreateModemControllerActivityLocked();
11359 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chenjie Yu89083392018-01-11 14:53:31 -080011360 final long rxMs = (entry.rxPackets * rxTimeMs)
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011361 / totalRxPackets;
11362 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11363 }
11364
11365 if (totalTxPackets > 0 && entry.txPackets > 0) {
11366 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11367 long txMs =
Chenjie Yu89083392018-01-11 14:53:31 -080011368 entry.txPackets * txTimeMs[lvl];
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011369 txMs /= totalTxPackets;
11370 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11371 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011372 }
11373 }
11374 }
11375 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011376
11377 if (radioTime > 0) {
11378 // Whoops, there is some radio time we can't blame on an app!
11379 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11380 mMobileRadioActiveUnknownCount.addCountLocked(1);
11381 }
11382
11383 mNetworkStatsPool.release(delta);
11384 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011385 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011386 }
11387 }
11388
Chenjie Yu89083392018-01-11 14:53:31 -080011389 // Cache last value for comparison.
11390 private BluetoothActivityEnergyInfo mLastBluetoothActivityEnergyInfo =
11391 new BluetoothActivityEnergyInfo(0, 0, 0, 0, 0, 0);
11392
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011393 /**
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011394 * Add modem tx power to history
11395 * Device is said to be in high cellular transmit power when it has spent most of the transmit
11396 * time at the highest power level.
11397 * @param activityInfo
11398 */
11399 private void addModemTxPowerToHistory(final ModemActivityInfo activityInfo) {
11400 if (activityInfo == null) {
11401 return;
11402 }
11403 int[] txTimeMs = activityInfo.getTxTimeMillis();
11404 if (txTimeMs == null || txTimeMs.length != ModemActivityInfo.TX_POWER_LEVELS) {
11405 return;
11406 }
11407 final long elapsedRealtime = mClocks.elapsedRealtime();
11408 final long uptime = mClocks.uptimeMillis();
11409 int levelMaxTimeSpent = 0;
11410 for (int i = 1; i < txTimeMs.length; i++) {
11411 if (txTimeMs[i] > txTimeMs[levelMaxTimeSpent]) {
11412 levelMaxTimeSpent = i;
11413 }
11414 }
11415 if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
11416 if (!mIsCellularTxPowerHigh) {
11417 mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11418 addHistoryRecordLocked(elapsedRealtime, uptime);
11419 mIsCellularTxPowerHigh = true;
11420 }
11421 return;
11422 }
11423 if (mIsCellularTxPowerHigh) {
11424 mHistoryCur.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11425 addHistoryRecordLocked(elapsedRealtime, uptime);
11426 mIsCellularTxPowerHigh = false;
11427 }
11428 return;
11429 }
11430
11431 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011432 * Distribute Bluetooth energy info and network traffic to apps.
11433 * @param info The energy information from the bluetooth controller.
11434 */
11435 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011436 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011437 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011438 }
11439
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011440 if (info == null || !mOnBatteryInternal) {
11441 return;
11442 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011443
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011444 mHasBluetoothReporting = true;
11445
Bookatz867c0d72017-03-07 18:23:42 -080011446 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Chenjie Yu89083392018-01-11 14:53:31 -080011447 final long rxTimeMs = info.getControllerRxTimeMillis() -
11448 mLastBluetoothActivityEnergyInfo.getControllerRxTimeMillis();
11449 final long txTimeMs = info.getControllerTxTimeMillis() -
11450 mLastBluetoothActivityEnergyInfo.getControllerTxTimeMillis();
11451 final long idleTimeMs = info.getControllerIdleTimeMillis() -
11452 mLastBluetoothActivityEnergyInfo.getControllerIdleTimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011453 if (DEBUG_ENERGY) {
11454 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11455 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11456 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011457 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011458 }
11459
11460 long totalScanTimeMs = 0;
11461
11462 final int uidCount = mUidStats.size();
11463 for (int i = 0; i < uidCount; i++) {
11464 final Uid u = mUidStats.valueAt(i);
11465 if (u.mBluetoothScanTimer == null) {
11466 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011467 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011468
Bookatzaa4594a2017-03-24 12:39:56 -070011469 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011470 elapsedRealtimeMs * 1000) / 1000;
11471 }
11472
11473 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11474 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11475
11476 if (DEBUG_ENERGY) {
11477 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11478 + " TX=" + normalizeScanTxTime);
11479 }
11480
11481 long leftOverRxTimeMs = rxTimeMs;
11482 long leftOverTxTimeMs = txTimeMs;
11483
11484 for (int i = 0; i < uidCount; i++) {
11485 final Uid u = mUidStats.valueAt(i);
11486 if (u.mBluetoothScanTimer == null) {
11487 continue;
11488 }
11489
Bookatzaa4594a2017-03-24 12:39:56 -070011490 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011491 elapsedRealtimeMs * 1000) / 1000;
11492 if (scanTimeSinceMarkMs > 0) {
11493 // Set the new mark so that next time we get new data since this point.
11494 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11495
11496 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11497 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11498
11499 if (normalizeScanRxTime) {
11500 // Scan time is longer than the total rx time in the controller,
11501 // so distribute the scan time proportionately. This means regular traffic
11502 // will not blamed, but scans are more expensive anyways.
11503 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11504 }
11505
11506 if (normalizeScanTxTime) {
11507 // Scan time is longer than the total tx time in the controller,
11508 // so distribute the scan time proportionately. This means regular traffic
11509 // will not blamed, but scans are more expensive anyways.
11510 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11511 }
11512
11513 final ControllerActivityCounterImpl counter =
11514 u.getOrCreateBluetoothControllerActivityLocked();
11515 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11516 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11517
11518 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11519 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11520 }
11521 }
11522
11523 if (DEBUG_ENERGY) {
11524 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs
11525 + " TX=" + leftOverTxTimeMs);
11526 }
11527
11528 //
11529 // Now distribute blame to apps that did bluetooth traffic.
11530 //
11531
11532 long totalTxBytes = 0;
11533 long totalRxBytes = 0;
11534
11535 final UidTraffic[] uidTraffic = info.getUidTraffic();
Chenjie Yu89083392018-01-11 14:53:31 -080011536 final UidTraffic[] lastUidTraffic = mLastBluetoothActivityEnergyInfo.getUidTraffic();
11537 final ArrayList<UidTraffic> deltaTraffic = new ArrayList<>();
11538 int m = 0, n = 0;
11539 for (; m < uidTraffic.length && n < lastUidTraffic.length; m++) {
11540 final UidTraffic traffic = uidTraffic[m];
11541 final UidTraffic lastTraffic = lastUidTraffic[n];
11542 if (traffic.getUid() == lastTraffic.getUid()) {
11543 deltaTraffic.add(new UidTraffic(traffic.getUid(),
11544 traffic.getRxBytes() - lastTraffic.getRxBytes(),
11545 traffic.getTxBytes() - lastTraffic.getTxBytes()));
11546 n++;
11547 }
11548 }
11549 for (; m < uidTraffic.length; m ++) {
11550 deltaTraffic.add(uidTraffic[m]);
11551 }
11552
11553 for (int i = 0, j = 0; i < deltaTraffic.size(); i++) {
11554 final UidTraffic traffic = deltaTraffic.get(i);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011555
11556 // Add to the global counters.
11557 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(
11558 traffic.getRxBytes());
11559 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(
11560 traffic.getTxBytes());
11561
11562 // Add to the UID counters.
11563 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
11564 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, traffic.getRxBytes(), 0);
11565 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, traffic.getTxBytes(), 0);
11566
11567 // Calculate the total traffic.
11568 totalTxBytes += traffic.getTxBytes();
11569 totalRxBytes += traffic.getRxBytes();
11570 }
11571
11572 if ((totalTxBytes != 0 || totalRxBytes != 0) &&
11573 (leftOverRxTimeMs != 0 || leftOverTxTimeMs != 0)) {
Chenjie Yu89083392018-01-11 14:53:31 -080011574 for (int i = 0; i < deltaTraffic.size(); i++) {
11575 final UidTraffic traffic = deltaTraffic.get(i);
Adam Lesinski50e47602015-12-04 17:04:54 -080011576
Adam Lesinski50e47602015-12-04 17:04:54 -080011577 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011578 final ControllerActivityCounterImpl counter =
11579 u.getOrCreateBluetoothControllerActivityLocked();
11580
11581 if (totalRxBytes > 0 && traffic.getRxBytes() > 0) {
11582 final long timeRxMs = (leftOverRxTimeMs * traffic.getRxBytes()) / totalRxBytes;
11583
11584 if (DEBUG_ENERGY) {
11585 Slog.d(TAG, "UID=" + traffic.getUid() + " rx_bytes=" + traffic.getRxBytes()
11586 + " rx_time=" + timeRxMs);
11587 }
11588 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11589 leftOverRxTimeMs -= timeRxMs;
11590 }
11591
11592 if (totalTxBytes > 0 && traffic.getTxBytes() > 0) {
11593 final long timeTxMs = (leftOverTxTimeMs * traffic.getTxBytes()) / totalTxBytes;
11594
11595 if (DEBUG_ENERGY) {
11596 Slog.d(TAG, "UID=" + traffic.getUid() + " tx_bytes=" + traffic.getTxBytes()
11597 + " tx_time=" + timeTxMs);
11598 }
11599
11600 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11601 leftOverTxTimeMs -= timeTxMs;
11602 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011603 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011604 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011605
Chenjie Yu89083392018-01-11 14:53:31 -080011606 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11607 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11608 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011609
11610 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11611 final double opVolt = mPowerProfile.getAveragePower(
11612 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11613 if (opVolt != 0) {
11614 // We store the power drain as mAms.
11615 mBluetoothActivity.getPowerCounter().addCountLocked(
Chenjie Yu89083392018-01-11 14:53:31 -080011616 (long) ((info.getControllerEnergyUsed() -
11617 mLastBluetoothActivityEnergyInfo.getControllerEnergyUsed() )/ opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011618 }
Chenjie Yu89083392018-01-11 14:53:31 -080011619 mLastBluetoothActivityEnergyInfo = info;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011620 }
11621
11622 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011623 * Read and record Resource Power Manager (RPM) state and voter times.
11624 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11625 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011626 */
11627 public void updateRpmStatsLocked() {
11628 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011629 long now = SystemClock.elapsedRealtime();
11630 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11631 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11632 mLastRpmStatsUpdateTimeMs = now;
11633 }
Bookatz50df7112017-08-04 14:53:26 -070011634
11635 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11636 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11637
11638 // Update values for this platform state.
11639 final String pName = pstate.getKey();
11640 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11641 final int pCount = pstate.getValue().mCount;
11642 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011643 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11644 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11645 }
Bookatz50df7112017-08-04 14:53:26 -070011646
11647 // Update values for each voter of this platform state.
11648 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11649 : pstate.getValue().mVoters.entrySet()) {
11650 final String vName = pName + "." + voter.getKey();
11651 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11652 final int vCount = voter.getValue().mCount;
11653 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011654 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11655 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11656 }
Bookatz50df7112017-08-04 14:53:26 -070011657 }
11658 }
11659
11660 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11661 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11662
11663 final String subsysName = subsys.getKey();
11664 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11665 : subsys.getValue().mStates.entrySet()) {
11666 final String name = subsysName + "." + sstate.getKey();
11667 final long timeUs = sstate.getValue().mTimeMs * 1000;
11668 final int count = sstate.getValue().mCount;
11669 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011670 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11671 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11672 }
Bookatz50df7112017-08-04 14:53:26 -070011673 }
11674 }
11675 }
11676
11677 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011678 * Read and distribute kernel wake lock use across apps.
11679 */
11680 public void updateKernelWakelocksLocked() {
11681 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11682 mTmpWakelockStats);
11683 if (wakelockStats == null) {
11684 // Not crashing might make board bringup easier.
11685 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11686 return;
11687 }
11688
11689 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11690 String name = ent.getKey();
11691 KernelWakelockStats.Entry kws = ent.getValue();
11692
11693 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11694 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011695 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011696 mKernelWakelockStats.put(name, kwlt);
11697 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011698
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011699 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011700 kwlt.setUpdateVersion(kws.mVersion);
11701 }
11702
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011703 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011704 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11705 // this time.
11706 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11707 SamplingTimer st = ent.getValue();
11708 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11709 st.endSample();
11710 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011711 }
11712 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011713
Adam Lesinskid84ad302016-05-17 18:31:02 -070011714 // Record whether we've seen a non-zero time (for debugging b/22716723).
11715 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011716 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11717 }
11718
11719 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11720 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11721 wakelockStats.kernelWakelockVersion);
11722 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011723 }
11724
Adam Lesinski72478f02015-06-17 15:39:43 -070011725 // We use an anonymous class to access these variables,
11726 // so they can't live on the stack or they'd have to be
11727 // final MutableLong objects (more allocations).
11728 // Used in updateCpuTimeLocked().
11729 long mTempTotalCpuUserTimeUs;
11730 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011731 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011732
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011733 /**
James Carr3a226052016-07-01 14:49:52 -070011734 * Reads the newest memory stats from the kernel.
11735 */
11736 public void updateKernelMemoryBandwidthLocked() {
11737 mKernelMemoryBandwidthStats.updateStats();
11738 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11739 final int bandwidthEntryCount = bandwidthEntries.size();
11740 int index;
11741 for (int i = 0; i < bandwidthEntryCount; i++) {
11742 SamplingTimer timer;
11743 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11744 timer = mKernelMemoryStats.valueAt(index);
11745 } else {
11746 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11747 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11748 }
11749 timer.update(bandwidthEntries.valueAt(i), 1);
11750 if (DEBUG_MEMORY) {
11751 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11752 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11753 mKernelMemoryStats.get(
11754 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11755 mKernelMemoryStats.size()));
11756 }
11757 }
11758 }
11759
11760 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011761 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11762 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11763 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011764 */
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011765 public void updateCpuTimeLocked() {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011766 if (mPowerProfile == null) {
11767 return;
11768 }
11769
Adam Lesinski72478f02015-06-17 15:39:43 -070011770 if (DEBUG_ENERGY_CPU) {
11771 Slog.d(TAG, "!Cpu updating!");
11772 }
11773
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011774 if (mCpuFreqs == null) {
11775 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11776 }
11777
Sudheer Shanka38383232017-07-25 09:55:03 -070011778 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11779 // usually holding the wakelock on behalf of an app.
11780 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11781 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Adam Lesinski72478f02015-06-17 15:39:43 -070011782 if (mOnBatteryScreenOffTimeBase.isRunning()) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011783 partialTimersToConsider = new ArrayList<>();
11784 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011785 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011786 // Since the collection and blaming of wakelocks can be scheduled to run after
11787 // some delay, the mPartialTimers list may have new entries. We can't blame
11788 // the newly added timer for past cpu time, so we only consider timers that
11789 // were present for one round of collection. Once a timer has gone through
11790 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011791 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011792 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011793 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011794 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011795 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011796 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011797
Sudheer Shanka38383232017-07-25 09:55:03 -070011798 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11799 // need to take the snapshots.
11800 if (!mOnBatteryInternal) {
11801 mKernelUidCpuTimeReader.readDelta(null);
11802 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Mafae87da2018-01-19 20:07:20 -080011803 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11804 mKernelUidCpuActiveTimeReader.readDelta(null);
11805 mKernelUidCpuClusterTimeReader.readDelta(null);
11806 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011807 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
11808 mKernelCpuSpeedReaders[cluster].readDelta();
11809 }
11810 return;
11811 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011812
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011813 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011814 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
11815 ? null : new SparseLongArray();
Sudheer Shanka38383232017-07-25 09:55:03 -070011816 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011817 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
11818 // freqs, so no need to approximate these values.
11819 if (updatedUids != null) {
11820 updateClusterSpeedTimes(updatedUids);
Sudheer Shanka671985f2017-05-19 11:33:42 -070011821 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011822 readKernelUidCpuFreqTimesLocked(partialTimersToConsider);
Mike Mafae87da2018-01-19 20:07:20 -080011823 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11824 readKernelUidCpuActiveTimesLocked();
11825 readKernelUidCpuClusterTimesLocked();
11826 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011827 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011828
Sudheer Shanka38383232017-07-25 09:55:03 -070011829 /**
11830 * Mark the current partial timers as gone through a collection so that they will be
11831 * considered in the next cpu times distribution to wakelock holders.
11832 */
11833 @VisibleForTesting
11834 public void markPartialTimersAsEligible() {
11835 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
11836 // No difference, so each timer is now considered for the next collection.
11837 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
11838 mPartialTimers.get(i).mInList = true;
11839 }
11840 } else {
11841 // The lists are different, meaning we added (or removed a timer) since the last
11842 // collection.
11843 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
11844 mLastPartialTimers.get(i).mInList = false;
11845 }
11846 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070011847
Sudheer Shanka38383232017-07-25 09:55:03 -070011848 // Mark the current timers as gone through a collection.
11849 final int numPartialTimers = mPartialTimers.size();
11850 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011851 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011852 timer.mInList = true;
11853 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070011854 }
11855 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011856 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011857
Sudheer Shanka38383232017-07-25 09:55:03 -070011858 /**
11859 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
11860 * calculate cpu times spent by each uid at different frequencies.
11861 *
11862 * @param updatedUids The uids for which times spent at different frequencies are calculated.
11863 */
11864 @VisibleForTesting
11865 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011866 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011867 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070011868 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011869 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011870 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
11871 if (clusterSpeedTimesMs[cluster] != null) {
11872 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
11873 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011874 }
11875 }
11876 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011877 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011878 // We have cpu times per freq aggregated over all uids but we need the times per uid.
11879 // So, we distribute total time spent by an uid to different cpu freqs based on the
11880 // amount of time cpu was running at that freq.
11881 final int updatedUidsCount = updatedUids.size();
11882 for (int i = 0; i < updatedUidsCount; ++i) {
11883 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070011884 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011885 // Add the cpu speeds to this UID.
11886 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070011887 if (u.mCpuClusterSpeedTimesUs == null ||
11888 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011889 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011890 }
11891
Sudheer Shankaaf857412017-07-21 00:14:24 -070011892 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
11893 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
11894 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
11895 u.mCpuClusterSpeedTimesUs[cluster].length) {
11896 u.mCpuClusterSpeedTimesUs[cluster]
11897 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011898 }
11899
Sudheer Shankaaf857412017-07-21 00:14:24 -070011900 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011901 for (int speed = 0; speed < speedsInCluster; speed++) {
11902 if (cpuSpeeds[speed] == null) {
11903 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11904 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011905 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
11906 * clusterSpeedTimesMs[cluster][speed]
11907 / totalCpuClustersTimeMs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011908 }
11909 }
11910 }
11911 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011912 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011913
Sudheer Shanka38383232017-07-25 09:55:03 -070011914 /**
11915 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
11916 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
11917 * wakelock holders.
11918 *
11919 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
11920 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
11921 */
11922 @VisibleForTesting
11923 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
11924 @Nullable SparseLongArray updatedUids) {
11925 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
11926 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11927 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070011928
Sudheer Shanka38383232017-07-25 09:55:03 -070011929 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
11930 uid = mapUid(uid);
11931 if (Process.isIsolated(uid)) {
11932 // This could happen if the isolated uid mapping was removed before that process
11933 // was actually killed.
11934 mKernelUidCpuTimeReader.removeUid(uid);
11935 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
11936 return;
11937 }
11938 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11939 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
11940 mKernelUidCpuTimeReader.removeUid(uid);
11941 return;
11942 }
11943 final Uid u = getUidStatsLocked(uid);
11944
11945 // Accumulate the total system and user time.
11946 mTempTotalCpuUserTimeUs += userTimeUs;
11947 mTempTotalCpuSystemTimeUs += systemTimeUs;
11948
11949 StringBuilder sb = null;
11950 if (DEBUG_ENERGY_CPU) {
11951 sb = new StringBuilder();
11952 sb.append(" got time for uid=").append(u.mUid).append(": u=");
11953 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11954 sb.append(" s=");
11955 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11956 sb.append("\n");
11957 }
11958
11959 if (numWakelocks > 0) {
11960 // We have wakelocks being held, so only give a portion of the
11961 // time to the process. The rest will be distributed among wakelock
11962 // holders.
11963 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
11964 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
11965 }
11966
11967 if (sb != null) {
11968 sb.append(" adding to uid=").append(u.mUid).append(": u=");
11969 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11970 sb.append(" s=");
11971 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11972 Slog.d(TAG, sb.toString());
11973 }
11974
11975 u.mUserCpuTime.addCountLocked(userTimeUs);
11976 u.mSystemCpuTime.addCountLocked(systemTimeUs);
11977 if (updatedUids != null) {
11978 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
11979 }
11980 });
11981
11982 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11983 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11984 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
11985 }
11986
11987 if (numWakelocks > 0) {
11988 // Distribute a portion of the total cpu time to wakelock holders.
11989 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11990 mTempTotalCpuSystemTimeUs =
11991 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11992
11993 for (int i = 0; i < numWakelocks; ++i) {
11994 final StopwatchTimer timer = partialTimers.get(i);
11995 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
11996 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
11997
11998 if (DEBUG_ENERGY_CPU) {
11999 final StringBuilder sb = new StringBuilder();
12000 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
12001 .append(": u=");
12002 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12003 sb.append(" s=");
12004 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12005 Slog.d(TAG, sb.toString());
12006 }
12007
12008 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs);
12009 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs);
12010 if (updatedUids != null) {
12011 final int uid = timer.mUid.getUid();
12012 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
12013 }
12014
12015 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
12016 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000);
12017
12018 mTempTotalCpuUserTimeUs -= userTimeUs;
12019 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070012020 }
12021 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012022 }
12023
Sudheer Shanka38383232017-07-25 09:55:03 -070012024 /**
12025 * Take a snapshot of the cpu times spent by each uid in each freq and update the
12026 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012027 *
12028 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070012029 */
12030 @VisibleForTesting
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012031 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers) {
12032 final boolean perClusterTimesAvailable =
12033 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
12034 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12035 final int numClusters = mPowerProfile.getNumCpuClusters();
12036 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012037 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012038 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
12039 uid = mapUid(uid);
12040 if (Process.isIsolated(uid)) {
12041 mKernelUidCpuFreqTimeReader.removeUid(uid);
12042 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
12043 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070012044 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012045 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12046 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
12047 mKernelUidCpuFreqTimeReader.removeUid(uid);
12048 return;
12049 }
12050 final Uid u = getUidStatsLocked(uid);
12051 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12052 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
12053 }
12054 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
12055 if (u.mScreenOffCpuFreqTimeMs == null ||
12056 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12057 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
12058 mOnBatteryScreenOffTimeBase);
12059 }
12060 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012061
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012062 if (perClusterTimesAvailable) {
12063 if (u.mCpuClusterSpeedTimesUs == null ||
12064 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12065 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012066 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012067 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
12068 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012069 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012070
12071 int freqIndex = 0;
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 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
12080 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
12081 }
12082 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
12083 for (int speed = 0; speed < speedsInCluster; ++speed) {
12084 if (cpuTimesUs[speed] == null) {
12085 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12086 }
12087 final long appAllocationUs;
12088 if (mWakeLockAllocationsUs != null) {
12089 appAllocationUs =
12090 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
12091 mWakeLockAllocationsUs[cluster][speed] +=
12092 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
12093 } else {
12094 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
12095 }
12096 cpuTimesUs[speed].addCountLocked(appAllocationUs);
12097 freqIndex++;
12098 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012099 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012100 }
12101 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012102
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012103 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12104 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12105 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
12106 }
12107
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012108 if (mWakeLockAllocationsUs != null) {
12109 for (int i = 0; i < numWakelocks; ++i) {
12110 final Uid u = partialTimers.get(i).mUid;
12111 if (u.mCpuClusterSpeedTimesUs == null ||
12112 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12113 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
12114 }
12115
12116 for (int cluster = 0; cluster < numClusters; ++cluster) {
12117 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12118 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12119 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12120 u.mCpuClusterSpeedTimesUs[cluster]
12121 = new LongSamplingCounter[speedsInCluster];
12122 }
12123 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
12124 for (int speed = 0; speed < speedsInCluster; ++speed) {
12125 if (cpuTimeUs[speed] == null) {
12126 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12127 }
12128 final long allocationUs =
12129 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
12130 cpuTimeUs[speed].addCountLocked(allocationUs);
12131 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
12132 }
12133 }
12134 }
12135 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012136 }
12137
Mike Ma3d422c32017-10-25 11:08:57 -070012138 /**
12139 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
12140 * counters.
12141 */
12142 @VisibleForTesting
12143 public void readKernelUidCpuActiveTimesLocked() {
12144 final long startTimeMs = mClocks.uptimeMillis();
12145 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesUs) -> {
12146 uid = mapUid(uid);
12147 if (Process.isIsolated(uid)) {
12148 mKernelUidCpuActiveTimeReader.removeUid(uid);
12149 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
12150 return;
12151 }
12152 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12153 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
12154 mKernelUidCpuActiveTimeReader.removeUid(uid);
12155 return;
12156 }
12157 final Uid u = getUidStatsLocked(uid);
12158 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesUs);
12159 });
12160
12161 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12162 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12163 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12164 }
12165 }
12166
12167 /**
12168 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12169 * counters.
12170 */
12171 @VisibleForTesting
12172 public void readKernelUidCpuClusterTimesLocked() {
12173 final long startTimeMs = mClocks.uptimeMillis();
12174 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesUs) -> {
12175 uid = mapUid(uid);
12176 if (Process.isIsolated(uid)) {
12177 mKernelUidCpuClusterTimeReader.removeUid(uid);
12178 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12179 return;
12180 }
12181 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12182 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12183 mKernelUidCpuClusterTimeReader.removeUid(uid);
12184 return;
12185 }
12186 final Uid u = getUidStatsLocked(uid);
12187 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesUs);
12188 });
12189
12190 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12191 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12192 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12193 }
12194 }
12195
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012196 boolean setChargingLocked(boolean charging) {
12197 if (mCharging != charging) {
12198 mCharging = charging;
12199 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012200 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012201 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012202 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012203 }
12204 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12205 return true;
12206 }
12207 return false;
12208 }
12209
Mike Mac2f518a2017-09-19 16:06:03 -070012210 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12211 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012212 boolean doWrite = false;
12213 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12214 m.arg1 = onBattery ? 1 : 0;
12215 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012216
Dianne Hackborn40c87252014-03-19 16:55:40 -070012217 final long uptime = mSecUptime * 1000;
12218 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012219 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012220 if (onBattery) {
12221 // We will reset our status if we are unplugging after the
12222 // battery was last full, or the level is at 100, or
12223 // we have gone through a significant charge (from a very low
12224 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012225 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012226 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012227 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012228 || (mDischargeCurrentLevel < 20 && level >= 80)
12229 || (getHighDischargeAmountSinceCharge() >= 200
12230 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012231 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012232 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012233 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12234 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012235 // Before we write, collect a snapshot of the final aggregated
12236 // stats to be reported in the next checkin. Only do this if we have
12237 // a sufficient amount of data to make it interesting.
12238 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012239 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012240 final Parcel parcel = Parcel.obtain();
12241 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012242 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012243 BackgroundThread.getHandler().post(new Runnable() {
12244 @Override public void run() {
12245 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012246 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012247 FileOutputStream stream = null;
12248 try {
12249 stream = mCheckinFile.startWrite();
12250 stream.write(parcel.marshall());
12251 stream.flush();
12252 FileUtils.sync(stream);
12253 stream.close();
12254 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012255 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12256 "batterystats-checkin",
12257 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012258 } catch (IOException e) {
12259 Slog.w("BatteryStats",
12260 "Error writing checkin battery statistics", e);
12261 mCheckinFile.failWrite(stream);
12262 } finally {
12263 parcel.recycle();
12264 }
12265 }
12266 }
12267 });
12268 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012269 doWrite = true;
12270 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012271 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012272 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012273 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012274 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012275 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012276 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012277 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012278 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012279 if (mCharging) {
12280 setChargingLocked(false);
12281 }
12282 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012283 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012284 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012285 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012286 mDischargeStepTracker.clearTime();
12287 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012288 mInitStepMode = mCurStepMode;
12289 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012290 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012291 mHistoryCur.batteryLevel = (byte)level;
12292 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12293 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12294 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012295 if (reset) {
12296 mRecordingHistory = true;
12297 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12298 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012299 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012300 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012301 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012302 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012303 mDischargeScreenDozeUnplugLevel = 0;
12304 mDischargeScreenOffUnplugLevel = 0;
12305 } else if (isScreenDoze(screenState)) {
12306 mDischargeScreenOnUnplugLevel = 0;
12307 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012308 mDischargeScreenOffUnplugLevel = 0;
12309 } else {
12310 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012311 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012312 mDischargeScreenOffUnplugLevel = level;
12313 }
12314 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012315 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012316 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012317 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012318 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012319 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012320 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012321 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012322 mHistoryCur.batteryLevel = (byte)level;
12323 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12324 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12325 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012326 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012327 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012328 if (level < mDischargeUnplugLevel) {
12329 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12330 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12331 }
Mike Mac2f518a2017-09-19 16:06:03 -070012332 updateDischargeScreenLevelsLocked(screenState, screenState);
12333 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012334 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012335 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012336 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012337 mInitStepMode = mCurStepMode;
12338 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012339 }
12340 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12341 if (mFile != null) {
12342 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012343 }
12344 }
12345 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012346
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012347 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12348 boolean reset) {
12349 mRecordingHistory = true;
12350 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012351 addHistoryBufferLocked(elapsedRealtimeMs,
Dianne Hackborn37de0982014-05-09 09:32:18 -070012352 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012353 mHistoryCur);
12354 mHistoryCur.currentTime = 0;
12355 if (reset) {
12356 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12357 }
12358 }
12359
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012360 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12361 final long uptimeMs) {
12362 if (mRecordingHistory) {
12363 mHistoryCur.currentTime = currentTime;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012364 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_CURRENT_TIME, mHistoryCur);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012365 mHistoryCur.currentTime = 0;
12366 }
12367 }
12368
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012369 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12370 if (mRecordingHistory) {
12371 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012372 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_SHUTDOWN, mHistoryCur);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012373 mHistoryCur.currentTime = 0;
12374 }
12375 }
12376
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012377 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012378 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012379 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012380 }
12381 }
12382
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012383 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012384 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012385
Bookatz8c6571b2017-10-24 15:04:41 -070012386 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12387 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12388 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012389 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12390 temp = Math.max(0, temp);
12391
Bookatz8c6571b2017-10-24 15:04:41 -070012392 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
12393 status, plugType, level, temp);
12394
Todd Poynor1acf06a2017-12-07 19:19:35 -080012395 final boolean onBattery =
12396 plugType == BATTERY_PLUGGED_NONE &&
12397 status != BatteryManager.BATTERY_STATUS_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080012398 final long uptime = mClocks.uptimeMillis();
12399 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012400 if (!mHaveBatteryLevel) {
12401 mHaveBatteryLevel = true;
12402 // We start out assuming that the device is plugged in (not
12403 // on battery). If our first report is now that we are indeed
12404 // plugged in, then twiddle our state to correctly reflect that
12405 // since we won't be going through the full setOnBattery().
12406 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012407 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012408 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012409 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012410 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012411 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012412 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012413 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012414 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012415 mHistoryCur.batteryStatus = (byte)status;
12416 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012417 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012418 mMaxChargeStepLevel = mMinDischargeStepLevel =
12419 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012420 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012421 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12422 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12423 }
12424 int oldStatus = mHistoryCur.batteryStatus;
12425 if (onBattery) {
12426 mDischargeCurrentLevel = level;
12427 if (!mRecordingHistory) {
12428 mRecordingHistory = true;
12429 startRecordingHistory(elapsedRealtime, uptime, true);
12430 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012431 } else if (level < 96 &&
12432 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012433 if (!mRecordingHistory) {
12434 mRecordingHistory = true;
12435 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012436 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012437 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012438 mCurrentBatteryLevel = level;
12439 if (mDischargePlugLevel < 0) {
12440 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012441 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012442
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012443 if (onBattery != mOnBattery) {
12444 mHistoryCur.batteryLevel = (byte)level;
12445 mHistoryCur.batteryStatus = (byte)status;
12446 mHistoryCur.batteryHealth = (byte)health;
12447 mHistoryCur.batteryPlugType = (byte)plugType;
12448 mHistoryCur.batteryTemperature = (short)temp;
12449 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012450 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12451 // Only record discharges
12452 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12453 mDischargeCounter.addCountLocked(chargeDiff);
12454 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012455 if (isScreenDoze(mScreenState)) {
12456 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12457 }
Mike Ma15313c92017-11-15 17:58:21 -080012458 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12459 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12460 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12461 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12462 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012463 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012464 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012465 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012466 } else {
12467 boolean changed = false;
12468 if (mHistoryCur.batteryLevel != level) {
12469 mHistoryCur.batteryLevel = (byte)level;
12470 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012471
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012472 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12473 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012474 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070012475 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012476 if (mHistoryCur.batteryStatus != status) {
12477 mHistoryCur.batteryStatus = (byte)status;
12478 changed = true;
12479 }
12480 if (mHistoryCur.batteryHealth != health) {
12481 mHistoryCur.batteryHealth = (byte)health;
12482 changed = true;
12483 }
12484 if (mHistoryCur.batteryPlugType != plugType) {
12485 mHistoryCur.batteryPlugType = (byte)plugType;
12486 changed = true;
12487 }
12488 if (temp >= (mHistoryCur.batteryTemperature+10)
12489 || temp <= (mHistoryCur.batteryTemperature-10)) {
12490 mHistoryCur.batteryTemperature = (short)temp;
12491 changed = true;
12492 }
12493 if (volt > (mHistoryCur.batteryVoltage+20)
12494 || volt < (mHistoryCur.batteryVoltage-20)) {
12495 mHistoryCur.batteryVoltage = (char)volt;
12496 changed = true;
12497 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012498 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12499 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012500 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12501 // Only record discharges
12502 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12503 mDischargeCounter.addCountLocked(chargeDiff);
12504 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012505 if (isScreenDoze(mScreenState)) {
12506 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12507 }
Mike Ma15313c92017-11-15 17:58:21 -080012508 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12509 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12510 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12511 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12512 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012513 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012514 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012515 changed = true;
12516 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012517 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12518 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12519 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12520 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012521 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012522 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12523 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12524 modeBits, elapsedRealtime);
12525 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12526 modeBits, elapsedRealtime);
12527 mLastDischargeStepLevel = level;
12528 mMinDischargeStepLevel = level;
12529 mInitStepMode = mCurStepMode;
12530 mModStepMode = 0;
12531 }
12532 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012533 if (level >= 90) {
12534 // If the battery level is at least 90%, always consider the device to be
12535 // charging even if it happens to go down a level.
12536 changed |= setChargingLocked(true);
12537 mLastChargeStepLevel = level;
12538 } if (!mCharging) {
12539 if (mLastChargeStepLevel < level) {
12540 // We have not reporting that we are charging, but the level has now
12541 // gone up, so consider the state to be charging.
12542 changed |= setChargingLocked(true);
12543 mLastChargeStepLevel = level;
12544 }
12545 } else {
12546 if (mLastChargeStepLevel > level) {
12547 // We had reported that the device was charging, but here we are with
12548 // power connected and the level going down. Looks like the current
12549 // power supplied isn't enough, so consider the device to now be
12550 // discharging.
12551 changed |= setChargingLocked(false);
12552 mLastChargeStepLevel = level;
12553 }
12554 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012555 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12556 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12557 modeBits, elapsedRealtime);
12558 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12559 modeBits, elapsedRealtime);
12560 mLastChargeStepLevel = level;
12561 mMaxChargeStepLevel = level;
12562 mInitStepMode = mCurStepMode;
12563 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012564 }
12565 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012566 if (changed) {
12567 addHistoryRecordLocked(elapsedRealtime, uptime);
12568 }
Evan Millarc64edde2009-04-18 12:26:32 -070012569 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012570 if (!onBattery &&
12571 (status == BatteryManager.BATTERY_STATUS_FULL ||
12572 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12573 // We don't record history while we are plugged in and fully charged
12574 // (or when battery is not present). The next time we are
12575 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012576 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012577 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012578
Jocelyn Dangc627d102017-04-14 13:15:14 -070012579 if (mMinLearnedBatteryCapacity == -1) {
12580 mMinLearnedBatteryCapacity = chargeFullUAh;
12581 } else {
12582 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012583 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012584 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012585 }
12586
Bookatz8c6571b2017-10-24 15:04:41 -070012587 // Inform StatsLog of setBatteryState changes.
12588 // If this is the first reporting, pass in recentPast == null.
12589 private void reportChangesToStatsLog(HistoryItem recentPast,
12590 final int status, final int plugType, final int level, final int temp) {
12591
12592 if (recentPast == null || recentPast.batteryStatus != status) {
12593 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12594 }
12595 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12596 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12597 }
12598 if (recentPast == null || recentPast.batteryLevel != level) {
12599 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12600 }
12601 // Let's just always print the temperature, regardless of whether it changed.
12602 StatsLog.write(StatsLog.DEVICE_TEMPERATURE_REPORTED, temp);
12603 }
12604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012605 public long getAwakeTimeBattery() {
12606 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12607 }
12608
12609 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012610 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012611 }
12612
12613 @Override
12614 public long computeUptime(long curTime, int which) {
12615 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012616 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012617 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012618 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012619 }
12620 return 0;
12621 }
12622
12623 @Override
12624 public long computeRealtime(long curTime, int which) {
12625 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012626 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012627 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012628 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 }
12630 return 0;
12631 }
12632
12633 @Override
12634 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012635 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012636 }
12637
12638 @Override
12639 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012640 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012641 }
12642
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012643 @Override
12644 public long computeBatteryScreenOffUptime(long curTime, int which) {
12645 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12646 }
12647
12648 @Override
12649 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12650 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012651 }
12652
Dianne Hackborn260c5022014-04-29 11:23:16 -070012653 private long computeTimePerLevel(long[] steps, int numSteps) {
12654 // For now we'll do a simple average across all steps.
12655 if (numSteps <= 0) {
12656 return -1;
12657 }
12658 long total = 0;
12659 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012660 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012661 }
12662 return total / numSteps;
12663 /*
12664 long[] buckets = new long[numSteps];
12665 int numBuckets = 0;
12666 int numToAverage = 4;
12667 int i = 0;
12668 while (i < numSteps) {
12669 long totalTime = 0;
12670 int num = 0;
12671 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012672 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012673 num++;
12674 }
12675 buckets[numBuckets] = totalTime / num;
12676 numBuckets++;
12677 numToAverage *= 2;
12678 i += num;
12679 }
12680 if (numBuckets < 1) {
12681 return -1;
12682 }
12683 long averageTime = buckets[numBuckets-1];
12684 for (i=numBuckets-2; i>=0; i--) {
12685 averageTime = (averageTime + buckets[i]) / 2;
12686 }
12687 return averageTime;
12688 */
12689 }
12690
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012691 @Override
12692 public long computeBatteryTimeRemaining(long curTime) {
12693 if (!mOnBattery) {
12694 return -1;
12695 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012696 /* Simple implementation just looks at the average discharge per level across the
12697 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012698 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12699 if (discharge < 2) {
12700 return -1;
12701 }
12702 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12703 if (duration < 1000*1000) {
12704 return -1;
12705 }
12706 long usPerLevel = duration/discharge;
12707 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012708 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012709 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012710 return -1;
12711 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012712 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012713 if (msPerLevel <= 0) {
12714 return -1;
12715 }
12716 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012717 }
12718
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012719 @Override
12720 public LevelStepTracker getDischargeLevelStepTracker() {
12721 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012722 }
12723
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012724 @Override
12725 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12726 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012727 }
12728
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012729 @Override
12730 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012731 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012732 // Not yet working.
12733 return -1;
12734 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012735 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012736 int curLevel = mCurrentBatteryLevel;
12737 int plugLevel = mDischargePlugLevel;
12738 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12739 return -1;
12740 }
12741 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12742 if (duration < 1000*1000) {
12743 return -1;
12744 }
12745 long usPerLevel = duration/(curLevel-plugLevel);
12746 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012747 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012748 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012749 return -1;
12750 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012751 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012752 if (msPerLevel <= 0) {
12753 return -1;
12754 }
12755 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012756 }
12757
Siddharth Raya1fd0572017-11-13 14:20:47 -080012758 /*@hide */
12759 public CellularBatteryStats getCellularBatteryStats() {
12760 CellularBatteryStats s = new CellularBatteryStats();
12761 final int which = STATS_SINCE_CHARGED;
12762 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12763 final ControllerActivityCounter counter = getModemControllerActivity();
12764 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12765 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12766 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12767 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12768 for (int i = 0; i < timeInRatMs.length; i++) {
12769 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12770 }
12771 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12772 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12773 timeInRxSignalStrengthLevelMs[i]
12774 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12775 }
12776 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12777 counter.getTxTimeCounters().length)];
12778 long totalTxTimeMs = 0;
12779 for (int i = 0; i < txTimeMs.length; i++) {
12780 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12781 totalTxTimeMs += txTimeMs[i];
12782 }
12783 final long totalControllerActivityTimeMs
12784 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12785 final long sleepTimeMs
12786 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + totalTxTimeMs);
12787 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12788 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12789 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12790 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12791 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12792 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
12793 s.setSleepTimeMs(sleepTimeMs);
12794 s.setIdleTimeMs(idleTimeMs);
12795 s.setRxTimeMs(rxTimeMs);
12796 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12797 s.setTimeInRatMs(timeInRatMs);
12798 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
12799 s.setTxTimeMs(txTimeMs);
12800 return s;
12801 }
12802
Siddharth Rayb50a6842017-12-14 15:15:28 -080012803 /*@hide */
12804 public WifiBatteryStats getWifiBatteryStats() {
12805 WifiBatteryStats s = new WifiBatteryStats();
12806 final int which = STATS_SINCE_CHARGED;
12807 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12808 final ControllerActivityCounter counter = getWifiControllerActivity();
12809 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12810 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
12811 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12812 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
12813 final long totalControllerActivityTimeMs
12814 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12815 final long sleepTimeMs
12816 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
12817 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12818 long numAppScanRequest = 0;
12819 for (int i = 0; i < mUidStats.size(); i++) {
12820 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
12821 }
12822 long[] timeInStateMs = new long[NUM_WIFI_STATES];
12823 for (int i=0; i<NUM_WIFI_STATES; i++) {
12824 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
12825 }
12826 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
12827 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12828 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
12829 }
12830 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
12831 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12832 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
12833 }
12834 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12835 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
12836 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
12837 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
12838 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
12839 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
12840 s.setSleepTimeMs(sleepTimeMs);
12841 s.setIdleTimeMs(idleTimeMs);
12842 s.setRxTimeMs(rxTimeMs);
12843 s.setTxTimeMs(txTimeMs);
12844 s.setScanTimeMs(scanTimeMs);
12845 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12846 s.setNumAppScanRequest(numAppScanRequest);
12847 s.setTimeInStateMs(timeInStateMs);
12848 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
12849 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
12850 return s;
12851 }
12852
Siddharth Ray78ccaf52017-12-23 16:16:21 -080012853 /*@hide */
12854 public GpsBatteryStats getGpsBatteryStats() {
12855 GpsBatteryStats s = new GpsBatteryStats();
12856 final int which = STATS_SINCE_CHARGED;
12857 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12858 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12859 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
12860 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
12861 for (int i=0; i<time.length; i++) {
12862 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
12863 }
12864 s.setTimeInGpsSignalQualityLevel(time);
12865 return s;
12866 }
12867
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012868 @Override
12869 public LevelStepTracker getChargeLevelStepTracker() {
12870 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012871 }
12872
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012873 @Override
12874 public LevelStepTracker getDailyChargeLevelStepTracker() {
12875 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012876 }
12877
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012878 @Override
12879 public ArrayList<PackageChange> getDailyPackageChanges() {
12880 return mDailyPackageChanges;
12881 }
12882
Joe Onoratoe1acd632016-02-23 13:25:10 -080012883 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012884 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012885 }
12886
12887 @Override
12888 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012889 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012890 }
12891
12892 @Override
12893 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012894 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012895 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070012896
The Android Open Source Project10592532009-03-18 17:39:46 -070012897 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012898 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012899 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012900 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012901 }
12902 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012903
Evan Millar633a1742009-04-02 16:36:33 -070012904 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012905 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012906 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012907
The Android Open Source Project10592532009-03-18 17:39:46 -070012908 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012909 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012910 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012911 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012912 }
12913 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012914
Evan Millar633a1742009-04-02 16:36:33 -070012915 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012916 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012918
Amith Yamasanie43530a2009-08-21 13:11:37 -070012919 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012920 public int getLowDischargeAmountSinceCharge() {
12921 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012922 int val = mLowDischargeAmountSinceCharge;
12923 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12924 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
12925 }
12926 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012927 }
12928 }
12929
12930 @Override
12931 public int getHighDischargeAmountSinceCharge() {
12932 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012933 int val = mHighDischargeAmountSinceCharge;
12934 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12935 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
12936 }
12937 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012938 }
12939 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012940
12941 @Override
12942 public int getDischargeAmount(int which) {
12943 int dischargeAmount = which == STATS_SINCE_CHARGED
12944 ? getHighDischargeAmountSinceCharge()
12945 : (getDischargeStartLevel() - getDischargeCurrentLevel());
12946 if (dischargeAmount < 0) {
12947 dischargeAmount = 0;
12948 }
12949 return dischargeAmount;
12950 }
12951
Mike Mac2f518a2017-09-19 16:06:03 -070012952 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012953 public int getDischargeAmountScreenOn() {
12954 synchronized(this) {
12955 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070012956 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012957 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12958 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12959 }
12960 return val;
12961 }
12962 }
12963
Mike Mac2f518a2017-09-19 16:06:03 -070012964 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012965 public int getDischargeAmountScreenOnSinceCharge() {
12966 synchronized(this) {
12967 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070012968 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012969 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12970 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12971 }
12972 return val;
12973 }
12974 }
12975
Mike Mac2f518a2017-09-19 16:06:03 -070012976 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012977 public int getDischargeAmountScreenOff() {
12978 synchronized(this) {
12979 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070012980 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012981 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12982 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12983 }
Mike Mac2f518a2017-09-19 16:06:03 -070012984 // For backward compatibility, doze discharge is counted into screen off.
12985 return val + getDischargeAmountScreenDoze();
12986 }
12987 }
12988
12989 @Override
12990 public int getDischargeAmountScreenOffSinceCharge() {
12991 synchronized(this) {
12992 int val = mDischargeAmountScreenOffSinceCharge;
12993 if (mOnBattery && isScreenOff(mScreenState)
12994 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12995 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12996 }
12997 // For backward compatibility, doze discharge is counted into screen off.
12998 return val + getDischargeAmountScreenDozeSinceCharge();
12999 }
13000 }
13001
13002 @Override
13003 public int getDischargeAmountScreenDoze() {
13004 synchronized(this) {
13005 int val = mDischargeAmountScreenDoze;
13006 if (mOnBattery && isScreenDoze(mScreenState)
13007 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13008 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
13009 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013010 return val;
13011 }
13012 }
13013
Mike Mac2f518a2017-09-19 16:06:03 -070013014 @Override
13015 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013016 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070013017 int val = mDischargeAmountScreenDozeSinceCharge;
13018 if (mOnBattery && isScreenDoze(mScreenState)
13019 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13020 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013021 }
13022 return val;
13023 }
13024 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013026 /**
13027 * Retrieve the statistics object for a particular uid, creating if needed.
13028 */
13029 public Uid getUidStatsLocked(int uid) {
13030 Uid u = mUidStats.get(uid);
13031 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080013032 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013033 mUidStats.put(uid, u);
13034 }
13035 return u;
13036 }
13037
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013038 /**
13039 * Retrieve the statistics object for a particular uid. Returns null if the object is not
13040 * available.
13041 */
13042 public Uid getAvailableUidStatsLocked(int uid) {
13043 Uid u = mUidStats.get(uid);
13044 return u;
13045 }
13046
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013047 public void onCleanupUserLocked(int userId) {
13048 final int firstUidForUser = UserHandle.getUid(userId, 0);
13049 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13050 mKernelUidCpuFreqTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
13051 mKernelUidCpuTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013052 if (mKernelSingleUidTimeReader != null) {
13053 mKernelSingleUidTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
13054 }
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013055 }
13056
13057 public void onUserRemovedLocked(int userId) {
13058 final int firstUidForUser = UserHandle.getUid(userId, 0);
13059 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13060 mUidStats.put(firstUidForUser, null);
13061 mUidStats.put(lastUidForUser, null);
13062 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
13063 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
13064 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
13065 }
13066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013067 /**
13068 * Remove the statistics object for a particular uid.
13069 */
13070 public void removeUidStatsLocked(int uid) {
Adam Lesinskib83ffee2015-05-12 14:43:47 -070013071 mKernelUidCpuTimeReader.removeUid(uid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -070013072 mKernelUidCpuFreqTimeReader.removeUid(uid);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013073 if (mKernelSingleUidTimeReader != null) {
13074 mKernelSingleUidTimeReader.removeUid(uid);
13075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013076 mUidStats.remove(uid);
13077 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070013078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013079 /**
13080 * Retrieve the statistics object for a particular process, creating
13081 * if needed.
13082 */
13083 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013084 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013085 Uid u = getUidStatsLocked(uid);
13086 return u.getProcessStatsLocked(name);
13087 }
13088
13089 /**
13090 * Retrieve the statistics object for a particular process, creating
13091 * if needed.
13092 */
13093 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013094 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013095 Uid u = getUidStatsLocked(uid);
13096 return u.getPackageStatsLocked(pkg);
13097 }
13098
13099 /**
13100 * Retrieve the statistics object for a particular service, creating
13101 * if needed.
13102 */
13103 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013104 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013105 Uid u = getUidStatsLocked(uid);
13106 return u.getServiceStatsLocked(pkg, name);
13107 }
13108
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013109 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013110 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013111 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013112 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013113 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013114
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013115 public boolean trackPerProcStateCpuTimes() {
13116 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
13117 }
13118
13119 public void systemServicesReady(Context context) {
13120 mConstants.startObserving(context.getContentResolver());
13121 }
13122
13123 @VisibleForTesting
13124 public final class Constants extends ContentObserver {
13125 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
13126 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080013127 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
13128 = "track_cpu_active_cluster_time";
13129 public static final String KEY_READ_BINARY_CPU_TIME
13130 = "read_binary_cpu_time";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013131
13132 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080013133 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
13134 private static final boolean DEFAULT_READ_BINARY_CPU_TIME = false;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013135
13136 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013137 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
13138 // Not used right now.
13139 public boolean READ_BINARY_CPU_TIME = DEFAULT_READ_BINARY_CPU_TIME;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013140
13141 private ContentResolver mResolver;
13142 private final KeyValueListParser mParser = new KeyValueListParser(',');
13143
13144 public Constants(Handler handler) {
13145 super(handler);
13146 }
13147
13148 public void startObserving(ContentResolver resolver) {
13149 mResolver = resolver;
13150 mResolver.registerContentObserver(
13151 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13152 false /* notifyForDescendants */, this);
13153 updateConstants();
13154 }
13155
13156 @Override
13157 public void onChange(boolean selfChange, Uri uri) {
13158 updateConstants();
13159 }
13160
13161 private void updateConstants() {
13162 synchronized (BatteryStatsImpl.this) {
13163 try {
13164 mParser.setString(Settings.Global.getString(mResolver,
13165 Settings.Global.BATTERY_STATS_CONSTANTS));
13166 } catch (IllegalArgumentException e) {
13167 // Failed to parse the settings string, log this and move on
13168 // with defaults.
13169 Slog.e(TAG, "Bad batterystats settings", e);
13170 }
13171
13172 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13173 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13174 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013175 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13176 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
13177 READ_BINARY_CPU_TIME = mParser.getBoolean(
13178 KEY_READ_BINARY_CPU_TIME, DEFAULT_READ_BINARY_CPU_TIME);
13179
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013180 }
13181 }
13182
13183 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13184 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13185 if (isEnabled && !wasEnabled) {
13186 mKernelSingleUidTimeReader.markDataAsStale(true);
13187 mExternalSync.scheduleCpuSyncDueToSettingChange();
13188 }
13189 }
13190
13191 public void dumpLocked(PrintWriter pw) {
13192 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13193 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013194 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13195 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
13196 pw.print(KEY_READ_BINARY_CPU_TIME); pw.print("=");
13197 pw.println(READ_BINARY_CPU_TIME);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013198 }
13199 }
13200
13201 public void dumpConstantsLocked(PrintWriter pw) {
13202 mConstants.dumpLocked(pw);
13203 }
13204
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013205 Parcel mPendingWrite = null;
13206 final ReentrantLock mWriteLock = new ReentrantLock();
13207
13208 public void writeAsyncLocked() {
13209 writeLocked(false);
13210 }
13211
13212 public void writeSyncLocked() {
13213 writeLocked(true);
13214 }
13215
13216 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013217 if (mFile == null) {
13218 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013219 return;
13220 }
13221
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013222 if (mShuttingDown) {
13223 return;
13224 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013225
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013226 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013227 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013228 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013229
13230 if (mPendingWrite != null) {
13231 mPendingWrite.recycle();
13232 }
13233 mPendingWrite = out;
13234
13235 if (sync) {
13236 commitPendingDataToDisk();
13237 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013238 BackgroundThread.getHandler().post(new Runnable() {
13239 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013240 commitPendingDataToDisk();
13241 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013242 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013243 }
13244 }
13245
13246 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013247 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013248 synchronized (this) {
13249 next = mPendingWrite;
13250 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013251 if (next == null) {
13252 return;
13253 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013254 }
13255
Amith Yamasanid2450862017-02-07 15:58:24 -080013256 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013257 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013258 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013259 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013260 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013261 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013262 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013263 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013264 mFile.commit();
Dianne Hackborne17b4452018-01-10 13:15:40 -080013265 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13266 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013267 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013268 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013269 mFile.rollback();
13270 } finally {
13271 next.recycle();
13272 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013274 }
13275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013276 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013277 if (mDailyFile != null) {
13278 readDailyStatsLocked();
13279 }
13280
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013281 if (mFile == null) {
13282 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013283 return;
13284 }
13285
13286 mUidStats.clear();
13287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013288 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013289 File file = mFile.chooseForRead();
13290 if (!file.exists()) {
13291 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013292 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013293 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013294
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013295 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013296 Parcel in = Parcel.obtain();
13297 in.unmarshall(raw, 0, raw.length);
13298 in.setDataPosition(0);
13299 stream.close();
13300
13301 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013302 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013303 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013304 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013305 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013306
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013307 mEndPlatformVersion = Build.ID;
13308
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013309 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013310 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013311 final long elapsedRealtime = mClocks.elapsedRealtime();
13312 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013313 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013314 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013315 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000013316 addHistoryBufferLocked(elapsedRealtime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013317 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013318 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013319
13320 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013321 }
13322
13323 public int describeContents() {
13324 return 0;
13325 }
13326
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013327 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013328 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013329
13330 mHistoryBuffer.setDataSize(0);
13331 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013332 mHistoryTagPool.clear();
13333 mNextHistoryTagIdx = 0;
13334 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013335
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013336 int numTags = in.readInt();
13337 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013338 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013339 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013340 if (str == null) {
13341 throw new ParcelFormatException("null history tag string");
13342 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013343 int uid = in.readInt();
13344 HistoryTag tag = new HistoryTag();
13345 tag.string = str;
13346 tag.uid = uid;
13347 tag.poolIdx = idx;
13348 mHistoryTagPool.put(tag, idx);
13349 if (idx >= mNextHistoryTagIdx) {
13350 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013351 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013352 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013353 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013354
13355 int bufSize = in.readInt();
13356 int curPos = in.dataPosition();
13357 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013358 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13359 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013360 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013361 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13362 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013363 } else {
13364 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13365 + " bytes at " + curPos);
13366 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13367 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013368 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013369
Dianne Hackbornae384452011-06-28 12:33:48 -070013370 if (andOldHistory) {
13371 readOldHistory(in);
13372 }
13373
13374 if (DEBUG_HISTORY) {
13375 StringBuilder sb = new StringBuilder(128);
13376 sb.append("****************** OLD mHistoryBaseTime: ");
13377 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13378 Slog.i(TAG, sb.toString());
13379 }
13380 mHistoryBaseTime = historyBaseTime;
13381 if (DEBUG_HISTORY) {
13382 StringBuilder sb = new StringBuilder(128);
13383 sb.append("****************** NEW mHistoryBaseTime: ");
13384 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13385 Slog.i(TAG, sb.toString());
13386 }
13387
13388 // We are just arbitrarily going to insert 1 minute from the sample of
13389 // the last run until samples in this run.
13390 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013391 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013392 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013393 if (DEBUG_HISTORY) {
13394 StringBuilder sb = new StringBuilder(128);
13395 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13396 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13397 Slog.i(TAG, sb.toString());
13398 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013399 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013400 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013401
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013402 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013403 if (!USE_OLD_HISTORY) {
13404 return;
13405 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013406 mHistory = mHistoryEnd = mHistoryCache = null;
13407 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013408 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013409 HistoryItem rec = new HistoryItem(time, in);
13410 addHistoryRecordLocked(rec);
13411 }
13412 }
13413
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013414 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013415 if (DEBUG_HISTORY) {
13416 StringBuilder sb = new StringBuilder(128);
13417 sb.append("****************** WRITING mHistoryBaseTime: ");
13418 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013419 sb.append(" mLastHistoryElapsedRealtime: ");
13420 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013421 Slog.i(TAG, sb.toString());
13422 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013423 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013424 if (!inclData) {
13425 out.writeInt(0);
13426 out.writeInt(0);
13427 return;
13428 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013429 out.writeInt(mHistoryTagPool.size());
13430 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13431 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013432 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013433 out.writeString(tag.string);
13434 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013435 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013436 out.writeInt(mHistoryBuffer.dataSize());
13437 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13438 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13439 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013440
13441 if (andOldHistory) {
13442 writeOldHistory(out);
13443 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013444 }
13445
13446 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013447 if (!USE_OLD_HISTORY) {
13448 return;
13449 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013450 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013451 while (rec != null) {
13452 if (rec.time >= 0) rec.writeToParcel(out, 0);
13453 rec = rec.next;
13454 }
13455 out.writeLong(-1);
13456 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013457
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013458 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013459 final int version = in.readInt();
13460 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013461 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013462 + ", expected " + VERSION + "; erasing old stats");
13463 return;
13464 }
13465
Dianne Hackbornae384452011-06-28 12:33:48 -070013466 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013468 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013469 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013470 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013471 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013472 mStartPlatformVersion = in.readString();
13473 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013474 mOnBatteryTimeBase.readSummaryFromParcel(in);
13475 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013476 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013477 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013478 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013479 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013480 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013481 mMinLearnedBatteryCapacity = in.readInt();
13482 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013483 mLowDischargeAmountSinceCharge = in.readInt();
13484 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013485 mDischargeAmountScreenOnSinceCharge = in.readInt();
13486 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013487 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013488 mDischargeStepTracker.readFromParcel(in);
13489 mChargeStepTracker.readFromParcel(in);
13490 mDailyDischargeStepTracker.readFromParcel(in);
13491 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013492 mDischargeCounter.readSummaryFromParcelLocked(in);
13493 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013494 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013495 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13496 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013497 int NPKG = in.readInt();
13498 if (NPKG > 0) {
13499 mDailyPackageChanges = new ArrayList<>(NPKG);
13500 while (NPKG > 0) {
13501 NPKG--;
13502 PackageChange pc = new PackageChange();
13503 pc.mPackageName = in.readString();
13504 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013505 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013506 mDailyPackageChanges.add(pc);
13507 }
13508 } else {
13509 mDailyPackageChanges = null;
13510 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013511 mDailyStartTime = in.readLong();
13512 mNextMinDailyDeadline = in.readLong();
13513 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013515 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013516
Jeff Browne95c3cd2014-05-02 16:59:26 -070013517 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013518 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013519 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013520 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13521 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13522 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013523 mInteractive = false;
13524 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013525 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013526 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013527 mLongestLightIdleTime = in.readLong();
13528 mLongestFullIdleTime = in.readLong();
13529 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13530 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13531 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013532 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013533 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013534 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013535 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13536 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013537 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013538 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13539 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13540 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013541 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013542 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13543 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013544 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013545 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013546 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013547 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013548 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013549 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13550 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013551 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013552 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013553 mWifiOn = false;
13554 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013555 mGlobalWifiRunning = false;
13556 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013557 for (int i=0; i<NUM_WIFI_STATES; i++) {
13558 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13559 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013560 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13561 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13562 }
13563 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13564 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13565 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013566 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13567 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013568 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13569 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13570 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013571 mBluetoothActivity.readSummaryFromParcel(in);
13572 mModemActivity.readSummaryFromParcel(in);
13573 mHasWifiReporting = in.readInt() != 0;
13574 mHasBluetoothReporting = in.readInt() != 0;
13575 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013576
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013577 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013578 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013579 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013580 mCameraOnNesting = 0;
13581 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013582 mBluetoothScanNesting = 0;
13583 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080013584 mIsCellularTxPowerHigh = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013585
Bookatz50df7112017-08-04 14:53:26 -070013586 int NRPMS = in.readInt();
13587 if (NRPMS > 10000) {
13588 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13589 }
13590 for (int irpm = 0; irpm < NRPMS; irpm++) {
13591 if (in.readInt() != 0) {
13592 String rpmName = in.readString();
13593 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13594 }
13595 }
13596 int NSORPMS = in.readInt();
13597 if (NSORPMS > 10000) {
13598 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13599 }
13600 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13601 if (in.readInt() != 0) {
13602 String rpmName = in.readString();
13603 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13604 }
13605 }
13606
Evan Millarc64edde2009-04-18 12:26:32 -070013607 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013608 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013609 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013610 }
Evan Millarc64edde2009-04-18 12:26:32 -070013611 for (int ikw = 0; ikw < NKW; ikw++) {
13612 if (in.readInt() != 0) {
13613 String kwltName = in.readString();
13614 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13615 }
13616 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013617
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013618 int NWR = in.readInt();
13619 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013620 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013621 }
13622 for (int iwr = 0; iwr < NWR; iwr++) {
13623 if (in.readInt() != 0) {
13624 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013625 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013626 }
13627 }
13628
James Carr3a226052016-07-01 14:49:52 -070013629 int NMS = in.readInt();
13630 for (int ims = 0; ims < NMS; ims++) {
13631 if (in.readInt() != 0) {
13632 long kmstName = in.readLong();
13633 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13634 }
13635 }
13636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013637 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013638 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013639 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013641 for (int iu = 0; iu < NU; iu++) {
13642 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013643 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013644 mUidStats.put(uid, u);
13645
Bookatz867c0d72017-03-07 18:23:42 -080013646 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013647 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013648
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013649 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013650 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013651 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013652 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013653 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013654 if (in.readInt() != 0) {
13655 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13656 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013657 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013658 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013659 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013660 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013661 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13662 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13663 if (in.readInt() != 0) {
13664 u.makeWifiBatchedScanBin(i, null);
13665 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13666 }
13667 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013668 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013669 if (in.readInt() != 0) {
13670 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13671 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013672 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013673 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013674 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013675 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013676 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13677 }
13678 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013679 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13680 }
13681 if (in.readInt() != 0) {
13682 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13683 }
13684 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013685 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13686 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013687 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013688 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13689 }
13690 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013691 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13692 }
13693 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013694 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13695 }
Bookatz956f36bf2017-04-28 09:48:17 -070013696 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013697 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13698 }
13699 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013700 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13701 }
Bookatzb1f04f32017-05-19 13:57:32 -070013702 if (in.readInt() != 0) {
13703 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13704 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013705 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013706 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13707 if (in.readInt() != 0) {
13708 u.makeProcessState(i, null);
13709 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13710 }
13711 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013712 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013713 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013714 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013715
Dianne Hackborn617f8772009-03-31 15:04:46 -070013716 if (in.readInt() != 0) {
13717 if (u.mUserActivityCounters == null) {
13718 u.initUserActivityLocked();
13719 }
13720 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13721 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13722 }
13723 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013724
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013725 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013726 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013727 u.initNetworkActivityLocked();
13728 }
13729 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013730 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13731 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013732 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013733 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13734 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013735 }
13736
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013737 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13738 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13739
Adam Lesinski6832f392015-09-05 18:05:40 -070013740 if (in.readInt() != 0) {
13741 final int numClusters = in.readInt();
13742 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13743 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013744 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013745
Sudheer Shankaaf857412017-07-21 00:14:24 -070013746 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013747 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013748 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013749 final int NSB = in.readInt();
13750 if (mPowerProfile != null &&
13751 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13752 throw new ParcelFormatException("File corrupt: too many speed bins " +
13753 NSB);
13754 }
13755
Sudheer Shankaaf857412017-07-21 00:14:24 -070013756 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070013757 for (int speed = 0; speed < NSB; speed++) {
13758 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013759 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070013760 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013761 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070013762 }
13763 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070013764 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013765 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070013766 }
13767 }
13768 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013769 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013770 }
13771
Sudheer Shanka59f5c002017-05-15 10:57:15 -070013772 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13773 in, mOnBatteryTimeBase);
13774 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13775 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070013776
13777 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
13778 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
13779
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013780 int length = in.readInt();
13781 if (length == Uid.NUM_PROCESS_STATE) {
13782 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
13783 for (int procState = 0; procState < length; ++procState) {
13784 u.mProcStateTimeMs[procState]
13785 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13786 in, mOnBatteryTimeBase);
13787 }
13788 } else {
13789 u.mProcStateTimeMs = null;
13790 }
13791 length = in.readInt();
13792 if (length == Uid.NUM_PROCESS_STATE) {
13793 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
13794 for (int procState = 0; procState < length; ++procState) {
13795 u.mProcStateScreenOffTimeMs[procState]
13796 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13797 in, mOnBatteryScreenOffTimeBase);
13798 }
13799 } else {
13800 u.mProcStateScreenOffTimeMs = null;
13801 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070013802
13803 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070013804 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13805 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
13806 } else {
13807 u.mMobileRadioApWakeupCount = null;
13808 }
13809
13810 if (in.readInt() != 0) {
13811 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13812 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
13813 } else {
13814 u.mWifiRadioApWakeupCount = null;
13815 }
13816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013817 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013818 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013819 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013821 for (int iw = 0; iw < NW; iw++) {
13822 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013823 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013824 }
13825
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013826 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013827 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013828 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013829 }
13830 for (int is = 0; is < NS; is++) {
13831 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013832 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013833 }
13834
13835 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013836 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013837 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013838 }
13839 for (int ij = 0; ij < NJ; ij++) {
13840 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013841 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013842 }
13843
Dianne Hackborn94326cb2017-06-28 16:17:20 -070013844 u.readJobCompletionsFromParcelLocked(in);
13845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013846 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013847 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013848 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013850 for (int is = 0; is < NP; is++) {
13851 int seNumber = in.readInt();
13852 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080013853 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013854 }
13855 }
13856
13857 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013858 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013859 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013861 for (int ip = 0; ip < NP; ip++) {
13862 String procName = in.readString();
13863 Uid.Proc p = u.getProcessStatsLocked(procName);
13864 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013865 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013866 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013867 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013868 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
13869 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013870 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013871 }
13872
13873 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013874 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013875 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013877 for (int ip = 0; ip < NP; ip++) {
13878 String pkgName = in.readString();
13879 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013880 final int NWA = in.readInt();
13881 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013882 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013883 }
13884 p.mWakeupAlarms.clear();
13885 for (int iwa=0; iwa<NWA; iwa++) {
13886 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070013887 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013888 c.readSummaryFromParcelLocked(in);
13889 p.mWakeupAlarms.put(tag, c);
13890 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013891 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013892 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013893 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013895 for (int is = 0; is < NS; is++) {
13896 String servName = in.readString();
13897 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
13898 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013899 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013900 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013901 }
13902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013903 }
13904 }
13905
13906 /**
13907 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
13908 * disk. This format does not allow a lossless round-trip.
13909 *
13910 * @param out the Parcel to be written to.
13911 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013912 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013913 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013914
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013915 // Pull the clock time. This may update the time and make a new history entry
13916 // if we had originally pulled a time before the RTC was set.
13917 long startClockTime = getStartClockTime();
13918
Joe Onoratoabded112016-02-08 16:49:39 -080013919 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
13920 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013921
13922 out.writeInt(VERSION);
13923
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013924 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013926 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013927 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013928 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013929 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013930 out.writeString(mStartPlatformVersion);
13931 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013932 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
13933 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013934 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013935 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070013936 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013937 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013938 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070013939 out.writeInt(mMinLearnedBatteryCapacity);
13940 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080013941 out.writeInt(getLowDischargeAmountSinceCharge());
13942 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013943 out.writeInt(getDischargeAmountScreenOnSinceCharge());
13944 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070013945 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013946 mDischargeStepTracker.writeToParcel(out);
13947 mChargeStepTracker.writeToParcel(out);
13948 mDailyDischargeStepTracker.writeToParcel(out);
13949 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070013950 mDischargeCounter.writeSummaryFromParcelLocked(out);
13951 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070013952 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080013953 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
13954 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013955 if (mDailyPackageChanges != null) {
13956 final int NPKG = mDailyPackageChanges.size();
13957 out.writeInt(NPKG);
13958 for (int i=0; i<NPKG; i++) {
13959 PackageChange pc = mDailyPackageChanges.get(i);
13960 out.writeString(pc.mPackageName);
13961 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070013962 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013963 }
13964 } else {
13965 out.writeInt(0);
13966 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013967 out.writeLong(mDailyStartTime);
13968 out.writeLong(mNextMinDailyDeadline);
13969 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013970
13971 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070013972 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013973 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013974 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013975 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013976 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013977 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013978 out.writeLong(mLongestLightIdleTime);
13979 out.writeLong(mLongestFullIdleTime);
13980 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13981 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13982 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013983 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013984 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080013985 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013986 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013987 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013988 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013989 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013990 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013991 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013992 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013993 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
13994 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013995 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013996 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13997 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013998 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013999 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
14000 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014001 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014002 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14003 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014004 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014005 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014006 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014007 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14008 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14009 }
14010 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14011 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14012 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014013 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14014 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014015 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14016 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14017 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014018 mBluetoothActivity.writeSummaryToParcel(out);
14019 mModemActivity.writeSummaryToParcel(out);
14020 out.writeInt(mHasWifiReporting ? 1 : 0);
14021 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14022 out.writeInt(mHasModemReporting ? 1 : 0);
14023
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014024 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014025 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014026 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014027 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014028
Bookatz50df7112017-08-04 14:53:26 -070014029 out.writeInt(mRpmStats.size());
14030 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14031 Timer rpmt = ent.getValue();
14032 if (rpmt != null) {
14033 out.writeInt(1);
14034 out.writeString(ent.getKey());
14035 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14036 } else {
14037 out.writeInt(0);
14038 }
14039 }
14040 out.writeInt(mScreenOffRpmStats.size());
14041 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14042 Timer rpmt = ent.getValue();
14043 if (rpmt != null) {
14044 out.writeInt(1);
14045 out.writeString(ent.getKey());
14046 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14047 } else {
14048 out.writeInt(0);
14049 }
14050 }
14051
Evan Millarc64edde2009-04-18 12:26:32 -070014052 out.writeInt(mKernelWakelockStats.size());
14053 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14054 Timer kwlt = ent.getValue();
14055 if (kwlt != null) {
14056 out.writeInt(1);
14057 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014058 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14059 } else {
14060 out.writeInt(0);
14061 }
14062 }
14063
14064 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014065 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14066 SamplingTimer timer = ent.getValue();
14067 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014068 out.writeInt(1);
14069 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014070 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014071 } else {
14072 out.writeInt(0);
14073 }
14074 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014075
James Carr3a226052016-07-01 14:49:52 -070014076 out.writeInt(mKernelMemoryStats.size());
14077 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14078 Timer kmt = mKernelMemoryStats.valueAt(i);
14079 if (kmt != null) {
14080 out.writeInt(1);
14081 out.writeLong(mKernelMemoryStats.keyAt(i));
14082 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14083 } else {
14084 out.writeInt(0);
14085 }
14086 }
14087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014088 final int NU = mUidStats.size();
14089 out.writeInt(NU);
14090 for (int iu = 0; iu < NU; iu++) {
14091 out.writeInt(mUidStats.keyAt(iu));
14092 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014093
Bookatz867c0d72017-03-07 18:23:42 -080014094 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014095 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014096
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014097 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014098 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014099 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014100 } else {
14101 out.writeInt(0);
14102 }
14103 if (u.mFullWifiLockTimer != null) {
14104 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014105 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014106 } else {
14107 out.writeInt(0);
14108 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014109 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014110 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014111 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014112 } else {
14113 out.writeInt(0);
14114 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014115 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14116 if (u.mWifiBatchedScanTimer[i] != null) {
14117 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014118 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014119 } else {
14120 out.writeInt(0);
14121 }
14122 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014123 if (u.mWifiMulticastTimer != null) {
14124 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014125 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014126 } else {
14127 out.writeInt(0);
14128 }
14129 if (u.mAudioTurnedOnTimer != null) {
14130 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014131 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014132 } else {
14133 out.writeInt(0);
14134 }
14135 if (u.mVideoTurnedOnTimer != null) {
14136 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014137 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014138 } else {
14139 out.writeInt(0);
14140 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014141 if (u.mFlashlightTurnedOnTimer != null) {
14142 out.writeInt(1);
14143 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14144 } else {
14145 out.writeInt(0);
14146 }
14147 if (u.mCameraTurnedOnTimer != null) {
14148 out.writeInt(1);
14149 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14150 } else {
14151 out.writeInt(0);
14152 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014153 if (u.mForegroundActivityTimer != null) {
14154 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014155 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014156 } else {
14157 out.writeInt(0);
14158 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014159 if (u.mForegroundServiceTimer != null) {
14160 out.writeInt(1);
14161 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14162 } else {
14163 out.writeInt(0);
14164 }
Bookatzc8c44962017-05-11 12:12:54 -070014165 if (u.mAggregatedPartialWakelockTimer != null) {
14166 out.writeInt(1);
14167 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14168 } else {
14169 out.writeInt(0);
14170 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014171 if (u.mBluetoothScanTimer != null) {
14172 out.writeInt(1);
14173 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14174 } else {
14175 out.writeInt(0);
14176 }
Bookatzb1f04f32017-05-19 13:57:32 -070014177 if (u.mBluetoothUnoptimizedScanTimer != null) {
14178 out.writeInt(1);
14179 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14180 } else {
14181 out.writeInt(0);
14182 }
Bookatz956f36bf2017-04-28 09:48:17 -070014183 if (u.mBluetoothScanResultCounter != null) {
14184 out.writeInt(1);
14185 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14186 } else {
14187 out.writeInt(0);
14188 }
Bookatzb1f04f32017-05-19 13:57:32 -070014189 if (u.mBluetoothScanResultBgCounter != null) {
14190 out.writeInt(1);
14191 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14192 } else {
14193 out.writeInt(0);
14194 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014195 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14196 if (u.mProcessStateTimer[i] != null) {
14197 out.writeInt(1);
14198 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14199 } else {
14200 out.writeInt(0);
14201 }
14202 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014203 if (u.mVibratorOnTimer != null) {
14204 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014205 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014206 } else {
14207 out.writeInt(0);
14208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014209
Dianne Hackborn617f8772009-03-31 15:04:46 -070014210 if (u.mUserActivityCounters == null) {
14211 out.writeInt(0);
14212 } else {
14213 out.writeInt(1);
14214 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14215 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14216 }
14217 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014218
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014219 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014220 out.writeInt(0);
14221 } else {
14222 out.writeInt(1);
14223 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014224 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14225 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014226 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014227 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14228 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014229 }
14230
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014231 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14232 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14233
Sudheer Shankaaf857412017-07-21 00:14:24 -070014234 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014235 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014236 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14237 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014238 if (cpuSpeeds != null) {
14239 out.writeInt(1);
14240 out.writeInt(cpuSpeeds.length);
14241 for (LongSamplingCounter c : cpuSpeeds) {
14242 if (c != null) {
14243 out.writeInt(1);
14244 c.writeSummaryFromParcelLocked(out);
14245 } else {
14246 out.writeInt(0);
14247 }
14248 }
14249 } else {
14250 out.writeInt(0);
14251 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014252 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014253 } else {
14254 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014255 }
14256
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014257 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14258 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014259
Mike Ma3d422c32017-10-25 11:08:57 -070014260 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14261 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14262
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014263 if (u.mProcStateTimeMs != null) {
14264 out.writeInt(u.mProcStateTimeMs.length);
14265 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14266 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14267 }
14268 } else {
14269 out.writeInt(0);
14270 }
14271 if (u.mProcStateScreenOffTimeMs != null) {
14272 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14273 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14274 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14275 }
14276 } else {
14277 out.writeInt(0);
14278 }
14279
Adam Lesinski5f056f62016-07-14 16:56:08 -070014280 if (u.mMobileRadioApWakeupCount != null) {
14281 out.writeInt(1);
14282 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14283 } else {
14284 out.writeInt(0);
14285 }
14286
14287 if (u.mWifiRadioApWakeupCount != null) {
14288 out.writeInt(1);
14289 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14290 } else {
14291 out.writeInt(0);
14292 }
14293
Dianne Hackbornd953c532014-08-16 18:17:38 -070014294 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14295 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014296 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014297 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014298 out.writeString(wakeStats.keyAt(iw));
14299 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014300 if (wl.mTimerFull != null) {
14301 out.writeInt(1);
14302 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14303 } else {
14304 out.writeInt(0);
14305 }
14306 if (wl.mTimerPartial != null) {
14307 out.writeInt(1);
14308 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14309 } else {
14310 out.writeInt(0);
14311 }
14312 if (wl.mTimerWindow != null) {
14313 out.writeInt(1);
14314 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14315 } else {
14316 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014317 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014318 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014319 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014320 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014321 } else {
14322 out.writeInt(0);
14323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014324 }
14325
Bookatz2bffb5b2017-04-13 11:59:33 -070014326 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014327 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014328 out.writeInt(NS);
14329 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014330 out.writeString(syncStats.keyAt(is));
14331 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014332 }
14333
Bookatzaa4594a2017-03-24 12:39:56 -070014334 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014335 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014336 out.writeInt(NJ);
14337 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014338 out.writeString(jobStats.keyAt(ij));
14339 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014340 }
14341
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014342 u.writeJobCompletionsToParcelLocked(out);
14343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014344 int NSE = u.mSensorStats.size();
14345 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014346 for (int ise=0; ise<NSE; ise++) {
14347 out.writeInt(u.mSensorStats.keyAt(ise));
14348 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14349 if (se.mTimer != null) {
14350 out.writeInt(1);
14351 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14352 } else {
14353 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014354 }
14355 }
14356
14357 int NP = u.mProcessStats.size();
14358 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014359 for (int ip=0; ip<NP; ip++) {
14360 out.writeString(u.mProcessStats.keyAt(ip));
14361 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14362 out.writeLong(ps.mUserTime);
14363 out.writeLong(ps.mSystemTime);
14364 out.writeLong(ps.mForegroundTime);
14365 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014366 out.writeInt(ps.mNumCrashes);
14367 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014368 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014369 }
14370
14371 NP = u.mPackageStats.size();
14372 out.writeInt(NP);
14373 if (NP > 0) {
14374 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14375 : u.mPackageStats.entrySet()) {
14376 out.writeString(ent.getKey());
14377 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014378 final int NWA = ps.mWakeupAlarms.size();
14379 out.writeInt(NWA);
14380 for (int iwa=0; iwa<NWA; iwa++) {
14381 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14382 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14383 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014384 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014385 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014386 for (int is=0; is<NS; is++) {
14387 out.writeString(ps.mServiceStats.keyAt(is));
14388 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14389 long time = ss.getStartTimeToNowLocked(
14390 mOnBatteryTimeBase.getUptime(NOW_SYS));
14391 out.writeLong(time);
14392 out.writeInt(ss.mStarts);
14393 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014394 }
14395 }
14396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014397 }
14398 }
14399
14400 public void readFromParcel(Parcel in) {
14401 readFromParcelLocked(in);
14402 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014404 void readFromParcelLocked(Parcel in) {
14405 int magic = in.readInt();
14406 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014407 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014408 }
14409
Dianne Hackbornae384452011-06-28 12:33:48 -070014410 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014412 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014413 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014414 mStartPlatformVersion = in.readString();
14415 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014416 mUptime = in.readLong();
14417 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014418 mRealtime = in.readLong();
14419 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014420 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014421 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014422 mMinLearnedBatteryCapacity = in.readInt();
14423 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014424 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014425 mOnBatteryTimeBase.readFromParcel(in);
14426 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14427
Jeff Browne95c3cd2014-05-02 16:59:26 -070014428 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014429 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014430 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014431 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014432 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14433 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014434 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014435 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014436 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014437 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014438 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14439 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014440 mLongestLightIdleTime = in.readLong();
14441 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014442 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14443 mOnBatteryTimeBase, in);
14444 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14445 mOnBatteryTimeBase, in);
14446 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14447 mOnBatteryTimeBase, in);
14448 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14449 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014450 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014451 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014452 null, mOnBatteryTimeBase, in);
14453 }
Joe Onoratoabded112016-02-08 16:49:39 -080014454 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14455 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014456 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014457 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014458 null, mOnBatteryTimeBase, in);
14459 }
14460 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14461 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14462 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14463 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014464 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014465 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14466 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014467 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014468 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014469 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014470 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14471 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014472 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14473 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014474 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014475 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014476 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014477 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014478 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14479 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014480 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014481 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014482 null, mOnBatteryTimeBase, in);
14483 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014484 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014485 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014486 null, mOnBatteryTimeBase, in);
14487 }
14488 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014489 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014490 null, mOnBatteryTimeBase, in);
14491 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014492 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14493 mOnBatteryTimeBase, in);
14494 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14495 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014496 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14497 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14498 null, mOnBatteryTimeBase, in);
14499 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014500 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14501 NUM_BT_TX_LEVELS, in);
14502 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14503 ModemActivityInfo.TX_POWER_LEVELS, in);
14504 mHasWifiReporting = in.readInt() != 0;
14505 mHasBluetoothReporting = in.readInt() != 0;
14506 mHasModemReporting = in.readInt() != 0;
14507
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014508 mNumConnectivityChange = in.readInt();
14509 mLoadedNumConnectivityChange = in.readInt();
14510 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014511 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014512 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014513 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014514 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014515 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014516 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014517 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014518 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014519 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014520 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080014521 mIsCellularTxPowerHigh = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014522 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014523 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014524 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014525 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014526 mLowDischargeAmountSinceCharge = in.readInt();
14527 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014528 mDischargeAmountScreenOn = in.readInt();
14529 mDischargeAmountScreenOnSinceCharge = in.readInt();
14530 mDischargeAmountScreenOff = in.readInt();
14531 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014532 mDischargeAmountScreenDoze = in.readInt();
14533 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014534 mDischargeStepTracker.readFromParcel(in);
14535 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014536 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014537 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14538 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014539 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14540 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014541 mLastWriteTime = in.readLong();
14542
Bookatz50df7112017-08-04 14:53:26 -070014543 mRpmStats.clear();
14544 int NRPMS = in.readInt();
14545 for (int irpm = 0; irpm < NRPMS; irpm++) {
14546 if (in.readInt() != 0) {
14547 String rpmName = in.readString();
14548 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14549 mRpmStats.put(rpmName, rpmt);
14550 }
14551 }
14552 mScreenOffRpmStats.clear();
14553 int NSORPMS = in.readInt();
14554 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14555 if (in.readInt() != 0) {
14556 String rpmName = in.readString();
14557 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14558 mScreenOffRpmStats.put(rpmName, rpmt);
14559 }
14560 }
14561
Evan Millarc64edde2009-04-18 12:26:32 -070014562 mKernelWakelockStats.clear();
14563 int NKW = in.readInt();
14564 for (int ikw = 0; ikw < NKW; ikw++) {
14565 if (in.readInt() != 0) {
14566 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014567 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014568 mKernelWakelockStats.put(wakelockName, kwlt);
14569 }
14570 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014571
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014572 mWakeupReasonStats.clear();
14573 int NWR = in.readInt();
14574 for (int iwr = 0; iwr < NWR; iwr++) {
14575 if (in.readInt() != 0) {
14576 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014577 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014578 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014579 }
14580 }
14581
James Carr3a226052016-07-01 14:49:52 -070014582 mKernelMemoryStats.clear();
14583 int nmt = in.readInt();
14584 for (int imt = 0; imt < nmt; imt++) {
14585 if (in.readInt() != 0) {
14586 Long bucket = in.readLong();
14587 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14588 mKernelMemoryStats.put(bucket, kmt);
14589 }
14590 }
14591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014592 mPartialTimers.clear();
14593 mFullTimers.clear();
14594 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014595 mWifiRunningTimers.clear();
14596 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014597 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014598 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014599 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014600 mAudioTurnedOnTimers.clear();
14601 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014602 mFlashlightTurnedOnTimers.clear();
14603 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014604
14605 int numUids = in.readInt();
14606 mUidStats.clear();
14607 for (int i = 0; i < numUids; i++) {
14608 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014609 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014610 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014611 mUidStats.append(uid, u);
14612 }
14613 }
14614
14615 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014616 writeToParcelLocked(out, true, flags);
14617 }
14618
14619 public void writeToParcelWithoutUids(Parcel out, int flags) {
14620 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014621 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014622
14623 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014624 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014625 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014626 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014627
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014628 // Pull the clock time. This may update the time and make a new history entry
14629 // if we had originally pulled a time before the RTC was set.
14630 long startClockTime = getStartClockTime();
14631
Joe Onoratoabded112016-02-08 16:49:39 -080014632 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14633 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014634 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14635 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014637 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014638
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014639 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014641 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014642 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014643 out.writeString(mStartPlatformVersion);
14644 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014645 out.writeLong(mUptime);
14646 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014647 out.writeLong(mRealtime);
14648 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014649 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014650 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014651 out.writeInt(mMinLearnedBatteryCapacity);
14652 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014653 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14654 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14655
14656 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014657 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014658 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14659 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14660 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014661 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014662 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014663 out.writeLong(mLongestLightIdleTime);
14664 out.writeLong(mLongestFullIdleTime);
14665 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14666 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14667 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014668 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014669 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14670 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14671 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14672 }
14673 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14674 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14675 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14676 }
14677 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14678 mNetworkByteActivityCounters[i].writeToParcel(out);
14679 mNetworkPacketActivityCounters[i].writeToParcel(out);
14680 }
14681 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14682 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014683 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014684 mMobileRadioActiveUnknownTime.writeToParcel(out);
14685 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014686 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014687 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14688 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14689 for (int i=0; i<NUM_WIFI_STATES; i++) {
14690 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14691 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014692 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14693 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14694 }
14695 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14696 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14697 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014698 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
14699 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014700 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14701 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
14702 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014703 mBluetoothActivity.writeToParcel(out, 0);
14704 mModemActivity.writeToParcel(out, 0);
14705 out.writeInt(mHasWifiReporting ? 1 : 0);
14706 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14707 out.writeInt(mHasModemReporting ? 1 : 0);
14708
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014709 out.writeInt(mNumConnectivityChange);
14710 out.writeInt(mLoadedNumConnectivityChange);
14711 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014712 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014713 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014714 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014715 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014716 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014717 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014718 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014719 out.writeInt(mLowDischargeAmountSinceCharge);
14720 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014721 out.writeInt(mDischargeAmountScreenOn);
14722 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14723 out.writeInt(mDischargeAmountScreenOff);
14724 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014725 out.writeInt(mDischargeAmountScreenDoze);
14726 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014727 mDischargeStepTracker.writeToParcel(out);
14728 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014729 mDischargeCounter.writeToParcel(out);
14730 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014731 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080014732 mDischargeLightDozeCounter.writeToParcel(out);
14733 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014734 out.writeLong(mLastWriteTime);
14735
Bookatz50df7112017-08-04 14:53:26 -070014736 out.writeInt(mRpmStats.size());
14737 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14738 SamplingTimer rpmt = ent.getValue();
14739 if (rpmt != null) {
14740 out.writeInt(1);
14741 out.writeString(ent.getKey());
14742 rpmt.writeToParcel(out, uSecRealtime);
14743 } else {
14744 out.writeInt(0);
14745 }
14746 }
14747 out.writeInt(mScreenOffRpmStats.size());
14748 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14749 SamplingTimer rpmt = ent.getValue();
14750 if (rpmt != null) {
14751 out.writeInt(1);
14752 out.writeString(ent.getKey());
14753 rpmt.writeToParcel(out, uSecRealtime);
14754 } else {
14755 out.writeInt(0);
14756 }
14757 }
14758
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014759 if (inclUids) {
14760 out.writeInt(mKernelWakelockStats.size());
14761 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14762 SamplingTimer kwlt = ent.getValue();
14763 if (kwlt != null) {
14764 out.writeInt(1);
14765 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014766 kwlt.writeToParcel(out, uSecRealtime);
14767 } else {
14768 out.writeInt(0);
14769 }
14770 }
14771 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014772 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14773 SamplingTimer timer = ent.getValue();
14774 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014775 out.writeInt(1);
14776 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014777 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014778 } else {
14779 out.writeInt(0);
14780 }
Evan Millarc64edde2009-04-18 12:26:32 -070014781 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014782 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070014783 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014784 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070014785 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070014786
James Carr3a226052016-07-01 14:49:52 -070014787 out.writeInt(mKernelMemoryStats.size());
14788 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14789 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
14790 if (kmt != null) {
14791 out.writeInt(1);
14792 out.writeLong(mKernelMemoryStats.keyAt(i));
14793 kmt.writeToParcel(out, uSecRealtime);
14794 } else {
14795 out.writeInt(0);
14796 }
14797 }
14798
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014799 if (inclUids) {
14800 int size = mUidStats.size();
14801 out.writeInt(size);
14802 for (int i = 0; i < size; i++) {
14803 out.writeInt(mUidStats.keyAt(i));
14804 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014805
Bookatz867c0d72017-03-07 18:23:42 -080014806 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014807 }
14808 } else {
14809 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014810 }
14811 }
14812
14813 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
14814 new Parcelable.Creator<BatteryStatsImpl>() {
14815 public BatteryStatsImpl createFromParcel(Parcel in) {
14816 return new BatteryStatsImpl(in);
14817 }
14818
14819 public BatteryStatsImpl[] newArray(int size) {
14820 return new BatteryStatsImpl[size];
14821 }
14822 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014823
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014824 public void prepareForDumpLocked() {
14825 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014826 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014827
14828 // Pull the clock time. This may update the time and make a new history entry
14829 // if we had originally pulled a time before the RTC was set.
14830 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014831 }
14832
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014833 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014834 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014835 pw.println("mOnBatteryTimeBase:");
14836 mOnBatteryTimeBase.dump(pw, " ");
14837 pw.println("mOnBatteryScreenOffTimeBase:");
14838 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014839 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070014840 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014841 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070014842 pr.println("*** Screen doze timer:");
14843 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014844 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014845 pr.println("*** Screen brightness #" + i + ":");
14846 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014847 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014848 pr.println("*** Interactive timer:");
14849 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014850 pr.println("*** Power save mode timer:");
14851 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014852 pr.println("*** Device idle mode light timer:");
14853 mDeviceIdleModeLightTimer.logState(pr, " ");
14854 pr.println("*** Device idle mode full timer:");
14855 mDeviceIdleModeFullTimer.logState(pr, " ");
14856 pr.println("*** Device light idling timer:");
14857 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014858 pr.println("*** Device idling timer:");
14859 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014860 pr.println("*** Phone timer:");
14861 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080014862 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070014863 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014864 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014865 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070014866 pr.println("*** Signal scanning :");
14867 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014868 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014869 pr.println("*** Data connection type #" + i + ":");
14870 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014871 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014872 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080014873 pr.println("*** Mobile network active timer:");
14874 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014875 pr.println("*** Mobile network active adjusted timer:");
14876 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014877 pr.println("*** Wifi Multicast WakeLock Timer:");
14878 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014879 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014880 pr.println("*** Wifi timer:");
14881 mWifiOnTimer.logState(pr, " ");
14882 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014883 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014884 for (int i=0; i<NUM_WIFI_STATES; i++) {
14885 pr.println("*** Wifi state #" + i + ":");
14886 mWifiStateTimer[i].logState(pr, " ");
14887 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014888 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14889 pr.println("*** Wifi suppl state #" + i + ":");
14890 mWifiSupplStateTimer[i].logState(pr, " ");
14891 }
14892 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14893 pr.println("*** Wifi signal strength #" + i + ":");
14894 mWifiSignalStrengthsTimer[i].logState(pr, " ");
14895 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014896 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14897 pr.println("*** GPS signal quality #" + i + ":");
14898 mGpsSignalQualityTimer[i].logState(pr, " ");
14899 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014900 pr.println("*** Flashlight timer:");
14901 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014902 pr.println("*** Camera timer:");
14903 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014904 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014905 super.dumpLocked(context, pw, flags, reqUid, histStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014907}