blob: d011e99534e7fce634ed7aac22c0e021aead112e [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.os;
18
Sudheer Shanka9b735c52017-05-09 18:26:18 -070019import android.annotation.NonNull;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070020import android.annotation.Nullable;
Dianne Hackborn61659e52014-07-09 16:13:01 -070021import android.app.ActivityManager;
Adam Lesinski33dac552015-03-09 15:24:48 -070022import android.bluetooth.BluetoothActivityEnergyInfo;
Adam Lesinski50e47602015-12-04 17:04:54 -080023import android.bluetooth.UidTraffic;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080024import android.content.ContentResolver;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080025import android.content.Context;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070026import android.content.Intent;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080027import android.database.ContentObserver;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070028import android.net.ConnectivityManager;
29import android.net.NetworkStats;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080030import android.net.Uri;
Adam Lesinski33dac552015-03-09 15:24:48 -070031import android.net.wifi.WifiActivityEnergyInfo;
Dianne Hackborn3251b902014-06-20 14:40:53 -070032import android.net.wifi.WifiManager;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070033import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.os.BatteryStats;
Dianne Hackborncd0e3352014-08-07 17:08:09 -070035import android.os.Build;
Siddharth Raya1fd0572017-11-13 14:20:47 -080036import android.os.connectivity.CellularBatteryStats;
Siddharth Rayb50a6842017-12-14 15:15:28 -080037import android.os.connectivity.WifiBatteryStats;
Siddharth Ray78ccaf52017-12-23 16:16:21 -080038import android.os.connectivity.GpsBatteryStats;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070039import android.os.FileUtils;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070040import android.os.Handler;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080041import android.os.IBatteryPropertiesRegistrar;
Jeff Brown6f357d32014-01-15 20:40:55 -080042import android.os.Looper;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070043import android.os.Message;
Bookatz1a1b0462018-01-12 11:47:03 -080044import android.os.OsProtoEnums;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Parcel;
46import android.os.ParcelFormatException;
47import android.os.Parcelable;
Bookatz1a1b0462018-01-12 11:47:03 -080048import android.os.PowerManager;
Evan Millarc64edde2009-04-18 12:26:32 -070049import android.os.Process;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080050import android.os.RemoteException;
51import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.SystemClock;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070053import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070054import android.os.WorkSource;
Narayan Kamath81822022017-12-08 11:56:01 +000055import android.os.WorkSource.WorkChain;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080056import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070057import android.telephony.DataConnectionRealTimeInfo;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080058import android.telephony.ModemActivityInfo;
Amith Yamasanif37447b2009-10-08 18:28:01 -070059import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070060import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070061import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070062import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070063import android.util.ArrayMap;
Sudheer Shankab2f83c12017-11-13 19:25:01 -080064import android.util.IntArray;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080065import android.util.KeyValueListParser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070067import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070068import android.util.LongSparseArray;
69import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070070import android.util.MutableInt;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070071import android.util.Pools;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070072import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070074import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080076import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070077import android.util.SparseLongArray;
Bookatzc1a050a2017-10-10 15:49:28 -070078import android.util.StatsLog;
Dianne Hackbornae384452011-06-28 12:33:48 -070079import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080080import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070081import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
Adam Lesinski14ae39a2017-05-26 11:50:40 -070083import com.android.internal.annotations.GuardedBy;
Adam Lesinski98f0d462016-04-19 16:46:20 -070084import com.android.internal.annotations.VisibleForTesting;
Siddharth Ray78ccaf52017-12-23 16:16:21 -080085import com.android.internal.location.gnssmetrics.GnssMetrics;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070086import com.android.internal.net.NetworkStatsFactory;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080087import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070088import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080089import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070090import com.android.internal.util.JournaledFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080091import com.android.internal.util.XmlUtils;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070092
Narayan Kamath81822022017-12-08 11:56:01 +000093import java.util.List;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070094import libcore.util.EmptyArray;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080095import org.xmlpull.v1.XmlPullParser;
96import org.xmlpull.v1.XmlPullParserException;
97import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070098
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080099import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import java.io.File;
101import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800102import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.io.FileOutputStream;
104import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700105import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100106import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700108import java.util.Arrays;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800109import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.HashMap;
Evan Millarc64edde2009-04-18 12:26:32 -0700111import java.util.Iterator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import java.util.Map;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700113import java.util.concurrent.Future;
Christopher Tate4cee7252010-03-19 14:50:40 -0700114import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700115import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
117/**
118 * All information we are collecting about things that can happen that impact
119 * battery life. All times are represented in microseconds except where indicated
120 * otherwise.
121 */
Joe Onoratoabded112016-02-08 16:49:39 -0800122public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800124 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700125 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800126 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700127 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700128 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700129 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700130
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700131 // TODO: remove "tcp" from network methods, since we measure total stats.
132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700134 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
136 // Current on-disk Parcel version
Siddharth Rayb50a6842017-12-14 15:15:28 -0800137 private static final int VERSION = 174 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700138
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700139 // Maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100140 private static final int MAX_HISTORY_ITEMS;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700141
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700142 // No, really, THIS is the maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100143 private static final int MAX_MAX_HISTORY_ITEMS;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700144
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800145 // The maximum number of names wakelocks we will keep track of
146 // per uid; once the limit is reached, we batch the remaining wakelocks
147 // in to one common name.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100148 private static final int MAX_WAKELOCKS_PER_UID;
149
150 static final int MAX_HISTORY_BUFFER; // 256KB
151 static final int MAX_MAX_HISTORY_BUFFER; // 320KB
152
153 static {
154 if (ActivityManager.isLowRamDeviceStatic()) {
155 MAX_HISTORY_ITEMS = 800;
156 MAX_MAX_HISTORY_ITEMS = 1200;
157 MAX_WAKELOCKS_PER_UID = 40;
158 MAX_HISTORY_BUFFER = 96*1024; // 96KB
159 MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
160 } else {
Makoto Onuki44d64602018-01-18 08:44:28 -0800161 MAX_HISTORY_ITEMS = 4000;
162 MAX_MAX_HISTORY_ITEMS = 6000;
163 MAX_WAKELOCKS_PER_UID = 200;
164 MAX_HISTORY_BUFFER = 512*1024; // 512KB
165 MAX_MAX_HISTORY_BUFFER = 640*1024; // 640KB
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100166 }
167 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700168
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800169 // Number of transmit power states the Wifi controller can be in.
170 private static final int NUM_WIFI_TX_LEVELS = 1;
171
172 // Number of transmit power states the Bluetooth controller can be in.
173 private static final int NUM_BT_TX_LEVELS = 1;
174
Sudheer Shanka38383232017-07-25 09:55:03 -0700175 /**
176 * Holding a wakelock costs more than just using the cpu.
177 * Currently, we assign only half the cpu time to an app that is running but
178 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
179 * If no app is holding a wakelock, then the distribution is normal.
180 */
181 @VisibleForTesting
182 public static final int WAKE_LOCK_WEIGHT = 50;
183
Joe Onoratoabded112016-02-08 16:49:39 -0800184 protected Clocks mClocks;
185
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700186 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700187 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800188 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700190 static final int MSG_UPDATE_WAKELOCKS = 1;
191 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700192 static final int MSG_REPORT_CHARGING = 3;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700193 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700194
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700195 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
196 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
197
Sudheer Shanka38383232017-07-25 09:55:03 -0700198 @VisibleForTesting
199 protected KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
200 @VisibleForTesting
201 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
202 @VisibleForTesting
203 protected KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700204 new KernelUidCpuFreqTimeReader();
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800205 @VisibleForTesting
Mike Ma3d422c32017-10-25 11:08:57 -0700206 protected KernelUidCpuActiveTimeReader mKernelUidCpuActiveTimeReader =
207 new KernelUidCpuActiveTimeReader();
208 @VisibleForTesting
209 protected KernelUidCpuClusterTimeReader mKernelUidCpuClusterTimeReader =
210 new KernelUidCpuClusterTimeReader();
211 @VisibleForTesting
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800212 protected KernelSingleUidTimeReader mKernelSingleUidTimeReader;
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700213
James Carr3a226052016-07-01 14:49:52 -0700214 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
215 = new KernelMemoryBandwidthStats();
216 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
217 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
218 return mKernelMemoryStats;
219 }
220
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800221 @GuardedBy("this")
222 public boolean mPerProcStateCpuTimesAvailable = true;
223
224 /**
225 * Uids for which per-procstate cpu times need to be updated.
226 *
227 * Contains uid -> procState mappings.
228 */
229 @GuardedBy("this")
230 @VisibleForTesting
231 protected final SparseIntArray mPendingUids = new SparseIntArray();
232
Bookatz0b8a0502017-09-13 11:51:52 -0700233 /** Container for Resource Power Manager stats. Updated by updateRpmStatsLocked. */
Bookatz50df7112017-08-04 14:53:26 -0700234 private final RpmStats mTmpRpmStats = new RpmStats();
Bookatz0b8a0502017-09-13 11:51:52 -0700235 /** The soonest the RPM stats can be updated after it was last updated. */
236 private static final long RPM_STATS_UPDATE_FREQ_MS = 1000;
237 /** Last time that RPM stats were updated by updateRpmStatsLocked. */
238 private long mLastRpmStatsUpdateTimeMs = -RPM_STATS_UPDATE_FREQ_MS;
Bookatz50df7112017-08-04 14:53:26 -0700239
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700240 public interface BatteryCallback {
241 public void batteryNeedsCpuUpdate();
242 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700243 public void batterySendBroadcast(Intent intent);
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700244 }
245
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700246 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700247 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700248 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000249 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700250 }
251
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700252 public static abstract class UserInfoProvider {
253 private int[] userIds;
254 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700255 @VisibleForTesting
256 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700257 userIds = getUserIds();
258 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700259 @VisibleForTesting
260 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700261 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
262 }
263 }
264
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700265 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
266
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700267 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800268 public MyHandler(Looper looper) {
269 super(looper, null, true);
270 }
271
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700272 @Override
273 public void handleMessage(Message msg) {
274 BatteryCallback cb = mCallback;
275 switch (msg.what) {
276 case MSG_UPDATE_WAKELOCKS:
Adam Lesinski72478f02015-06-17 15:39:43 -0700277 synchronized (BatteryStatsImpl.this) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -0700278 updateCpuTimeLocked();
Adam Lesinski72478f02015-06-17 15:39:43 -0700279 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700280 if (cb != null) {
281 cb.batteryNeedsCpuUpdate();
282 }
283 break;
284 case MSG_REPORT_POWER_CHANGE:
285 if (cb != null) {
286 cb.batteryPowerChanged(msg.arg1 != 0);
287 }
288 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700289 case MSG_REPORT_CHARGING:
290 if (cb != null) {
291 final String action;
292 synchronized (BatteryStatsImpl.this) {
293 action = mCharging ? BatteryManager.ACTION_CHARGING
294 : BatteryManager.ACTION_DISCHARGING;
295 }
296 Intent intent = new Intent(action);
297 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
298 cb.batterySendBroadcast(intent);
299 }
300 break;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700301 }
302 }
303 }
304
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800305 /**
306 * Update per-freq cpu times for all the uids in {@link #mPendingUids}.
307 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800308 public void updateProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800309 final SparseIntArray uidStates;
310 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800311 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
312 return;
313 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800314 if(!initKernelSingleUidTimeReaderLocked()) {
315 return;
316 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800317 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
318 // compute deltas since it might result in mis-attributing cpu times to wrong states.
319 if (mKernelSingleUidTimeReader.hasStaleData()) {
320 mPendingUids.clear();
321 return;
322 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800323
324 if (mPendingUids.size() == 0) {
325 return;
326 }
327 uidStates = mPendingUids.clone();
328 mPendingUids.clear();
329 }
330 for (int i = uidStates.size() - 1; i >= 0; --i) {
331 final int uid = uidStates.keyAt(i);
332 final int procState = uidStates.valueAt(i);
333 final int[] isolatedUids;
334 final Uid u;
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800335 synchronized (BatteryStatsImpl.this) {
336 // It's possible that uid no longer exists and any internal references have
337 // already been deleted, so using {@link #getAvailableUidStatsLocked} to avoid
338 // creating an UidStats object if it doesn't already exist.
339 u = getAvailableUidStatsLocked(uid);
340 if (u == null) {
341 continue;
342 }
343 if (u.mChildUids == null) {
344 isolatedUids = null;
345 } else {
346 isolatedUids = u.mChildUids.toArray();
347 for (int j = isolatedUids.length - 1; j >= 0; --j) {
348 isolatedUids[j] = u.mChildUids.get(j);
349 }
350 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800351 }
352 long[] cpuTimesMs = mKernelSingleUidTimeReader.readDeltaMs(uid);
353 if (isolatedUids != null) {
354 for (int j = isolatedUids.length - 1; j >= 0; --j) {
355 cpuTimesMs = addCpuTimes(cpuTimesMs,
356 mKernelSingleUidTimeReader.readDeltaMs(isolatedUids[j]));
357 }
358 }
359 if (onBattery && cpuTimesMs != null) {
360 synchronized (BatteryStatsImpl.this) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800361 u.addProcStateTimesMs(procState, cpuTimesMs, onBattery);
362 u.addProcStateScreenOffTimesMs(procState, cpuTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800363 }
364 }
365 }
366 }
367
Sudheer Shankae544d162017-12-28 17:06:20 -0800368 public void copyFromAllUidsCpuTimes() {
369 synchronized (BatteryStatsImpl.this) {
370 copyFromAllUidsCpuTimes(
371 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
372 }
373 }
374
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800375 /**
376 * When the battery/screen state changes, we don't attribute the cpu times to any process
377 * but we still need to snapshots of all uids to get correct deltas later on. Since we
378 * already read this data for updating per-freq cpu times, we can use the same data for
379 * per-procstate cpu times.
380 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800381 public void copyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800382 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800383 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
384 return;
385 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800386 if(!initKernelSingleUidTimeReaderLocked()) {
387 return;
388 }
389
390 final SparseArray<long[]> allUidCpuFreqTimesMs =
391 mKernelUidCpuFreqTimeReader.getAllUidCpuFreqTimeMs();
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800392 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
393 // compute deltas since it might result in mis-attributing cpu times to wrong states.
394 if (mKernelSingleUidTimeReader.hasStaleData()) {
395 mKernelSingleUidTimeReader.setAllUidsCpuTimesMs(allUidCpuFreqTimesMs);
396 mKernelSingleUidTimeReader.markDataAsStale(false);
397 mPendingUids.clear();
398 return;
399 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800400 for (int i = allUidCpuFreqTimesMs.size() - 1; i >= 0; --i) {
401 final int uid = allUidCpuFreqTimesMs.keyAt(i);
402 final Uid u = getAvailableUidStatsLocked(mapUid(uid));
403 if (u == null) {
404 continue;
405 }
406 final long[] cpuTimesMs = allUidCpuFreqTimesMs.valueAt(i);
407 if (cpuTimesMs == null) {
408 continue;
409 }
410 final long[] deltaTimesMs = mKernelSingleUidTimeReader.computeDelta(
411 uid, cpuTimesMs.clone());
Sudheer Shankae544d162017-12-28 17:06:20 -0800412 if (onBattery && deltaTimesMs != null) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800413 final int procState;
414 final int idx = mPendingUids.indexOfKey(uid);
415 if (idx >= 0) {
416 procState = mPendingUids.valueAt(idx);
417 mPendingUids.removeAt(idx);
418 } else {
419 procState = u.mProcessState;
420 }
421 if (procState >= 0 && procState < Uid.NUM_PROCESS_STATE) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800422 u.addProcStateTimesMs(procState, deltaTimesMs, onBattery);
423 u.addProcStateScreenOffTimesMs(procState, deltaTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800424 }
425 }
426 }
427 }
428 }
429
430 @VisibleForTesting
431 public long[] addCpuTimes(long[] timesA, long[] timesB) {
432 if (timesA != null && timesB != null) {
433 for (int i = timesA.length - 1; i >= 0; --i) {
434 timesA[i] += timesB[i];
435 }
436 return timesA;
437 }
438 return timesA == null ? (timesB == null ? null : timesB) : timesA;
439 }
440
441 @GuardedBy("this")
442 private boolean initKernelSingleUidTimeReaderLocked() {
443 if (mKernelSingleUidTimeReader == null) {
444 if (mPowerProfile == null) {
445 return false;
446 }
447 if (mCpuFreqs == null) {
448 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
449 }
450 if (mCpuFreqs != null) {
451 mKernelSingleUidTimeReader = new KernelSingleUidTimeReader(mCpuFreqs.length);
452 } else {
453 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable();
454 return false;
455 }
456 }
457 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable()
458 && mKernelSingleUidTimeReader.singleUidCpuTimesAvailable();
459 return true;
460 }
461
Joe Onoratoabded112016-02-08 16:49:39 -0800462 public interface Clocks {
463 public long elapsedRealtime();
464 public long uptimeMillis();
465 }
466
467 public static class SystemClocks implements Clocks {
468 public long elapsedRealtime() {
469 return SystemClock.elapsedRealtime();
470 }
471
472 public long uptimeMillis() {
473 return SystemClock.uptimeMillis();
474 }
475 }
476
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700477 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700478 int UPDATE_CPU = 0x01;
479 int UPDATE_WIFI = 0x02;
480 int UPDATE_RADIO = 0x04;
481 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700482 int UPDATE_RPM = 0x10; // 16
483 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800484
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700485 Future<?> scheduleSync(String reason, int flags);
486 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Sudheer Shankae544d162017-12-28 17:06:20 -0800487 Future<?> scheduleReadProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
488 Future<?> scheduleCopyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800489 Future<?> scheduleCpuSyncDueToSettingChange();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700490 }
491
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800492 public Handler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700493 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700494 @VisibleForTesting
495 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700496
497 private BatteryCallback mCallback;
498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800500 * Mapping isolated uids to the actual owning app uid.
501 */
502 final SparseIntArray mIsolatedUids = new SparseIntArray();
503
504 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 * The statistics we have collected organized by uids.
506 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800507 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508
509 // A set of pools of currently active timers. When a timer is queried, we will divide the
510 // elapsed time by the number of active timers to arrive at that timer's share of the time.
511 // In order to do this, we must refresh each timer whenever the number of active timers
512 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700513 @VisibleForTesting
514 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700515 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
516 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700517 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700518 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
519 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
520 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
521 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
522 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
523 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
524 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
525 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700526 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
527 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800528 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700530 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700531 @VisibleForTesting
532 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 // These are the objects that will want to do something when the device
535 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800536 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800537
538 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700539 // is unplugged from power *and* the screen is off or doze.
540 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800541
542 // Set to true when we want to distribute CPU across wakelocks for the next
543 // CPU update, even if we aren't currently running wake locks.
544 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700545
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700546 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700547
Dianne Hackborn37de0982014-05-09 09:32:18 -0700548 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800549
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700550 long mHistoryBaseTime;
Narayan Kamath695cf722017-12-21 18:32:47 +0000551 protected boolean mHaveBatteryLevel = false;
552 protected boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700553 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700554
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700555 final Parcel mHistoryBuffer = Parcel.obtain();
556 final HistoryItem mHistoryLastWritten = new HistoryItem();
557 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700558 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700559 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700560 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800561 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800562 int[] mReadHistoryUids;
563 int mReadHistoryChars;
564 int mNextHistoryTagIdx = 0;
565 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700566 int mHistoryBufferLastPos = -1;
567 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700568 int mActiveHistoryStates = 0xffffffff;
569 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700570 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700571 long mTrackRunningHistoryElapsedRealtime = 0;
572 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700573
574 final HistoryItem mHistoryCur = new HistoryItem();
575
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700576 HistoryItem mHistory;
577 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700578 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700579 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700580
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800581 // Used by computeHistoryStepDetails
582 HistoryStepDetails mLastHistoryStepDetails = null;
583 byte mLastHistoryStepLevel = 0;
584 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
585 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
586 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700587
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800588 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700589 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800590 */
591 long mLastStepCpuUserTime;
592 long mCurStepCpuUserTime;
593 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700594 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800595 */
596 long mLastStepCpuSystemTime;
597 long mCurStepCpuSystemTime;
598 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700599 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800600 */
601 long mLastStepStatUserTime;
602 long mLastStepStatSystemTime;
603 long mLastStepStatIOWaitTime;
604 long mLastStepStatIrqTime;
605 long mLastStepStatSoftIrqTime;
606 long mLastStepStatIdleTime;
607 long mCurStepStatUserTime;
608 long mCurStepStatSystemTime;
609 long mCurStepStatIOWaitTime;
610 long mCurStepStatIrqTime;
611 long mCurStepStatSoftIrqTime;
612 long mCurStepStatIdleTime;
613
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700614 private HistoryItem mHistoryIterator;
615 private boolean mReadOverflow;
616 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 int mStartCount;
619
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800620 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700621 String mStartPlatformVersion;
622 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 long mUptime;
625 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 long mRealtime;
627 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700628
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800629 int mWakeLockNesting;
630 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700631 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700632 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800633
Mike Mac2f518a2017-09-19 16:06:03 -0700634 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
635 protected int mScreenState = Display.STATE_UNKNOWN;
636 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
637 protected StopwatchTimer mScreenOnTimer;
638 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
639 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700640
Dianne Hackborn617f8772009-03-31 15:04:46 -0700641 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700642 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700643
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800644 boolean mPretendScreenOff;
645
Jeff Browne95c3cd2014-05-02 16:59:26 -0700646 boolean mInteractive;
647 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700648
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700649 boolean mPowerSaveModeEnabled;
650 StopwatchTimer mPowerSaveModeEnabledTimer;
651
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700652 boolean mDeviceIdling;
653 StopwatchTimer mDeviceIdlingTimer;
654
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700655 boolean mDeviceLightIdling;
656 StopwatchTimer mDeviceLightIdlingTimer;
657
658 int mDeviceIdleMode;
659 long mLastIdleTimeStart;
660 long mLongestLightIdleTime;
661 long mLongestFullIdleTime;
662 StopwatchTimer mDeviceIdleModeLightTimer;
663 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700666 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700667
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700668 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700669 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700670
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700671 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700672 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700673
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700674 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700675 StopwatchTimer mFlashlightOnTimer;
676
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700677 int mCameraOnNesting;
678 StopwatchTimer mCameraOnTimer;
679
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800680 int mGpsSignalQualityBin = -1;
681 final StopwatchTimer[] mGpsSignalQualityTimer =
682 new StopwatchTimer[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
683
Dianne Hackborn627bba72009-03-24 22:32:56 -0700684 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800685 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700686 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800687 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700688
689 StopwatchTimer mPhoneSignalScanningTimer;
690
Dianne Hackborn627bba72009-03-24 22:32:56 -0700691 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700692 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700693 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700694
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800695 final LongSamplingCounter[] mNetworkByteActivityCounters =
696 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
697 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700698 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
699
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800700 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800701 * The WiFi Overall wakelock timer
702 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
703 * since addition of per UID timers would not result in an accurate value due to overlapp of
704 * per uid wakelock timers
705 */
706 StopwatchTimer mWifiMulticastWakelockTimer;
707
708 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800709 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
710 */
711 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700712
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800713 /**
714 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
715 */
716 ControllerActivityCounterImpl mBluetoothActivity;
717
718 /**
719 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
720 */
721 ControllerActivityCounterImpl mModemActivity;
722
723 /**
724 * Whether the device supports WiFi controller energy reporting. This is set to true on
725 * the first WiFi energy report. See {@link #mWifiActivity}.
726 */
727 boolean mHasWifiReporting = false;
728
729 /**
730 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
731 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
732 */
733 boolean mHasBluetoothReporting = false;
734
735 /**
736 * Whether the device supports Modem controller energy reporting. This is set to true on
737 * the first Modem energy report. See {@link #mModemActivity}.
738 */
739 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700740
The Android Open Source Project10592532009-03-18 17:39:46 -0700741 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700742 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700743
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700744 boolean mGlobalWifiRunning;
745 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700746
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800747 int mWifiState = -1;
748 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
749
Dianne Hackborn3251b902014-06-20 14:40:53 -0700750 int mWifiSupplState = -1;
751 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
752
753 int mWifiSignalStrengthBin = -1;
754 final StopwatchTimer[] mWifiSignalStrengthsTimer =
755 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
756
Siddharth Rayb50a6842017-12-14 15:15:28 -0800757 StopwatchTimer mWifiActiveTimer;
758
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800759 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800760 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
761 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800762
Siddharth Rayf5e796a2018-01-22 18:18:17 -0800763 boolean mIsCellularTxPowerHigh = false;
764
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700765 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700766 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800767 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800768 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700769 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800770 LongSamplingCounter mMobileRadioActiveUnknownTime;
771 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800772
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700773 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 /**
776 * These provide time bases that discount the time the device is plugged
777 * in to power.
778 */
779 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700780 @VisibleForTesting
781 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700782
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700783 /**
784 * External reporting of whether the device is actually charging.
785 */
786 boolean mCharging = true;
787 int mLastChargingStateLevel;
788
The Android Open Source Project10592532009-03-18 17:39:46 -0700789 /*
790 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
791 */
Evan Millar633a1742009-04-02 16:36:33 -0700792 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700793 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700794 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700795 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700796 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700797 int mLowDischargeAmountSinceCharge;
798 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800799 int mDischargeScreenOnUnplugLevel;
800 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700801 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800802 int mDischargeAmountScreenOn;
803 int mDischargeAmountScreenOnSinceCharge;
804 int mDischargeAmountScreenOff;
805 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700806 int mDischargeAmountScreenDoze;
807 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700808
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700809 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700810 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700811 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800812 private LongSamplingCounter mDischargeLightDozeCounter;
813 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700814
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700815 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700816
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700817 int mInitStepMode = 0;
818 int mCurStepMode = 0;
819 int mModStepMode = 0;
820
Dianne Hackborn260c5022014-04-29 11:23:16 -0700821 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700822 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800823 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
824 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700825 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700826
827 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700828 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800829 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
830 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
831
832 static final int MAX_DAILY_ITEMS = 10;
833
834 long mDailyStartTime = 0;
835 long mNextMinDailyDeadline = 0;
836 long mNextMaxDailyDeadline = 0;
837
838 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700841
Amith Yamasanif37447b2009-10-08 18:28:01 -0700842 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800843 private int mPhoneServiceStateRaw = -1;
844 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700845
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800846 private int mNumConnectivityChange;
847 private int mLoadedNumConnectivityChange;
848 private int mUnpluggedNumConnectivityChange;
849
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700850 private int mEstimatedBatteryCapacity = -1;
851
Jocelyn Dangc627d102017-04-14 13:15:14 -0700852 private int mMinLearnedBatteryCapacity = -1;
853 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800854
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700855 private long[] mCpuFreqs;
856
Sudheer Shanka38383232017-07-25 09:55:03 -0700857 @VisibleForTesting
858 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700859
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800860 @GuardedBy("this")
861 private final Constants mConstants;
862
Evan Millarc64edde2009-04-18 12:26:32 -0700863 /*
Bookatz50df7112017-08-04 14:53:26 -0700864 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
865 * recording their times when on-battery (regardless of screen state).
866 */
867 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
868 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
869 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
870
871 @Override
872 public Map<String, ? extends Timer> getRpmStats() {
873 return mRpmStats;
874 }
875
Bookatz82b341172017-09-07 19:06:08 -0700876 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700877 @Override
878 public Map<String, ? extends Timer> getScreenOffRpmStats() {
879 return mScreenOffRpmStats;
880 }
881
882 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700883 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
884 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700885 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700886
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700887 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700888 return mKernelWakelockStats;
889 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700890
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700891 String mLastWakeupReason = null;
892 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700893 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700894
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700895 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700896 return mWakeupReasonStats;
897 }
898
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700899 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700900 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700901 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700902 }
903
904 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700905 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700906 return mDischargeScreenOffCounter.getCountLocked(which);
907 }
908
909 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700910 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700911 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700912 }
913
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700914 @Override
Mike Ma15313c92017-11-15 17:58:21 -0800915 public long getUahDischargeLightDoze(int which) {
916 return mDischargeLightDozeCounter.getCountLocked(which);
917 }
918
919 @Override
920 public long getUahDischargeDeepDoze(int which) {
921 return mDischargeDeepDozeCounter.getCountLocked(which);
922 }
923
924 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700925 public int getEstimatedBatteryCapacity() {
926 return mEstimatedBatteryCapacity;
927 }
928
Jocelyn Dangc627d102017-04-14 13:15:14 -0700929 @Override
930 public int getMinLearnedBatteryCapacity() {
931 return mMinLearnedBatteryCapacity;
932 }
933
934 @Override
935 public int getMaxLearnedBatteryCapacity() {
936 return mMaxLearnedBatteryCapacity;
937 }
938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -0800940 this(new SystemClocks());
941 }
942
943 public BatteryStatsImpl(Clocks clocks) {
944 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700945 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700946 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800947 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700948 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700949 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700950 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800951 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700952 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 }
954
Joe Onoratoabded112016-02-08 16:49:39 -0800955 private void init(Clocks clocks) {
956 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -0800957 }
958
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700959 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800960 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
961 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
962 }
963
Joe Onoratoabded112016-02-08 16:49:39 -0800964 // methods are protected not private to be VisibleForTesting
965 public static class TimeBase {
966 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800967
Joe Onoratoabded112016-02-08 16:49:39 -0800968 protected long mUptime;
969 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800970
Joe Onoratoabded112016-02-08 16:49:39 -0800971 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800972
Joe Onoratoabded112016-02-08 16:49:39 -0800973 protected long mPastUptime;
974 protected long mUptimeStart;
975 protected long mPastRealtime;
976 protected long mRealtimeStart;
977 protected long mUnpluggedUptime;
978 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800979
980 public void dump(PrintWriter pw, String prefix) {
981 StringBuilder sb = new StringBuilder(128);
982 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
983 sb.setLength(0);
984 sb.append(prefix);
985 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700986 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800987 pw.println(sb.toString());
988 sb.setLength(0);
989 sb.append(prefix);
990 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700991 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800992 pw.println(sb.toString());
993 sb.setLength(0);
994 sb.append(prefix);
995 sb.append("mPastUptime=");
996 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
997 formatTimeMs(sb, mUptimeStart / 1000);
998 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
999 pw.println(sb.toString());
1000 sb.setLength(0);
1001 sb.append(prefix);
1002 sb.append("mPastRealtime=");
1003 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
1004 formatTimeMs(sb, mRealtimeStart / 1000);
1005 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
1006 pw.println(sb.toString());
1007 }
1008
1009 public void add(TimeBaseObs observer) {
1010 mObservers.add(observer);
1011 }
1012
1013 public void remove(TimeBaseObs observer) {
1014 if (!mObservers.remove(observer)) {
1015 Slog.wtf(TAG, "Removed unknown observer: " + observer);
1016 }
1017 }
1018
Joe Onoratoabded112016-02-08 16:49:39 -08001019 public boolean hasObserver(TimeBaseObs observer) {
1020 return mObservers.contains(observer);
1021 }
1022
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001023 public void init(long uptime, long realtime) {
1024 mRealtime = 0;
1025 mUptime = 0;
1026 mPastUptime = 0;
1027 mPastRealtime = 0;
1028 mUptimeStart = uptime;
1029 mRealtimeStart = realtime;
1030 mUnpluggedUptime = getUptime(mUptimeStart);
1031 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1032 }
1033
1034 public void reset(long uptime, long realtime) {
1035 if (!mRunning) {
1036 mPastUptime = 0;
1037 mPastRealtime = 0;
1038 } else {
1039 mUptimeStart = uptime;
1040 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001041 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1042 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001043 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001044 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001045 mUnpluggedRealtime = getRealtime(realtime);
1046 }
1047 }
1048
1049 public long computeUptime(long curTime, int which) {
1050 switch (which) {
1051 case STATS_SINCE_CHARGED:
1052 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001053 case STATS_CURRENT:
1054 return getUptime(curTime);
1055 case STATS_SINCE_UNPLUGGED:
1056 return getUptime(curTime) - mUnpluggedUptime;
1057 }
1058 return 0;
1059 }
1060
1061 public long computeRealtime(long curTime, int which) {
1062 switch (which) {
1063 case STATS_SINCE_CHARGED:
1064 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001065 case STATS_CURRENT:
1066 return getRealtime(curTime);
1067 case STATS_SINCE_UNPLUGGED:
1068 return getRealtime(curTime) - mUnpluggedRealtime;
1069 }
1070 return 0;
1071 }
1072
1073 public long getUptime(long curTime) {
1074 long time = mPastUptime;
1075 if (mRunning) {
1076 time += curTime - mUptimeStart;
1077 }
1078 return time;
1079 }
1080
1081 public long getRealtime(long curTime) {
1082 long time = mPastRealtime;
1083 if (mRunning) {
1084 time += curTime - mRealtimeStart;
1085 }
1086 return time;
1087 }
1088
1089 public long getUptimeStart() {
1090 return mUptimeStart;
1091 }
1092
1093 public long getRealtimeStart() {
1094 return mRealtimeStart;
1095 }
1096
1097 public boolean isRunning() {
1098 return mRunning;
1099 }
1100
1101 public boolean setRunning(boolean running, long uptime, long realtime) {
1102 if (mRunning != running) {
1103 mRunning = running;
1104 if (running) {
1105 mUptimeStart = uptime;
1106 mRealtimeStart = realtime;
1107 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1108 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
1109
1110 for (int i = mObservers.size() - 1; i >= 0; i--) {
1111 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
1112 }
1113 } else {
1114 mPastUptime += uptime - mUptimeStart;
1115 mPastRealtime += realtime - mRealtimeStart;
1116
1117 long batteryUptime = getUptime(uptime);
1118 long batteryRealtime = getRealtime(realtime);
1119
1120 for (int i = mObservers.size() - 1; i >= 0; i--) {
1121 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
1122 }
1123 }
1124 return true;
1125 }
1126 return false;
1127 }
1128
1129 public void readSummaryFromParcel(Parcel in) {
1130 mUptime = in.readLong();
1131 mRealtime = in.readLong();
1132 }
1133
1134 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1135 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1136 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1137 }
1138
1139 public void readFromParcel(Parcel in) {
1140 mRunning = false;
1141 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001142 mPastUptime = in.readLong();
1143 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001144 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001145 mPastRealtime = in.readLong();
1146 mRealtimeStart = in.readLong();
1147 mUnpluggedUptime = in.readLong();
1148 mUnpluggedRealtime = in.readLong();
1149 }
1150
1151 public void writeToParcel(Parcel out, long uptime, long realtime) {
1152 final long runningUptime = getUptime(uptime);
1153 final long runningRealtime = getRealtime(realtime);
1154 out.writeLong(mUptime);
1155 out.writeLong(runningUptime);
1156 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001157 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001158 out.writeLong(runningRealtime);
1159 out.writeLong(mRealtimeStart);
1160 out.writeLong(mUnpluggedUptime);
1161 out.writeLong(mUnpluggedRealtime);
1162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001166 * State for keeping track of counting information.
1167 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001168 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -07001169 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001170 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001171 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001172 int mUnpluggedCount;
1173 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001174
Bookatz8c6f3c52017-05-24 12:00:17 -07001175 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001176 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -07001177 mPluggedCount = in.readInt();
1178 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001179 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001180 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001181 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001182 }
1183
Bookatz8c6f3c52017-05-24 12:00:17 -07001184 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001185 mTimeBase = timeBase;
1186 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001187 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001188
Dianne Hackborn617f8772009-03-31 15:04:46 -07001189 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001190 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001191 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001192 out.writeInt(mUnpluggedCount);
1193 }
1194
Bookatz8c6f3c52017-05-24 12:00:17 -07001195 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001196 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001197 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001198 }
1199
Bookatz8c6f3c52017-05-24 12:00:17 -07001200 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001201 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001202 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001203 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001204
Dianne Hackborn617f8772009-03-31 15:04:46 -07001205 /**
1206 * Writes a possibly null Counter to a Parcel.
1207 *
1208 * @param out the Parcel to be written to.
1209 * @param counter a Counter, or null.
1210 */
1211 public static void writeCounterToParcel(Parcel out, Counter counter) {
1212 if (counter == null) {
1213 out.writeInt(0); // indicates null
1214 return;
1215 }
1216 out.writeInt(1); // indicates non-null
1217
1218 counter.writeToParcel(out);
1219 }
1220
1221 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001222 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001223 int val = mCount.get();
1224 if (which == STATS_SINCE_UNPLUGGED) {
1225 val -= mUnpluggedCount;
1226 } else if (which != STATS_SINCE_CHARGED) {
1227 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001228 }
1229
1230 return val;
1231 }
1232
1233 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001234 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001235 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001236 + " mUnpluggedCount=" + mUnpluggedCount
1237 + " mPluggedCount=" + mPluggedCount);
1238 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001239
Bookatz8c6f3c52017-05-24 12:00:17 -07001240 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1241 public void stepAtomic() {
1242 if (mTimeBase.isRunning()) {
1243 mCount.incrementAndGet();
1244 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001245 }
1246
Bookatz4ebc0642017-05-11 12:21:19 -07001247 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001248 if (mTimeBase.isRunning()) {
1249 mCount.addAndGet(delta);
1250 }
Bookatz4ebc0642017-05-11 12:21:19 -07001251 }
1252
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001253 /**
1254 * Clear state of this counter.
1255 */
1256 void reset(boolean detachIfReset) {
1257 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001258 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001259 if (detachIfReset) {
1260 detach();
1261 }
1262 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001263
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001264 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001265 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001266 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001267
Bookatz8c6f3c52017-05-24 12:00:17 -07001268 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1269 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001270 int count = mCount.get();
1271 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001272 }
1273
Bookatz8c6f3c52017-05-24 12:00:17 -07001274 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1275 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001276 mLoadedCount = in.readInt();
1277 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001278 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001279 }
1280 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001281
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001282 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001283 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1284 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001285 public long[] mCounts;
1286 public long[] mLoadedCounts;
1287 public long[] mUnpluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001288
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001289 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001290 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001291 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001292 mLoadedCounts = in.createLongArray();
1293 mUnpluggedCounts = in.createLongArray();
1294 timeBase.add(this);
1295 }
1296
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001297 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001298 mTimeBase = timeBase;
1299 timeBase.add(this);
1300 }
1301
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001302 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001303 out.writeLongArray(mCounts);
1304 out.writeLongArray(mLoadedCounts);
1305 out.writeLongArray(mUnpluggedCounts);
1306 }
1307
1308 @Override
1309 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001310 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001311 }
1312
1313 @Override
1314 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001315 }
1316
1317 @Override
1318 public long[] getCountsLocked(int which) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001319 long[] val = copyArray(mCounts, null);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001320 if (which == STATS_SINCE_UNPLUGGED) {
1321 subtract(val, mUnpluggedCounts);
1322 } else if (which != STATS_SINCE_CHARGED) {
1323 subtract(val, mLoadedCounts);
1324 }
1325 return val;
1326 }
1327
1328 @Override
1329 public void logState(Printer pw, String prefix) {
1330 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1331 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
Sudheer Shankae544d162017-12-28 17:06:20 -08001332 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001333 }
1334
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001335 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001336 addCountLocked(counts, mTimeBase.isRunning());
1337 }
1338
1339 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001340 if (counts == null) {
1341 return;
1342 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001343 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001344 if (mCounts == null) {
1345 mCounts = new long[counts.length];
1346 }
1347 for (int i = 0; i < counts.length; ++i) {
1348 mCounts[i] += counts[i];
1349 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001350 }
1351 }
1352
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001353 public int getSize() {
1354 return mCounts == null ? 0 : mCounts.length;
1355 }
1356
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001357 /**
1358 * Clear state of this counter.
1359 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001360 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001361 fillArray(mCounts, 0);
1362 fillArray(mLoadedCounts, 0);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001363 fillArray(mUnpluggedCounts, 0);
1364 if (detachIfReset) {
1365 detach();
1366 }
1367 }
1368
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001369 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001370 mTimeBase.remove(this);
1371 }
1372
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001373 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001374 out.writeLongArray(mCounts);
1375 }
1376
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001377 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001378 mCounts = in.createLongArray();
1379 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1380 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001381 }
1382
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001383 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1384 if (counterArray != null) {
1385 out.writeInt(1);
1386 counterArray.writeToParcel(out);
1387 } else {
1388 out.writeInt(0);
1389 }
1390 }
1391
1392 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1393 if (in.readInt() != 0) {
1394 return new LongSamplingCounterArray(timeBase, in);
1395 } else {
1396 return null;
1397 }
1398 }
1399
1400 public static void writeSummaryToParcelLocked(Parcel out,
1401 LongSamplingCounterArray counterArray) {
1402 if (counterArray != null) {
1403 out.writeInt(1);
1404 counterArray.writeSummaryToParcelLocked(out);
1405 } else {
1406 out.writeInt(0);
1407 }
1408 }
1409
1410 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1411 TimeBase timeBase) {
1412 if (in.readInt() != 0) {
1413 final LongSamplingCounterArray counterArray
1414 = new LongSamplingCounterArray(timeBase);
1415 counterArray.readSummaryFromParcelLocked(in);
1416 return counterArray;
1417 } else {
1418 return null;
1419 }
1420 }
1421
Bookatz8c6f3c52017-05-24 12:00:17 -07001422 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001423 if (a != null) {
1424 Arrays.fill(a, val);
1425 }
1426 }
1427
Bookatz8c6f3c52017-05-24 12:00:17 -07001428 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001429 if (toSubtract == null) {
1430 return;
1431 }
1432 for (int i = 0; i < val.length; i++) {
1433 val[i] -= toSubtract[i];
1434 }
1435 }
1436
Bookatz8c6f3c52017-05-24 12:00:17 -07001437 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001438 if (src == null) {
1439 return null;
1440 } else {
1441 if (dest == null) {
1442 dest = new long[src.length];
1443 }
1444 System.arraycopy(src, 0, dest, 0, src.length);
1445 return dest;
1446 }
1447 }
1448 }
1449
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001450 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001451 final TimeBase mTimeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001452 long mCount;
1453 long mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001454 long mUnpluggedCount;
1455 long mPluggedCount;
1456
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001457 LongSamplingCounter(TimeBase timeBase, Parcel in) {
1458 mTimeBase = timeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001459 mPluggedCount = in.readLong();
1460 mCount = mPluggedCount;
1461 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001462 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001463 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001464 }
1465
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001466 LongSamplingCounter(TimeBase timeBase) {
1467 mTimeBase = timeBase;
1468 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001469 }
1470
1471 public void writeToParcel(Parcel out) {
1472 out.writeLong(mCount);
1473 out.writeLong(mLoadedCount);
1474 out.writeLong(mUnpluggedCount);
1475 }
1476
1477 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001478 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001479 mUnpluggedCount = mPluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001480 }
1481
1482 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001483 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001484 mPluggedCount = mCount;
1485 }
1486
1487 public long getCountLocked(int which) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001488 long val = mTimeBase.isRunning() ? mCount : mPluggedCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001489 if (which == STATS_SINCE_UNPLUGGED) {
1490 val -= mUnpluggedCount;
1491 } else if (which != STATS_SINCE_CHARGED) {
1492 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001493 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001494 return val;
1495 }
1496
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001497 @Override
1498 public void logState(Printer pw, String prefix) {
1499 pw.println(prefix + "mCount=" + mCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001500 + " mLoadedCount=" + mLoadedCount
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001501 + " mUnpluggedCount=" + mUnpluggedCount
1502 + " mPluggedCount=" + mPluggedCount);
1503 }
1504
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001505 void addCountLocked(long count) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001506 if (mTimeBase.isRunning()) {
1507 mCount += count;
1508 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001509 }
1510
1511 /**
1512 * Clear state of this counter.
1513 */
1514 void reset(boolean detachIfReset) {
1515 mCount = 0;
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001516 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001517 if (detachIfReset) {
1518 detach();
1519 }
1520 }
1521
1522 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001523 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001524 }
1525
1526 void writeSummaryFromParcelLocked(Parcel out) {
1527 out.writeLong(mCount);
1528 }
1529
1530 void readSummaryFromParcelLocked(Parcel in) {
1531 mLoadedCount = in.readLong();
1532 mCount = mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001533 mUnpluggedCount = mPluggedCount = mLoadedCount;
1534 }
1535 }
1536
Dianne Hackborn617f8772009-03-31 15:04:46 -07001537 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 * State for keeping track of timing information.
1539 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001540 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001541 protected final Clocks mClocks;
1542 protected final int mType;
1543 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001544
Joe Onoratoabded112016-02-08 16:49:39 -08001545 protected int mCount;
1546 protected int mLoadedCount;
1547 protected int mLastCount;
1548 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 // Times are in microseconds for better accuracy when dividing by the
1551 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 /**
1554 * The total time we have accumulated since the start of the original
1555 * boot, to the last time something interesting happened in the
1556 * current run.
1557 */
Joe Onoratoabded112016-02-08 16:49:39 -08001558 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 /**
1561 * The total time we loaded for the previous runs. Subtract this from
1562 * mTotalTime to find the time for the current run of the system.
1563 */
Joe Onoratoabded112016-02-08 16:49:39 -08001564 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 /**
1567 * The run time of the last run of the system, as loaded from the
1568 * saved data.
1569 */
Joe Onoratoabded112016-02-08 16:49:39 -08001570 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 /**
1573 * The value of mTotalTime when unplug() was last called. Subtract
1574 * this from mTotalTime to find the time since the last unplug from
1575 * power.
1576 */
Joe Onoratoabded112016-02-08 16:49:39 -08001577 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001578
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001579 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001580 * The total time this timer has been running until the latest mark has been set.
1581 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1582 */
Joe Onoratoabded112016-02-08 16:49:39 -08001583 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001584
1585 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001586 * Constructs from a parcel.
1587 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001588 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001589 * @param in
1590 */
Joe Onoratoabded112016-02-08 16:49:39 -08001591 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1592 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001594 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 mCount = in.readInt();
1597 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001598 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 mUnpluggedCount = in.readInt();
1600 mTotalTime = in.readLong();
1601 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001602 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001604 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001605 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001606 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
1608
Joe Onoratoabded112016-02-08 16:49:39 -08001609 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1610 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001612 mTimeBase = timeBase;
1613 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 }
Evan Millarc64edde2009-04-18 12:26:32 -07001615
1616 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001617
Evan Millarc64edde2009-04-18 12:26:32 -07001618 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001619
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001620 /**
1621 * Clear state of this timer. Returns true if the timer is inactive
1622 * so can be completely dropped.
1623 */
Joe Onoratoabded112016-02-08 16:49:39 -08001624 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001625 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001626 mCount = mLoadedCount = mLastCount = 0;
1627 if (detachIfReset) {
1628 detach();
1629 }
1630 return true;
1631 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001632
Joe Onoratoabded112016-02-08 16:49:39 -08001633 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001634 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001635 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001636
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001637 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001638 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1639 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001640 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001643 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001646 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
1648
Adam Lesinskie08af192015-03-25 16:42:59 -07001649 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001650 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001652 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 + " old mUnpluggedTime=" + mUnpluggedTime
1654 + " old mUnpluggedCount=" + mUnpluggedCount);
1655 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001656 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001657 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 if (DEBUG && mType < 0) {
1659 Log.v(TAG, "unplug #" + mType
1660 + ": new mUnpluggedTime=" + mUnpluggedTime
1661 + " new mUnpluggedCount=" + mUnpluggedCount);
1662 }
1663 }
1664
Adam Lesinskie08af192015-03-25 16:42:59 -07001665 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001666 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001667 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001668 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001669 + " old mTotalTime=" + mTotalTime);
1670 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001671 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001672 mCount = computeCurrentCountLocked();
1673 if (DEBUG && mType < 0) {
1674 Log.v(TAG, "plug #" + mType
1675 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 }
1677 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 /**
1680 * Writes a possibly null Timer to a Parcel.
1681 *
1682 * @param out the Parcel to be written to.
1683 * @param timer a Timer, or null.
1684 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001685 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 if (timer == null) {
1687 out.writeInt(0); // indicates null
1688 return;
1689 }
1690 out.writeInt(1); // indicates non-null
1691
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001692 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
1694
1695 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001696 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001697 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1698 if (which == STATS_SINCE_UNPLUGGED) {
1699 val -= mUnpluggedTime;
1700 } else if (which != STATS_SINCE_CHARGED) {
1701 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 }
1703
1704 return val;
1705 }
1706
1707 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001708 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001709 int val = computeCurrentCountLocked();
1710 if (which == STATS_SINCE_UNPLUGGED) {
1711 val -= mUnpluggedCount;
1712 } else if (which != STATS_SINCE_CHARGED) {
1713 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
1715
1716 return val;
1717 }
1718
Adam Lesinskie08af192015-03-25 16:42:59 -07001719 @Override
1720 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1721 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1722 return val - mTimeBeforeMark;
1723 }
1724
1725 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001726 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001727 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1729 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001730 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001732 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001734 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001735
1736
Joe Onoratoabded112016-02-08 16:49:39 -08001737 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001738 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1739 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001740 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001741 }
1742
Joe Onoratoabded112016-02-08 16:49:39 -08001743 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001744 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001745 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001746 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001747 mUnpluggedTime = mTotalTime;
1748 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001749 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001750 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001751
1752 // When reading the summary, we set the mark to be the latest information.
1753 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001754 }
1755 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001756
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001757 /**
1758 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1759 * method. The state of the timer according to its {@link TimeBase} will determine how much
1760 * of the value is recorded.
1761 *
1762 * If the value being recorded resets, {@link #endSample()} can be called in order to
1763 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1764 * between calls, the {@link #endSample()} is automatically called and the new value is
1765 * expected to increase monotonically from that point on.
1766 */
Joe Onoratoabded112016-02-08 16:49:39 -08001767 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001768
Evan Millarc64edde2009-04-18 12:26:32 -07001769 /**
1770 * The most recent reported count from /proc/wakelocks.
1771 */
1772 int mCurrentReportedCount;
1773
1774 /**
1775 * The reported count from /proc/wakelocks when unplug() was last
1776 * called.
1777 */
1778 int mUnpluggedReportedCount;
1779
1780 /**
1781 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001782 */
Evan Millarc64edde2009-04-18 12:26:32 -07001783 long mCurrentReportedTotalTime;
1784
1785
1786 /**
1787 * The reported total_time from /proc/wakelocks when unplug() was last
1788 * called.
1789 */
1790 long mUnpluggedReportedTotalTime;
1791
1792 /**
1793 * Whether we are currently in a discharge cycle.
1794 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001795 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001796
1797 /**
1798 * Whether we are currently recording reported values.
1799 */
1800 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001801
Evan Millarc64edde2009-04-18 12:26:32 -07001802 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001803 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001804 */
1805 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001806
Adam Lesinski98f0d462016-04-19 16:46:20 -07001807 @VisibleForTesting
1808 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001809 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001810 mCurrentReportedCount = in.readInt();
1811 mUnpluggedReportedCount = in.readInt();
1812 mCurrentReportedTotalTime = in.readLong();
1813 mUnpluggedReportedTotalTime = in.readLong();
1814 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001815 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001816 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001817
Adam Lesinski98f0d462016-04-19 16:46:20 -07001818 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001819 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001820 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001821 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001822 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001823 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001824
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001825 /**
1826 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1827 * be less than the values used for a previous invocation.
1828 */
1829 public void endSample() {
1830 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1831 mCount = computeCurrentCountLocked();
1832 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1833 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001834 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001835
Evan Millarc64edde2009-04-18 12:26:32 -07001836 public void setUpdateVersion(int version) {
1837 mUpdateVersion = version;
1838 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001839
Evan Millarc64edde2009-04-18 12:26:32 -07001840 public int getUpdateVersion() {
1841 return mUpdateVersion;
1842 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001843
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001844 /**
1845 * Updates the current recorded values. These are meant to be monotonically increasing
1846 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1847 *
1848 * If the values being recorded have been reset, the monotonically increasing requirement
1849 * will be broken. In this case, {@link #endSample()} is automatically called and
1850 * the total value of totalTime and count are recorded, starting a new monotonically
1851 * increasing sample.
1852 *
1853 * @param totalTime total time of sample in microseconds.
1854 * @param count total number of times the event being sampled occurred.
1855 */
1856 public void update(long totalTime, int count) {
1857 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001858 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001859 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001860 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001861 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001862
1863 mTrackingReportedValues = true;
1864
1865 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1866 endSample();
1867 }
1868
1869 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001870 mCurrentReportedCount = count;
1871 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001872
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001873 /**
1874 * Adds deltaTime and deltaCount to the current sample.
1875 *
1876 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1877 * @param deltaCount additional number of times the event being sampled occurred.
1878 */
1879 public void add(long deltaTime, int deltaCount) {
1880 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001881 }
1882
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001883 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001884 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
1885 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001886 if (mTrackingReportedValues) {
1887 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
1888 mUnpluggedReportedCount = mCurrentReportedCount;
1889 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001890 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07001891 }
1892
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001893 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001894 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1895 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1896 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07001897 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001898
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001899 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001900 public void logState(Printer pw, String prefix) {
1901 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001902 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07001903 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
1904 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
1905 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
1906 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001907
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001908 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001909 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001910 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001911 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
1912 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001913
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001914 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001915 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001916 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001917 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
1918 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001919
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001920 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001921 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1922 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001923 out.writeInt(mCurrentReportedCount);
1924 out.writeInt(mUnpluggedReportedCount);
1925 out.writeLong(mCurrentReportedTotalTime);
1926 out.writeLong(mUnpluggedReportedTotalTime);
1927 out.writeInt(mTrackingReportedValues ? 1 : 0);
1928 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001929
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001930 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001931 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001932 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001933 mTrackingReportedValues = false;
1934 mUnpluggedReportedTotalTime = 0;
1935 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001936 return true;
1937 }
Evan Millarc64edde2009-04-18 12:26:32 -07001938 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001939
Evan Millarc64edde2009-04-18 12:26:32 -07001940 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001941 * A timer that increments in batches. It does not run for durations, but just jumps
1942 * for a pre-determined amount.
1943 */
Joe Onoratoabded112016-02-08 16:49:39 -08001944 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001945 final Uid mUid;
1946
1947 /**
1948 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
1949 */
1950 long mLastAddedTime;
1951
1952 /**
1953 * The last duration that we added to the timer. This is in microseconds.
1954 */
1955 long mLastAddedDuration;
1956
1957 /**
1958 * Whether we are currently in a discharge cycle.
1959 */
1960 boolean mInDischarge;
1961
Joe Onoratoabded112016-02-08 16:49:39 -08001962 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
1963 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001964 mUid = uid;
1965 mLastAddedTime = in.readLong();
1966 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001967 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001968 }
1969
Joe Onoratoabded112016-02-08 16:49:39 -08001970 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
1971 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001972 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001973 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001974 }
1975
1976 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001977 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1978 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001979 out.writeLong(mLastAddedTime);
1980 out.writeLong(mLastAddedDuration);
1981 }
1982
1983 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001984 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001985 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001986 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001987 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001988 }
1989
1990 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001991 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001992 recomputeLastDuration(elapsedRealtime, false);
1993 mInDischarge = true;
1994 // If we are still within the last added duration, then re-added whatever remains.
1995 if (mLastAddedTime == elapsedRealtime) {
1996 mTotalTime += mLastAddedDuration;
1997 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001998 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001999 }
2000
2001 @Override
2002 public void logState(Printer pw, String prefix) {
2003 super.logState(pw, prefix);
2004 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
2005 + " mLastAddedDuration=" + mLastAddedDuration);
2006 }
2007
2008 private long computeOverage(long curTime) {
2009 if (mLastAddedTime > 0) {
2010 return mLastTime + mLastAddedDuration - curTime;
2011 }
2012 return 0;
2013 }
2014
2015 private void recomputeLastDuration(long curTime, boolean abort) {
2016 final long overage = computeOverage(curTime);
2017 if (overage > 0) {
2018 // Aborting before the duration ran out -- roll back the remaining
2019 // duration. Only do this if currently discharging; otherwise we didn't
2020 // actually add the time.
2021 if (mInDischarge) {
2022 mTotalTime -= overage;
2023 }
2024 if (abort) {
2025 mLastAddedTime = 0;
2026 } else {
2027 mLastAddedTime = curTime;
2028 mLastAddedDuration -= overage;
2029 }
2030 }
2031 }
2032
2033 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08002034 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002035 recomputeLastDuration(now, true);
2036 mLastAddedTime = now;
2037 mLastAddedDuration = durationMillis * 1000;
2038 if (mInDischarge) {
2039 mTotalTime += mLastAddedDuration;
2040 mCount++;
2041 }
2042 }
2043
2044 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002045 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002046 recomputeLastDuration(now, true);
2047 }
2048
2049 @Override
2050 protected int computeCurrentCountLocked() {
2051 return mCount;
2052 }
2053
2054 @Override
2055 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002056 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002057 if (overage > 0) {
2058 return mTotalTime = overage;
2059 }
2060 return mTotalTime;
2061 }
2062
2063 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002064 public boolean reset(boolean detachIfReset) {
2065 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002066 recomputeLastDuration(now, true);
2067 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002068 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002069 return !stillActive;
2070 }
2071 }
2072
Joe Onorato92fd23f2016-07-25 11:18:42 -07002073
2074 /**
2075 * A StopwatchTimer that also tracks the total and max individual
2076 * time spent active according to the given timebase. Whereas
2077 * StopwatchTimer apportions the time amongst all in the pool,
2078 * the total and max durations are not apportioned.
2079 */
2080 public static class DurationTimer extends StopwatchTimer {
2081 /**
2082 * The time (in ms) that the timer was last acquired or the time base
2083 * last (re-)started. Increasing the nesting depth does not reset this time.
2084 *
2085 * -1 if the timer is currently not running or the time base is not running.
2086 *
2087 * If written to a parcel, the start time is reset, as is mNesting in the base class
2088 * StopwatchTimer.
2089 */
2090 long mStartTimeMs = -1;
2091
2092 /**
Bookatz867c0d72017-03-07 18:23:42 -08002093 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002094 */
2095 long mMaxDurationMs;
2096
2097 /**
Bookatz867c0d72017-03-07 18:23:42 -08002098 * The time (in ms) that that the timer has been active since most recent
2099 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002100 */
2101 long mCurrentDurationMs;
2102
Bookatz867c0d72017-03-07 18:23:42 -08002103 /**
2104 * The total time (in ms) that that the timer has been active since most recent reset()
2105 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2106 * (but not including the present currentDuration) since reset. Not pooled.
2107 */
2108 long mTotalDurationMs;
2109
Joe Onorato92fd23f2016-07-25 11:18:42 -07002110 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2111 TimeBase timeBase, Parcel in) {
2112 super(clocks, uid, type, timerPool, timeBase, in);
2113 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002114 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002115 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002116 }
2117
2118 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2119 TimeBase timeBase) {
2120 super(clocks, uid, type, timerPool, timeBase);
2121 }
2122
2123 @Override
2124 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2125 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002126 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002127 out.writeLong(mTotalDurationMs);
2128 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002129 }
2130
2131 /**
2132 * Write the summary to the parcel.
2133 *
2134 * Since the time base is probably meaningless after we come back, reading
2135 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002136 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002137 */
2138 @Override
2139 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2140 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002141 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002142 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002143 }
2144
2145 /**
2146 * Read the summary parcel.
2147 *
2148 * Has the side effect of stopping the timer.
2149 */
2150 @Override
2151 public void readSummaryFromParcelLocked(Parcel in) {
2152 super.readSummaryFromParcelLocked(in);
2153 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002154 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002155 mStartTimeMs = -1;
2156 mCurrentDurationMs = 0;
2157 }
2158
2159 /**
2160 * The TimeBase time started (again).
2161 *
2162 * If the timer is also running, store the start time.
2163 */
2164 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2165 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2166 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002167 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002168 }
2169 }
2170
2171 /**
2172 * The TimeBase stopped running.
2173 *
2174 * If the timer is running, add the duration into mCurrentDurationMs.
2175 */
2176 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002177 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2178 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002179 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002180 // baseRealtimeUs has already been converted to the timebase's realtime.
2181 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002182 }
2183 mStartTimeMs = -1;
2184 }
2185
2186 @Override
2187 public void logState(Printer pw, String prefix) {
2188 super.logState(pw, prefix);
2189 }
2190
2191 @Override
2192 public void startRunningLocked(long elapsedRealtimeMs) {
2193 super.startRunningLocked(elapsedRealtimeMs);
2194 if (mNesting == 1 && mTimeBase.isRunning()) {
2195 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002196 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002197 }
2198 }
2199
2200 /**
2201 * Decrements the mNesting ref-count on this timer.
2202 *
2203 * If it actually stopped (mNesting went to 0), then possibly update
2204 * mMaxDuration if the current duration was the longest ever.
2205 */
2206 @Override
2207 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002208 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002209 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002210 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002211 if (durationMs > mMaxDurationMs) {
2212 mMaxDurationMs = durationMs;
2213 }
2214 mStartTimeMs = -1;
2215 mCurrentDurationMs = 0;
2216 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002217 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2218 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2219 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002220 }
2221
2222 @Override
2223 public boolean reset(boolean detachIfReset) {
2224 boolean result = super.reset(detachIfReset);
2225 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002226 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002227 mCurrentDurationMs = 0;
2228 if (mNesting > 0) {
2229 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2230 } else {
2231 mStartTimeMs = -1;
2232 }
2233 return result;
2234 }
2235
2236 /**
2237 * Returns the max duration that this timer has ever seen.
2238 *
2239 * Note that this time is NOT split between the timers in the timer group that
2240 * this timer is attached to. It is the TOTAL time.
2241 */
2242 @Override
2243 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2244 if (mNesting > 0) {
2245 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2246 if (durationMs > mMaxDurationMs) {
2247 return durationMs;
2248 }
2249 }
2250 return mMaxDurationMs;
2251 }
2252
2253 /**
2254 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002255 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002256 *
2257 * Note that this time is NOT split between the timers in the timer group that
2258 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002259 *
2260 * Note that if running timer is parceled and unparceled, this method will return
2261 * current duration value at the time of parceling even though timer may not be
2262 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002263 */
2264 @Override
2265 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2266 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002267 if (mNesting > 0 && mTimeBase.isRunning()) {
2268 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2269 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002270 }
2271 return durationMs;
2272 }
Bookatz867c0d72017-03-07 18:23:42 -08002273
2274 /**
2275 * Returns the total cumulative duration that this timer has been on since reset().
2276 * If mTimerPool == null, this should be the same
2277 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2278 *
2279 * Note that this time is NOT split between the timers in the timer group that
2280 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2281 * the result will not be equivalent to getTotalTimeLocked.
2282 */
2283 @Override
2284 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2285 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2286 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002287 }
2288
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002289 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002290 * State for keeping track of timing information.
2291 */
Joe Onoratoabded112016-02-08 16:49:39 -08002292 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002293 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002294 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002295
Evan Millarc64edde2009-04-18 12:26:32 -07002296 int mNesting;
2297
Evan Millarc64edde2009-04-18 12:26:32 -07002298 /**
2299 * The last time at which we updated the timer. If mNesting is > 0,
2300 * subtract this from the current battery time to find the amount of
2301 * time we have been running since we last computed an update.
2302 */
2303 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002304
Evan Millarc64edde2009-04-18 12:26:32 -07002305 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002306 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002307 * was actually held for an interesting duration. If time base was not running when timer
2308 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002309 */
Bookatzceebafe2017-04-06 11:59:13 -07002310 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002311
Amith Yamasanif37447b2009-10-08 18:28:01 -07002312 long mTimeout;
2313
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002314 /**
2315 * For partial wake locks, keep track of whether we are in the list
2316 * to consume CPU cycles.
2317 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002318 @VisibleForTesting
2319 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002320
Joe Onoratoabded112016-02-08 16:49:39 -08002321 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002322 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002323 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002324 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002325 mTimerPool = timerPool;
2326 mUpdateTime = in.readLong();
2327 }
2328
Joe Onoratoabded112016-02-08 16:49:39 -08002329 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002330 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002331 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002332 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002333 mTimerPool = timerPool;
2334 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002335
Joe Onoratoabded112016-02-08 16:49:39 -08002336 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002337 mTimeout = timeout;
2338 }
2339
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002340 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2341 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002342 out.writeLong(mUpdateTime);
2343 }
2344
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002345 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002346 if (mNesting > 0) {
2347 if (DEBUG && mType < 0) {
2348 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2349 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002350 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2351 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002352 if (DEBUG && mType < 0) {
2353 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2354 }
2355 }
2356 }
2357
2358 public void logState(Printer pw, String prefix) {
2359 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002360 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 + " mAcquireTime=" + mAcquireTime);
2362 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002363
Joe Onoratoabded112016-02-08 16:49:39 -08002364 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002366 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002367 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 if (mTimerPool != null) {
2369 // Accumulate time to all currently active timers before adding
2370 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002371 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 // Add this timer to the active pool
2373 mTimerPool.add(this);
2374 }
Bookatzceebafe2017-04-06 11:59:13 -07002375 if (mTimeBase.isRunning()) {
2376 // Increment the count
2377 mCount++;
2378 mAcquireTime = mTotalTime;
2379 } else {
2380 mAcquireTime = -1;
2381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 if (DEBUG && mType < 0) {
2383 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2384 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2385 + " mAcquireTime=" + mAcquireTime);
2386 }
2387 }
2388 }
2389
Joe Onoratoabded112016-02-08 16:49:39 -08002390 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002391 return mNesting > 0;
2392 }
2393
Joe Onoratoabded112016-02-08 16:49:39 -08002394 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 // Ignore attempt to stop a timer that isn't running
2396 if (mNesting == 0) {
2397 return;
2398 }
2399 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002400 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 if (mTimerPool != null) {
2402 // Accumulate time to all active counters, scaled by the total
2403 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002404 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 // Remove this timer from the active pool
2406 mTimerPool.remove(this);
2407 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 mNesting = 1;
2409 mTotalTime = computeRunTimeLocked(batteryRealtime);
2410 mNesting = 0;
2411 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 if (DEBUG && mType < 0) {
2414 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2415 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2416 + " mAcquireTime=" + mAcquireTime);
2417 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002418
Bookatzceebafe2017-04-06 11:59:13 -07002419 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 // If there was no change in the time, then discard this
2421 // count. A somewhat cheezy strategy, but hey.
2422 mCount--;
2423 }
2424 }
2425 }
2426
Joe Onoratoabded112016-02-08 16:49:39 -08002427 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002428 if (mNesting > 0) {
2429 mNesting = 1;
2430 stopRunningLocked(elapsedRealtimeMs);
2431 }
2432 }
2433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 // Update the total time for all other running Timers with the same type as this Timer
2435 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002436 private static long refreshTimersLocked(long batteryRealtime,
2437 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002438 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 final int N = pool.size();
2440 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002441 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 long heldTime = batteryRealtime - t.mUpdateTime;
2443 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002444 final long myTime = heldTime / N;
2445 if (t == self) {
2446 selfTime = myTime;
2447 }
2448 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 }
2450 t.mUpdateTime = batteryRealtime;
2451 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002452 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 }
2454
Evan Millarc64edde2009-04-18 12:26:32 -07002455 @Override
2456 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002457 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2458 curBatteryRealtime = mUpdateTime + mTimeout;
2459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 return mTotalTime + (mNesting > 0
2461 ? (curBatteryRealtime - mUpdateTime)
2462 / (mTimerPool != null ? mTimerPool.size() : 1)
2463 : 0);
2464 }
2465
Evan Millarc64edde2009-04-18 12:26:32 -07002466 @Override
2467 protected int computeCurrentCountLocked() {
2468 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 }
2470
Adam Lesinskie08af192015-03-25 16:42:59 -07002471 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002472 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002473 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002474 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002475 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002476 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002477 }
Bookatzceebafe2017-04-06 11:59:13 -07002478 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002479 return canDetach;
2480 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002481
Adam Lesinskie08af192015-03-25 16:42:59 -07002482 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002483 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002484 super.detach();
2485 if (mTimerPool != null) {
2486 mTimerPool.remove(this);
2487 }
2488 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002489
Adam Lesinskie08af192015-03-25 16:42:59 -07002490 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002491 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002492 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 mNesting = 0;
2494 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002495
2496 /**
2497 * Set the mark so that we can query later for the total time the timer has
2498 * accumulated since this point. The timer can be running or not.
2499 *
2500 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2501 */
2502 public void setMark(long elapsedRealtimeMs) {
2503 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2504 if (mNesting > 0) {
2505 // We are running.
2506 if (mTimerPool != null) {
2507 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2508 } else {
2509 mTotalTime += batteryRealtime - mUpdateTime;
2510 mUpdateTime = batteryRealtime;
2511 }
2512 }
2513 mTimeBeforeMark = mTotalTime;
2514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002516
Bookatz867c0d72017-03-07 18:23:42 -08002517 /**
2518 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2519 * TimeBase is effectively a subset of the other.
2520 */
Bookatzaa4594a2017-03-24 12:39:56 -07002521 public static class DualTimer extends DurationTimer {
2522 // This class both is a DurationTimer and also holds a second DurationTimer.
2523 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2524 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2525 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002526 // mSubTimer typically tracks only part of the total time, such as background time, as
2527 // determined by a subTimeBase. It is NOT pooled.
2528 private final DurationTimer mSubTimer;
2529
2530 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002531 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2532 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002533 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002534 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002535 */
2536 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2537 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002538 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002539 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2540 }
2541
2542 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002543 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2544 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002545 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002546 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002547 */
2548 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2549 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002550 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002551 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2552 }
2553
Bookatz867c0d72017-03-07 18:23:42 -08002554 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002555 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002556 public DurationTimer getSubTimer() {
2557 return mSubTimer;
2558 }
2559
Bookatzaa4594a2017-03-24 12:39:56 -07002560 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002561 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002562 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002563 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2564 }
2565
Bookatzaa4594a2017-03-24 12:39:56 -07002566 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002567 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002568 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002569 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2570 }
2571
Bookatzaa4594a2017-03-24 12:39:56 -07002572 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002573 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002574 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002575 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2576 }
2577
Bookatzaa4594a2017-03-24 12:39:56 -07002578 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002579 public boolean reset(boolean detachIfReset) {
2580 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002581 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2582 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002583 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002584 return !active;
2585 }
2586
Bookatzaa4594a2017-03-24 12:39:56 -07002587 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002588 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002589 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002590 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002591 }
2592
Bookatzaa4594a2017-03-24 12:39:56 -07002593 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002594 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002595 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002596 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2597 }
2598
Bookatzaa4594a2017-03-24 12:39:56 -07002599 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002600 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002601 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002602 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2603 }
2604
Bookatzaa4594a2017-03-24 12:39:56 -07002605 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002606 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002607 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002608 mSubTimer.readSummaryFromParcelLocked(in);
2609 }
2610 }
2611
2612
Dianne Hackbornd953c532014-08-16 18:17:38 -07002613 public abstract class OverflowArrayMap<T> {
2614 private static final String OVERFLOW_NAME = "*overflow*";
2615
Dianne Hackborn657153b2016-07-29 14:54:14 -07002616 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002617 final ArrayMap<String, T> mMap = new ArrayMap<>();
2618 T mCurOverflow;
2619 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002620 long mLastOverflowTime;
2621 long mLastOverflowFinishTime;
2622 long mLastClearTime;
2623 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002624
Dianne Hackborn657153b2016-07-29 14:54:14 -07002625 public OverflowArrayMap(int uid) {
2626 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002627 }
2628
2629 public ArrayMap<String, T> getMap() {
2630 return mMap;
2631 }
2632
2633 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002634 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002635 mMap.clear();
2636 mCurOverflow = null;
2637 mActiveOverflow = null;
2638 }
2639
2640 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002641 if (name == null) {
2642 name = "";
2643 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002644 mMap.put(name, obj);
2645 if (OVERFLOW_NAME.equals(name)) {
2646 mCurOverflow = obj;
2647 }
2648 }
2649
2650 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002651 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002652 if (mActiveOverflow != null) {
2653 if (mActiveOverflow.size() == 0) {
2654 mActiveOverflow = null;
2655 }
2656 }
2657 if (mActiveOverflow == null) {
2658 // There is no currently active overflow, so we should no longer have
2659 // an overflow entry.
2660 if (mMap.containsKey(OVERFLOW_NAME)) {
2661 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2662 + mMap.get(OVERFLOW_NAME));
2663 mMap.remove(OVERFLOW_NAME);
2664 }
2665 mCurOverflow = null;
2666 } else {
2667 // There is currently active overflow, so we should still have an overflow entry.
2668 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2669 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2670 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2671 }
2672 }
2673 }
2674
2675 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002676 if (name == null) {
2677 name = "";
2678 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002679 T obj = mMap.get(name);
2680 if (obj != null) {
2681 return obj;
2682 }
2683
2684 // No object exists for the given name, but do we currently have it
2685 // running as part of the overflow?
2686 if (mActiveOverflow != null) {
2687 MutableInt over = mActiveOverflow.get(name);
2688 if (over != null) {
2689 // We are already actively counting this name in the overflow object.
2690 obj = mCurOverflow;
2691 if (obj == null) {
2692 // Shouldn't be here, but we'll try to recover.
2693 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2694 obj = mCurOverflow = instantiateObject();
2695 mMap.put(OVERFLOW_NAME, obj);
2696 }
2697 over.value++;
2698 return obj;
2699 }
2700 }
2701
2702 // No object exists for given name nor in the overflow; we need to make
2703 // a new one.
2704 final int N = mMap.size();
2705 if (N >= MAX_WAKELOCKS_PER_UID) {
2706 // Went over the limit on number of objects to track; this one goes
2707 // in to the overflow.
2708 obj = mCurOverflow;
2709 if (obj == null) {
2710 // Need to start overflow now...
2711 obj = mCurOverflow = instantiateObject();
2712 mMap.put(OVERFLOW_NAME, obj);
2713 }
2714 if (mActiveOverflow == null) {
2715 mActiveOverflow = new ArrayMap<>();
2716 }
2717 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002718 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002719 return obj;
2720 }
2721
2722 // Normal case where we just need to make a new object.
2723 obj = instantiateObject();
2724 mMap.put(name, obj);
2725 return obj;
2726 }
2727
2728 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002729 if (name == null) {
2730 name = "";
2731 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002732 T obj = mMap.get(name);
2733 if (obj != null) {
2734 return obj;
2735 }
2736
2737 // No object exists for the given name, but do we currently have it
2738 // running as part of the overflow?
2739 if (mActiveOverflow != null) {
2740 MutableInt over = mActiveOverflow.get(name);
2741 if (over != null) {
2742 // We are already actively counting this name in the overflow object.
2743 obj = mCurOverflow;
2744 if (obj != null) {
2745 over.value--;
2746 if (over.value <= 0) {
2747 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002748 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002749 }
2750 return obj;
2751 }
2752 }
2753 }
2754
2755 // Huh, they are stopping an active operation but we can't find one!
2756 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002757 StringBuilder sb = new StringBuilder();
2758 sb.append("Unable to find object for ");
2759 sb.append(name);
2760 sb.append(" in uid ");
2761 sb.append(mUid);
2762 sb.append(" mapsize=");
2763 sb.append(mMap.size());
2764 sb.append(" activeoverflow=");
2765 sb.append(mActiveOverflow);
2766 sb.append(" curoverflow=");
2767 sb.append(mCurOverflow);
2768 long now = SystemClock.elapsedRealtime();
2769 if (mLastOverflowTime != 0) {
2770 sb.append(" lastOverflowTime=");
2771 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2772 }
2773 if (mLastOverflowFinishTime != 0) {
2774 sb.append(" lastOverflowFinishTime=");
2775 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2776 }
2777 if (mLastClearTime != 0) {
2778 sb.append(" lastClearTime=");
2779 TimeUtils.formatDuration(mLastClearTime-now, sb);
2780 }
2781 if (mLastCleanupTime != 0) {
2782 sb.append(" lastCleanupTime=");
2783 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2784 }
2785 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002786 return null;
2787 }
2788
2789 public abstract T instantiateObject();
2790 }
2791
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002792 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2793 implements Parcelable {
2794 private final LongSamplingCounter mIdleTimeMillis;
Siddharth Rayb50a6842017-12-14 15:15:28 -08002795 private final LongSamplingCounter mScanTimeMillis;
Siddharth Rayed754702018-02-15 12:44:37 -08002796 private final LongSamplingCounter mSleepTimeMillis;
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);
Siddharth Rayed754702018-02-15 12:44:37 -08002804 mSleepTimeMillis = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002805 mRxTimeMillis = new LongSamplingCounter(timeBase);
2806 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2807 for (int i = 0; i < numTxStates; i++) {
2808 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2809 }
2810 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2811 }
2812
2813 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2814 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002815 mScanTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayed754702018-02-15 12:44:37 -08002816 mSleepTimeMillis = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002817 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2818 final int recordedTxStates = in.readInt();
2819 if (recordedTxStates != numTxStates) {
2820 throw new ParcelFormatException("inconsistent tx state lengths");
2821 }
2822
2823 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2824 for (int i = 0; i < numTxStates; i++) {
2825 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2826 }
2827 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2828 }
2829
2830 public void readSummaryFromParcel(Parcel in) {
2831 mIdleTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002832 mScanTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayed754702018-02-15 12:44:37 -08002833 mSleepTimeMillis.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002834 mRxTimeMillis.readSummaryFromParcelLocked(in);
2835 final int recordedTxStates = in.readInt();
2836 if (recordedTxStates != mTxTimeMillis.length) {
2837 throw new ParcelFormatException("inconsistent tx state lengths");
2838 }
2839 for (LongSamplingCounter counter : mTxTimeMillis) {
2840 counter.readSummaryFromParcelLocked(in);
2841 }
2842 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2843 }
2844
2845 @Override
2846 public int describeContents() {
2847 return 0;
2848 }
2849
2850 public void writeSummaryToParcel(Parcel dest) {
2851 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002852 mScanTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002853 mSleepTimeMillis.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002854 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2855 dest.writeInt(mTxTimeMillis.length);
2856 for (LongSamplingCounter counter : mTxTimeMillis) {
2857 counter.writeSummaryFromParcelLocked(dest);
2858 }
2859 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2860 }
2861
2862 @Override
2863 public void writeToParcel(Parcel dest, int flags) {
2864 mIdleTimeMillis.writeToParcel(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002865 mScanTimeMillis.writeToParcel(dest);
Siddharth Rayed754702018-02-15 12:44:37 -08002866 mSleepTimeMillis.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002867 mRxTimeMillis.writeToParcel(dest);
2868 dest.writeInt(mTxTimeMillis.length);
2869 for (LongSamplingCounter counter : mTxTimeMillis) {
2870 counter.writeToParcel(dest);
2871 }
2872 mPowerDrainMaMs.writeToParcel(dest);
2873 }
2874
2875 public void reset(boolean detachIfReset) {
2876 mIdleTimeMillis.reset(detachIfReset);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002877 mScanTimeMillis.reset(detachIfReset);
Siddharth Rayed754702018-02-15 12:44:37 -08002878 mSleepTimeMillis.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002879 mRxTimeMillis.reset(detachIfReset);
2880 for (LongSamplingCounter counter : mTxTimeMillis) {
2881 counter.reset(detachIfReset);
2882 }
2883 mPowerDrainMaMs.reset(detachIfReset);
2884 }
2885
2886 public void detach() {
2887 mIdleTimeMillis.detach();
Siddharth Rayb50a6842017-12-14 15:15:28 -08002888 mScanTimeMillis.detach();
Siddharth Rayed754702018-02-15 12:44:37 -08002889 mSleepTimeMillis.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002890 mRxTimeMillis.detach();
2891 for (LongSamplingCounter counter : mTxTimeMillis) {
2892 counter.detach();
2893 }
2894 mPowerDrainMaMs.detach();
2895 }
2896
2897 /**
2898 * @return a LongSamplingCounter, measuring time spent in the idle state in
2899 * milliseconds.
2900 */
2901 @Override
2902 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07002903 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002904 }
2905
2906 /**
Siddharth Rayb50a6842017-12-14 15:15:28 -08002907 * @return a LongSamplingCounter, measuring time spent in the scan state in
2908 * milliseconds.
2909 */
2910 @Override
2911 public LongSamplingCounter getScanTimeCounter() {
2912 return mScanTimeMillis;
2913 }
2914
2915 /**
Siddharth Rayed754702018-02-15 12:44:37 -08002916 * @return a LongSamplingCounter, measuring time spent in the sleep state in
2917 * milliseconds.
2918 */
2919 @Override
2920 public LongSamplingCounter getSleepTimeCounter() {
2921 return mSleepTimeMillis;
2922 }
2923
2924 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002925 * @return a LongSamplingCounter, measuring time spent in the receive state in
2926 * milliseconds.
2927 */
2928 @Override
2929 public LongSamplingCounter getRxTimeCounter() {
2930 return mRxTimeMillis;
2931 }
2932
2933 /**
2934 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
2935 * milliseconds.
2936 */
2937 @Override
2938 public LongSamplingCounter[] getTxTimeCounters() {
2939 return mTxTimeMillis;
2940 }
2941
2942 /**
2943 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
2944 */
2945 @Override
2946 public LongSamplingCounter getPowerCounter() {
2947 return mPowerDrainMaMs;
2948 }
2949 }
2950
Bookatz50df7112017-08-04 14:53:26 -07002951 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
2952 public SamplingTimer getRpmTimerLocked(String name) {
2953 SamplingTimer rpmt = mRpmStats.get(name);
2954 if (rpmt == null) {
2955 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2956 mRpmStats.put(name, rpmt);
2957 }
2958 return rpmt;
2959 }
2960
2961 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
2962 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
2963 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
2964 if (rpmt == null) {
2965 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
2966 mScreenOffRpmStats.put(name, rpmt);
2967 }
2968 return rpmt;
2969 }
2970
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002971 /*
2972 * Get the wakeup reason counter, and create a new one if one
2973 * doesn't already exist.
2974 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002975 public SamplingTimer getWakeupReasonTimerLocked(String name) {
2976 SamplingTimer timer = mWakeupReasonStats.get(name);
2977 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002978 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002979 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002980 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002981 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002982 }
2983
Evan Millarc64edde2009-04-18 12:26:32 -07002984 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002985 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07002986 * doesn't already exist.
2987 */
2988 public SamplingTimer getKernelWakelockTimerLocked(String name) {
2989 SamplingTimer kwlt = mKernelWakelockStats.get(name);
2990 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002991 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07002992 mKernelWakelockStats.put(name, kwlt);
2993 }
2994 return kwlt;
2995 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07002996
James Carr3a226052016-07-01 14:49:52 -07002997 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
2998 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
2999 if (kmt == null) {
3000 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3001 mKernelMemoryStats.put(bucket, kmt);
3002 }
3003 return kmt;
3004 }
3005
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003006 private int writeHistoryTag(HistoryTag tag) {
3007 Integer idxObj = mHistoryTagPool.get(tag);
3008 int idx;
3009 if (idxObj != null) {
3010 idx = idxObj;
3011 } else {
3012 idx = mNextHistoryTagIdx;
3013 HistoryTag key = new HistoryTag();
3014 key.setTo(tag);
3015 tag.poolIdx = idx;
3016 mHistoryTagPool.put(key, idx);
3017 mNextHistoryTagIdx++;
3018 mNumHistoryTagChars += key.string.length() + 1;
3019 }
3020 return idx;
3021 }
3022
3023 private void readHistoryTag(int index, HistoryTag tag) {
3024 tag.string = mReadHistoryStrings[index];
3025 tag.uid = mReadHistoryUids[index];
3026 tag.poolIdx = index;
3027 }
3028
Adam Lesinski926969b2016-04-28 17:31:12 -07003029 /*
3030 The history delta format uses flags to denote further data in subsequent ints in the parcel.
3031
3032 There is always the first token, which may contain the delta time, or an indicator of
3033 the length of the time (int or long) following this token.
3034
3035 First token: always present,
3036 31 23 15 7 0
3037 â–ˆ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â–ˆ
3038
3039 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
3040 follows containing the time, and 0x7ffff indicates a long immediately follows with the
3041 delta time.
3042 A: battery level changed and an int follows with battery data.
3043 B: state changed and an int follows with state change data.
3044 C: state2 has changed and an int follows with state2 change data.
3045 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
3046 E: event data has changed and an event struct follows.
3047 F: battery charge in coulombs has changed and an int with the charge follows.
3048 G: state flag denoting that the mobile radio was active.
3049 H: state flag denoting that the wifi radio was active.
3050 I: state flag denoting that a wifi scan occurred.
3051 J: state flag denoting that a wifi full lock was held.
3052 K: state flag denoting that the gps was on.
3053 L: state flag denoting that a wakelock was held.
3054 M: state flag denoting that the cpu was running.
3055
3056 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3057 with the time delta.
3058
3059 Battery level int: if A in the first token is set,
3060 31 23 15 7 0
3061 â–ˆ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â–ˆ
3062
3063 D: indicates that extra history details follow.
3064 V: the battery voltage.
3065 T: the battery temperature.
3066 L: the battery level (out of 100).
3067
3068 State change int: if B in the first token is set,
3069 31 23 15 7 0
3070 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3071
3072 A: wifi multicast was on.
3073 B: battery was plugged in.
3074 C: screen was on.
3075 D: phone was scanning for signal.
3076 E: audio was on.
3077 F: a sensor was active.
3078
3079 State2 change int: if C in the first token is set,
3080 31 23 15 7 0
3081 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3082
3083 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3084 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3085 C: a bluetooth scan was active.
3086 D: the camera was active.
3087 E: bluetooth was on.
3088 F: a phone call was active.
3089 G: the device was charging.
3090 H: 2 bits indicating the device-idle (doze) state: off, light, full
3091 I: the flashlight was on.
3092 J: wifi was on.
3093 K: wifi was running.
3094 L: video was playing.
3095 M: power save mode was on.
3096
3097 Wakelock/wakereason struct: if D in the first token is set,
3098 TODO(adamlesinski): describe wakelock/wakereason struct.
3099
3100 Event struct: if E in the first token is set,
3101 TODO(adamlesinski): describe the event struct.
3102
3103 History step details struct: if D in the battery level int is set,
3104 TODO(adamlesinski): describe the history step details struct.
3105
3106 Battery charge int: if F in the first token is set, an int representing the battery charge
3107 in coulombs follows.
3108 */
3109
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003110 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003111 static final int DELTA_TIME_MASK = 0x7ffff;
3112 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3113 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3114 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003115 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003116 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003117 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003118 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003119 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003120 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003121 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003122 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003123 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003124 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003125 // Flag in delta int: contains the battery charge count in uAh.
3126 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003127 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003128 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003129
3130 // These are the pieces of battery state that are packed in to the upper bits of
3131 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003132 // in STATE_BATTERY_MASK.
3133 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003134 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3135 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3136 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3137 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3138 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3139 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003140
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003141 // We use the low bit of the battery state int to indicate that we have full details
3142 // from a battery level change.
3143 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3144
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003145 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003146 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003147 dest.writeInt(DELTA_TIME_ABS);
3148 cur.writeToParcel(dest, 0);
3149 return;
3150 }
3151
3152 final long deltaTime = cur.time - last.time;
3153 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3154 final int lastStateInt = buildStateInt(last);
3155
3156 int deltaTimeToken;
3157 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3158 deltaTimeToken = DELTA_TIME_LONG;
3159 } else if (deltaTime >= DELTA_TIME_ABS) {
3160 deltaTimeToken = DELTA_TIME_INT;
3161 } else {
3162 deltaTimeToken = (int)deltaTime;
3163 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003164 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003165 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3166 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3167 final boolean computeStepDetails = includeStepDetails != 0
3168 || mLastHistoryStepDetails == null;
3169 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003170 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3171 if (batteryLevelIntChanged) {
3172 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3173 }
3174 final int stateInt = buildStateInt(cur);
3175 final boolean stateIntChanged = stateInt != lastStateInt;
3176 if (stateIntChanged) {
3177 firstToken |= DELTA_STATE_FLAG;
3178 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003179 final boolean state2IntChanged = cur.states2 != last.states2;
3180 if (state2IntChanged) {
3181 firstToken |= DELTA_STATE2_FLAG;
3182 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003183 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003184 firstToken |= DELTA_WAKELOCK_FLAG;
3185 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003186 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3187 firstToken |= DELTA_EVENT_FLAG;
3188 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003189
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003190 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3191 if (batteryChargeChanged) {
3192 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003193 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003194 dest.writeInt(firstToken);
3195 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3196 + " deltaTime=" + deltaTime);
3197
3198 if (deltaTimeToken >= DELTA_TIME_INT) {
3199 if (deltaTimeToken == DELTA_TIME_INT) {
3200 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3201 dest.writeInt((int)deltaTime);
3202 } else {
3203 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3204 dest.writeLong(deltaTime);
3205 }
3206 }
3207 if (batteryLevelIntChanged) {
3208 dest.writeInt(batteryLevelInt);
3209 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3210 + Integer.toHexString(batteryLevelInt)
3211 + " batteryLevel=" + cur.batteryLevel
3212 + " batteryTemp=" + cur.batteryTemperature
3213 + " batteryVolt=" + (int)cur.batteryVoltage);
3214 }
3215 if (stateIntChanged) {
3216 dest.writeInt(stateInt);
3217 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3218 + Integer.toHexString(stateInt)
3219 + " batteryStatus=" + cur.batteryStatus
3220 + " batteryHealth=" + cur.batteryHealth
3221 + " batteryPlugType=" + cur.batteryPlugType
3222 + " states=0x" + Integer.toHexString(cur.states));
3223 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003224 if (state2IntChanged) {
3225 dest.writeInt(cur.states2);
3226 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3227 + Integer.toHexString(cur.states2));
3228 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003229 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3230 int wakeLockIndex;
3231 int wakeReasonIndex;
3232 if (cur.wakelockTag != null) {
3233 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3234 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3235 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3236 } else {
3237 wakeLockIndex = 0xffff;
3238 }
3239 if (cur.wakeReasonTag != null) {
3240 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3241 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3242 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3243 } else {
3244 wakeReasonIndex = 0xffff;
3245 }
3246 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003247 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003248 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003249 int index = writeHistoryTag(cur.eventTag);
3250 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003251 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003252 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3253 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3254 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003255 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003256 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003257 if (mPlatformIdleStateCallback != null) {
3258 mCurHistoryStepDetails.statPlatformIdleState =
3259 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3260 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3261 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003262
3263 mCurHistoryStepDetails.statSubsystemPowerState =
3264 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3265 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3266 mCurHistoryStepDetails.statSubsystemPowerState);
3267
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003268 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003269 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3270 if (includeStepDetails != 0) {
3271 mCurHistoryStepDetails.writeToParcel(dest);
3272 }
3273 cur.stepDetails = mCurHistoryStepDetails;
3274 mLastHistoryStepDetails = mCurHistoryStepDetails;
3275 } else {
3276 cur.stepDetails = null;
3277 }
3278 if (mLastHistoryStepLevel < cur.batteryLevel) {
3279 mLastHistoryStepDetails = null;
3280 }
3281 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003282
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003283 if (batteryChargeChanged) {
3284 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3285 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003286 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003287 }
3288
3289 private int buildBatteryLevelInt(HistoryItem h) {
3290 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003291 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3292 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3293 }
3294
3295 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3296 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3297 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3298 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003299 }
3300
3301 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003302 int plugType = 0;
3303 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3304 plugType = 1;
3305 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3306 plugType = 2;
3307 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3308 plugType = 3;
3309 }
3310 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3311 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3312 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003313 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003314 }
3315
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003316 private void computeHistoryStepDetails(final HistoryStepDetails out,
3317 final HistoryStepDetails last) {
3318 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3319
3320 // Perform a CPU update right after we do this collection, so we have started
3321 // collecting good data for the next step.
3322 requestImmediateCpuUpdate();
3323
3324 if (last == null) {
3325 // We are not generating a delta, so all we need to do is reset the stats
3326 // we will later be doing a delta from.
3327 final int NU = mUidStats.size();
3328 for (int i=0; i<NU; i++) {
3329 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3330 uid.mLastStepUserTime = uid.mCurStepUserTime;
3331 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3332 }
3333 mLastStepCpuUserTime = mCurStepCpuUserTime;
3334 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3335 mLastStepStatUserTime = mCurStepStatUserTime;
3336 mLastStepStatSystemTime = mCurStepStatSystemTime;
3337 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3338 mLastStepStatIrqTime = mCurStepStatIrqTime;
3339 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3340 mLastStepStatIdleTime = mCurStepStatIdleTime;
3341 tmp.clear();
3342 return;
3343 }
3344 if (DEBUG) {
3345 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3346 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3347 + " irq=" + mLastStepStatIrqTime + " sirq="
3348 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3349 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3350 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3351 + " irq=" + mCurStepStatIrqTime + " sirq="
3352 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3353 }
3354 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3355 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3356 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3357 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3358 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3359 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3360 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3361 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3362 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3363 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3364 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3365 final int NU = mUidStats.size();
3366 for (int i=0; i<NU; i++) {
3367 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3368 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3369 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3370 final int totalTime = totalUTime + totalSTime;
3371 uid.mLastStepUserTime = uid.mCurStepUserTime;
3372 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3373 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3374 continue;
3375 }
3376 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3377 out.appCpuUid3 = uid.mUid;
3378 out.appCpuUTime3 = totalUTime;
3379 out.appCpuSTime3 = totalSTime;
3380 } else {
3381 out.appCpuUid3 = out.appCpuUid2;
3382 out.appCpuUTime3 = out.appCpuUTime2;
3383 out.appCpuSTime3 = out.appCpuSTime2;
3384 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3385 out.appCpuUid2 = uid.mUid;
3386 out.appCpuUTime2 = totalUTime;
3387 out.appCpuSTime2 = totalSTime;
3388 } else {
3389 out.appCpuUid2 = out.appCpuUid1;
3390 out.appCpuUTime2 = out.appCpuUTime1;
3391 out.appCpuSTime2 = out.appCpuSTime1;
3392 out.appCpuUid1 = uid.mUid;
3393 out.appCpuUTime1 = totalUTime;
3394 out.appCpuSTime1 = totalSTime;
3395 }
3396 }
3397 }
3398 mLastStepCpuUserTime = mCurStepCpuUserTime;
3399 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3400 mLastStepStatUserTime = mCurStepStatUserTime;
3401 mLastStepStatSystemTime = mCurStepStatSystemTime;
3402 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3403 mLastStepStatIrqTime = mCurStepStatIrqTime;
3404 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3405 mLastStepStatIdleTime = mCurStepStatIdleTime;
3406 }
3407
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003408 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3409 int firstToken = src.readInt();
3410 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003411 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003412 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003413 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3414 + " deltaTimeToken=" + deltaTimeToken);
3415
3416 if (deltaTimeToken < DELTA_TIME_ABS) {
3417 cur.time += deltaTimeToken;
3418 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3419 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003420 cur.numReadInts += 2;
3421 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003422 cur.readFromParcel(src);
3423 return;
3424 } else if (deltaTimeToken == DELTA_TIME_INT) {
3425 int delta = src.readInt();
3426 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003427 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003428 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3429 } else {
3430 long delta = src.readLong();
3431 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3432 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003433 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003434 }
3435
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003436 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003437 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003438 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003439 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003440 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003441 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3442 + Integer.toHexString(batteryLevelInt)
3443 + " batteryLevel=" + cur.batteryLevel
3444 + " batteryTemp=" + cur.batteryTemperature
3445 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003446 } else {
3447 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003448 }
3449
3450 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3451 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003452 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003453 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3454 & STATE_BATTERY_STATUS_MASK);
3455 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3456 & STATE_BATTERY_HEALTH_MASK);
3457 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3458 & STATE_BATTERY_PLUG_MASK);
3459 switch (cur.batteryPlugType) {
3460 case 1:
3461 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3462 break;
3463 case 2:
3464 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3465 break;
3466 case 3:
3467 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3468 break;
3469 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003470 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003471 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3472 + Integer.toHexString(stateInt)
3473 + " batteryStatus=" + cur.batteryStatus
3474 + " batteryHealth=" + cur.batteryHealth
3475 + " batteryPlugType=" + cur.batteryPlugType
3476 + " states=0x" + Integer.toHexString(cur.states));
3477 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003478 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003479 }
3480
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003481 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3482 cur.states2 = src.readInt();
3483 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3484 + Integer.toHexString(cur.states2));
3485 }
3486
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003487 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003488 int indexes = src.readInt();
3489 int wakeLockIndex = indexes&0xffff;
3490 int wakeReasonIndex = (indexes>>16)&0xffff;
3491 if (wakeLockIndex != 0xffff) {
3492 cur.wakelockTag = cur.localWakelockTag;
3493 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3494 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3495 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3496 } else {
3497 cur.wakelockTag = null;
3498 }
3499 if (wakeReasonIndex != 0xffff) {
3500 cur.wakeReasonTag = cur.localWakeReasonTag;
3501 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3502 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3503 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3504 } else {
3505 cur.wakeReasonTag = null;
3506 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003507 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003508 } else {
3509 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003510 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003511 }
3512
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003513 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003514 cur.eventTag = cur.localEventTag;
3515 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003516 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003517 final int index = ((codeAndIndex>>16)&0xffff);
3518 readHistoryTag(index, cur.eventTag);
3519 cur.numReadInts += 1;
3520 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3521 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3522 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003523 } else {
3524 cur.eventCode = HistoryItem.EVENT_NONE;
3525 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003526
3527 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3528 cur.stepDetails = mReadHistoryStepDetails;
3529 cur.stepDetails.readFromParcel(src);
3530 } else {
3531 cur.stepDetails = null;
3532 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003533
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003534 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3535 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003536 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003537 }
3538
Dianne Hackbornfc064132014-06-02 12:42:12 -07003539 @Override
3540 public void commitCurrentHistoryBatchLocked() {
3541 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3542 }
3543
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003544 void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003545 if (!mHaveBatteryLevel || !mRecordingHistory) {
3546 return;
3547 }
3548
Dianne Hackborn40c87252014-03-19 16:55:40 -07003549 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003550 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3551 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003552 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003553 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003554 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3555 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003556 + Integer.toHexString(lastDiffStates) + " diff2="
3557 + Integer.toHexString(diffStates2) + " lastDiff2="
3558 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003559 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003560 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003561 && (diffStates2&lastDiffStates2) == 0
3562 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3563 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003564 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003565 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003566 || cur.eventCode == HistoryItem.EVENT_NONE)
3567 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3568 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3569 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3570 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3571 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3572 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003573 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003574 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003575 // as long as no bit has changed both between now and the last entry, as
3576 // well as the last entry and the one before it (so we capture any toggles).
3577 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003578 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3579 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3580 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003581 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003582 // If the last written history had a wakelock tag, we need to retain it.
3583 // Note that the condition above made sure that we aren't in a case where
3584 // both it and the current history item have a wakelock tag.
3585 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003586 cur.wakelockTag = cur.localWakelockTag;
3587 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003588 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003589 // If the last written history had a wake reason tag, we need to retain it.
3590 // Note that the condition above made sure that we aren't in a case where
3591 // both it and the current history item have a wakelock tag.
3592 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003593 cur.wakeReasonTag = cur.localWakeReasonTag;
3594 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003595 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003596 // If the last written history had an event, we need to retain it.
3597 // Note that the condition above made sure that we aren't in a case where
3598 // both it and the current history item have an event.
3599 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003600 cur.eventCode = mHistoryLastWritten.eventCode;
3601 cur.eventTag = cur.localEventTag;
3602 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003603 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003604 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003605 }
3606
Adam Lesinski45489782016-12-15 23:45:17 -08003607 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003608 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003609 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3610 // Clients can't deal with history buffers this large. This only
3611 // really happens when the device is on charger and interacted with
3612 // for long periods of time, like in retail mode. Since the device is
3613 // most likely charged, when unplugged, stats would have reset anyways.
3614 // Reset the stats and mark that we overflowed.
3615 // b/32540341
3616 resetAllStatsLocked();
3617
3618 // Mark that we want to set *OVERFLOW* event and the RESET:START
3619 // events.
3620 recordResetDueToOverflow = true;
3621
3622 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003623 if (!mHistoryOverflow) {
3624 mHistoryOverflow = true;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003625 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
3626 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003627 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003628 }
3629
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003630 // After overflow, we allow various bit-wise states to settle to 0.
3631 boolean writeAnyway = false;
3632 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3633 & mActiveHistoryStates;
3634 if (mHistoryLastWritten.states != curStates) {
3635 // mActiveHistoryStates keeps track of which bits in .states are now being
3636 // forced to 0.
3637 int old = mActiveHistoryStates;
3638 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3639 writeAnyway |= old != mActiveHistoryStates;
3640 }
3641 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3642 & mActiveHistoryStates2;
3643 if (mHistoryLastWritten.states2 != curStates2) {
3644 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3645 // forced to 0.
3646 int old = mActiveHistoryStates2;
3647 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3648 writeAnyway |= old != mActiveHistoryStates2;
3649 }
3650
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003651 // Once we've reached the maximum number of items, we only
3652 // record changes to the battery level and the most interesting states.
3653 // Once we've reached the maximum maximum number of items, we only
3654 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003655 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003656 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003657 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003658 & HistoryItem.MOST_INTERESTING_STATES) == 0
3659 || ((mHistoryLastWritten.states2^cur.states2)
3660 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003661 return;
3662 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003663
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003664 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003665 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003666 }
3667
Adam Lesinski45489782016-12-15 23:45:17 -08003668 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003669 // The history is currently empty; we need it to start with a time stamp.
3670 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003671 if (recordResetDueToOverflow) {
3672 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
3673 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003674 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_RESET, cur);
3675 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003676 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003677 }
3678
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003679 private void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd,
3680 HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003681 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003682 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003683 }
3684 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3685 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003686 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003687 mHistoryLastWritten.states &= mActiveHistoryStates;
3688 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003689 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003690 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003691 cur.wakelockTag = null;
3692 cur.wakeReasonTag = null;
3693 cur.eventCode = HistoryItem.EVENT_NONE;
3694 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003695 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3696 + " now " + mHistoryBuffer.dataPosition()
3697 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003698 }
3699
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003700 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003701 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003702
Dianne Hackborn40c87252014-03-19 16:55:40 -07003703 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003704 if (mTrackRunningHistoryElapsedRealtime != 0) {
3705 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3706 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3707 if (diffUptime < (diffElapsed-20)) {
3708 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3709 mHistoryAddTmp.setTo(mHistoryLastWritten);
3710 mHistoryAddTmp.wakelockTag = null;
3711 mHistoryAddTmp.wakeReasonTag = null;
3712 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3713 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
3714 addHistoryRecordInnerLocked(wakeElapsedTime, uptimeMs, mHistoryAddTmp);
3715 }
3716 }
3717 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3718 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3719 mTrackRunningHistoryUptime = uptimeMs;
3720 addHistoryRecordInnerLocked(elapsedRealtimeMs, uptimeMs, mHistoryCur);
3721 }
3722
3723 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
3724 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003725
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003726 if (!USE_OLD_HISTORY) {
3727 return;
3728 }
3729
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003730 if (!mHaveBatteryLevel || !mRecordingHistory) {
3731 return;
3732 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003733
3734 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003735 // and no states have since the last recorded entry changed and
3736 // are now resetting back to their original value, then just collapse
3737 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003738 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003739 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003740 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3741 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003742 // If the current is the same as the one before, then we no
3743 // longer need the entry.
3744 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003745 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003746 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003747 mHistoryLastEnd.next = null;
3748 mHistoryEnd.next = mHistoryCache;
3749 mHistoryCache = mHistoryEnd;
3750 mHistoryEnd = mHistoryLastEnd;
3751 mHistoryLastEnd = null;
3752 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003753 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3754 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003755 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003756 }
3757 return;
3758 }
3759
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003760 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003761 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003762
3763 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3764 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Narayan Kamath42151572018-02-05 15:29:04 +00003765 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003766 }
3767
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003768 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3769 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003770 // record changes to the battery level and the most interesting states.
3771 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003772 // record changes to the battery level.
3773 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003774 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003775 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003776 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003777 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003778 return;
3779 }
3780 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003781
Narayan Kamath42151572018-02-05 15:29:04 +00003782 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003783 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003784
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003785 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003786 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003787 mHistoryCur.eventCode = code;
3788 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3789 mHistoryCur.eventTag.string = name;
3790 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003791 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003792 }
3793
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003794 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003795 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003796 if (rec != null) {
3797 mHistoryCache = rec.next;
3798 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003799 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003800 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003801 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003802
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003803 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003804 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003805
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003806 void addHistoryRecordLocked(HistoryItem rec) {
3807 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003808 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003809 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003810 if (mHistoryEnd != null) {
3811 mHistoryEnd.next = rec;
3812 mHistoryEnd = rec;
3813 } else {
3814 mHistory = mHistoryEnd = rec;
3815 }
3816 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003817
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003818 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003819 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003820 if (USE_OLD_HISTORY) {
3821 if (mHistory != null) {
3822 mHistoryEnd.next = mHistoryCache;
3823 mHistoryCache = mHistory;
3824 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3825 }
3826 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003827 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003828
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003829 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003830 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003831 mTrackRunningHistoryElapsedRealtime = 0;
3832 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003833
3834 mHistoryBuffer.setDataSize(0);
3835 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003836 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003837 mHistoryLastLastWritten.clear();
3838 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003839 mHistoryTagPool.clear();
3840 mNextHistoryTagIdx = 0;
3841 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003842 mHistoryBufferLastPos = -1;
3843 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003844 mActiveHistoryStates = 0xffffffff;
3845 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003846 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003847
Mike Mac2f518a2017-09-19 16:06:03 -07003848 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003849 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003850 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003851 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3852 final boolean updateOnBatteryScreenOffTimeBase =
3853 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003854
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003855 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3856 if (updateOnBatteryScreenOffTimeBase) {
3857 updateKernelWakelocksLocked();
3858 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003859 }
Bookatz82b341172017-09-07 19:06:08 -07003860 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3861 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3862 // improved, remove the surrounding if{}.
3863 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3864 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3865 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003866 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003867 Slog.d(TAG, "Updating cpu time because screen is now "
3868 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003869 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003870 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -07003871 updateCpuTimeLocked();
Sudheer Shankae544d162017-12-28 17:06:20 -08003872 mExternalSync.scheduleCopyFromAllUidsCpuTimes(mOnBatteryTimeBase.isRunning(),
3873 mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003874
3875 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07003876 if (updateOnBatteryTimeBase) {
3877 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3878 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003879 }
Mike Mac2f518a2017-09-19 16:06:03 -07003880 }
3881 if (updateOnBatteryScreenOffTimeBase) {
3882 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
3883 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3884 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003885 }
Bookatzc8c44962017-05-11 12:12:54 -07003886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 }
3888 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003889
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003890 private void updateBatteryPropertiesLocked() {
3891 try {
3892 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
3893 ServiceManager.getService("batteryproperties"));
3894 registrar.scheduleUpdate();
3895 } catch (RemoteException e) {
3896 // Ignore.
3897 }
3898 }
3899
Dianne Hackborn099bc622014-01-22 13:39:16 -08003900 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
3901 mIsolatedUids.put(isolatedUid, appUid);
Bookatz90867622018-01-31 15:05:57 -08003902 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid,
3903 StatsLog.ISOLATED_UID_CHANGED__EVENT__CREATED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003904 final Uid u = getUidStatsLocked(appUid);
3905 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003906 }
3907
Adam Lesinski61db88f2015-07-01 15:05:07 -07003908 /**
3909 * Schedules a read of the latest cpu times before removing the isolated UID.
3910 * @see #removeIsolatedUidLocked(int)
3911 */
3912 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003913 int curUid = mIsolatedUids.get(isolatedUid, -1);
3914 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07003915 if (mExternalSync != null) {
3916 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
3917 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08003918 }
3919 }
3920
Adam Lesinski61db88f2015-07-01 15:05:07 -07003921 /**
3922 * This should only be called after the cpu times have been read.
3923 * @see #scheduleRemoveIsolatedUidLocked(int, int)
3924 */
3925 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003926 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08003927 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1),
3928 isolatedUid, StatsLog.ISOLATED_UID_CHANGED__EVENT__REMOVED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003929 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
3930 if (idx >= 0) {
3931 final int ownerUid = mIsolatedUids.valueAt(idx);
3932 final Uid u = getUidStatsLocked(ownerUid);
3933 u.removeIsolatedUid(isolatedUid);
3934 mIsolatedUids.removeAt(idx);
3935 }
3936 mKernelUidCpuTimeReader.removeUid(isolatedUid);
3937 mKernelUidCpuFreqTimeReader.removeUid(isolatedUid);
Mike Mafae87da2018-01-19 20:07:20 -08003938 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
3939 mKernelUidCpuActiveTimeReader.removeUid(isolatedUid);
3940 mKernelUidCpuClusterTimeReader.removeUid(isolatedUid);
3941 }
Adam Lesinski61db88f2015-07-01 15:05:07 -07003942 }
3943
Dianne Hackborn099bc622014-01-22 13:39:16 -08003944 public int mapUid(int uid) {
3945 int isolated = mIsolatedUids.get(uid, -1);
3946 return isolated > 0 ? isolated : uid;
3947 }
3948
3949 public void noteEventLocked(int code, String name, int uid) {
3950 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003951 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3952 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003953 }
Joe Onoratoabded112016-02-08 16:49:39 -08003954 final long elapsedRealtime = mClocks.elapsedRealtime();
3955 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003956 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003957 }
3958
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003959 boolean ensureStartClockTime(final long currentTime) {
3960 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
3961 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
3962 // If the start clock time has changed by more than a year, then presumably
3963 // the previous time was completely bogus. So we are going to figure out a
3964 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08003965 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003966 return true;
3967 }
3968 return false;
3969 }
3970
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003971 public void noteCurrentTimeChangedLocked() {
3972 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003973 final long elapsedRealtime = mClocks.elapsedRealtime();
3974 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003975 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003976 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003977 }
3978
Dianne Hackborn61659e52014-07-09 16:13:01 -07003979 public void noteProcessStartLocked(String name, int uid) {
3980 uid = mapUid(uid);
3981 if (isOnBattery()) {
3982 Uid u = getUidStatsLocked(uid);
3983 u.getProcessStatsLocked(name).incStartsLocked();
3984 }
3985 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3986 return;
3987 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003988 if (!mRecordAllHistory) {
3989 return;
3990 }
Joe Onoratoabded112016-02-08 16:49:39 -08003991 final long elapsedRealtime = mClocks.elapsedRealtime();
3992 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07003993 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
3994 }
3995
Dianne Hackborn1e01d162014-12-04 17:46:42 -08003996 public void noteProcessCrashLocked(String name, int uid) {
3997 uid = mapUid(uid);
3998 if (isOnBattery()) {
3999 Uid u = getUidStatsLocked(uid);
4000 u.getProcessStatsLocked(name).incNumCrashesLocked();
4001 }
4002 }
4003
4004 public void noteProcessAnrLocked(String name, int uid) {
4005 uid = mapUid(uid);
4006 if (isOnBattery()) {
4007 Uid u = getUidStatsLocked(uid);
4008 u.getProcessStatsLocked(name).incNumAnrsLocked();
4009 }
4010 }
4011
Dianne Hackborna8d10942015-11-19 17:55:19 -08004012 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07004013 int parentUid = mapUid(uid);
4014 if (uid != parentUid) {
4015 // Isolated UIDs process state is already rolled up into parent, so no need to track
4016 // Otherwise the parent's process state will get downgraded incorrectly
4017 return;
4018 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08004019 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004020 }
4021
4022 public void noteProcessFinishLocked(String name, int uid) {
4023 uid = mapUid(uid);
4024 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4025 return;
4026 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004027 if (!mRecordAllHistory) {
4028 return;
4029 }
Joe Onoratoabded112016-02-08 16:49:39 -08004030 final long elapsedRealtime = mClocks.elapsedRealtime();
4031 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004032 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004033 }
4034
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004035 public void noteSyncStartLocked(String name, int uid) {
4036 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004037 final long elapsedRealtime = mClocks.elapsedRealtime();
4038 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004039 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4040 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4041 return;
4042 }
4043 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4044 }
4045
4046 public void noteSyncFinishLocked(String name, int uid) {
4047 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004048 final long elapsedRealtime = mClocks.elapsedRealtime();
4049 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004050 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4051 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4052 return;
4053 }
4054 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4055 }
4056
4057 public void noteJobStartLocked(String name, int uid) {
4058 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004059 final long elapsedRealtime = mClocks.elapsedRealtime();
4060 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004061 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4062 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4063 return;
4064 }
4065 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4066 }
4067
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004068 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004069 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004070 final long elapsedRealtime = mClocks.elapsedRealtime();
4071 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004072 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004073 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4074 return;
4075 }
4076 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4077 }
4078
Narayan Kamath695cf722017-12-21 18:32:47 +00004079 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4080 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004081 }
4082
Narayan Kamath695cf722017-12-21 18:32:47 +00004083 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4084 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4085 }
4086
4087 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4088 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004089 if (!mRecordAllHistory) {
4090 return;
4091 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004092
Joe Onoratoabded112016-02-08 16:49:39 -08004093 final long elapsedRealtime = mClocks.elapsedRealtime();
4094 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004095
4096 if (workSource != null) {
4097 for (int i = 0; i < workSource.size(); ++i) {
4098 uid = mapUid(workSource.get(i));
4099 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4100 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4101 }
4102 }
4103
4104 List<WorkChain> workChains = workSource.getWorkChains();
4105 if (workChains != null) {
4106 for (int i = 0; i < workChains.size(); ++i) {
4107 uid = mapUid(workChains.get(i).getAttributionUid());
4108 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4109 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4110 }
4111 }
4112 }
4113 } else {
4114 uid = mapUid(uid);
4115
4116 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4117 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4118 }
4119 }
4120 }
4121
4122 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4123 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004124 if (workSource != null) {
4125 for (int i = 0; i < workSource.size(); ++i) {
4126 uid = workSource.get(i);
4127 final String workSourceName = workSource.getName(i);
4128
Tej Singh6f724c42018-01-03 20:02:03 -08004129 if (isOnBattery()) {
4130 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4131 workSourceName != null ? workSourceName : packageName);
4132 pkg.noteWakeupAlarmLocked(tag);
4133 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004134 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4135 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004136 }
4137
4138 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4139 if (workChains != null) {
4140 for (int i = 0; i < workChains.size(); ++i) {
4141 final WorkChain wc = workChains.get(i);
4142 uid = wc.getAttributionUid();
4143
Tej Singh6f724c42018-01-03 20:02:03 -08004144 if (isOnBattery()) {
4145 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4146 pkg.noteWakeupAlarmLocked(tag);
4147 }
Yangster-macafad8c62018-01-05 22:30:49 -08004148 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004149 }
4150 }
4151 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004152 if (isOnBattery()) {
4153 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4154 pkg.noteWakeupAlarmLocked(tag);
4155 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004156 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004157 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004158 }
4159
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004160 private void requestWakelockCpuUpdate() {
4161 if (!mHandler.hasMessages(MSG_UPDATE_WAKELOCKS)) {
4162 Message m = mHandler.obtainMessage(MSG_UPDATE_WAKELOCKS);
4163 mHandler.sendMessageDelayed(m, DELAY_UPDATE_WAKELOCKS);
4164 }
4165 }
4166
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004167 private void requestImmediateCpuUpdate() {
4168 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
4169 mHandler.sendEmptyMessage(MSG_UPDATE_WAKELOCKS);
4170 }
4171
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004172 public void setRecordAllHistoryLocked(boolean enabled) {
4173 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004174 if (!enabled) {
4175 // Clear out any existing state.
4176 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004177 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004178 // Record the currently running processes as stopping, now that we are no
4179 // longer tracking them.
4180 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4181 HistoryItem.EVENT_PROC);
4182 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004183 long mSecRealtime = mClocks.elapsedRealtime();
4184 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004185 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4186 SparseIntArray uids = ent.getValue();
4187 for (int j=0; j<uids.size(); j++) {
4188 addHistoryEventLocked(mSecRealtime, mSecUptime,
4189 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4190 }
4191 }
4192 }
4193 } else {
4194 // Record the currently running processes as starting, now that we are tracking them.
4195 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4196 HistoryItem.EVENT_PROC);
4197 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004198 long mSecRealtime = mClocks.elapsedRealtime();
4199 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004200 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4201 SparseIntArray uids = ent.getValue();
4202 for (int j=0; j<uids.size(); j++) {
4203 addHistoryEventLocked(mSecRealtime, mSecUptime,
4204 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4205 }
4206 }
4207 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004208 }
4209 }
4210
Dianne Hackborn9a755432014-05-15 17:05:22 -07004211 public void setNoAutoReset(boolean enabled) {
4212 mNoAutoReset = enabled;
4213 }
4214
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004215 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004216 if (mPretendScreenOff != pretendScreenOff) {
4217 mPretendScreenOff = pretendScreenOff;
4218 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4219 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004220 }
4221
Dianne Hackborn9a755432014-05-15 17:05:22 -07004222 private String mInitialAcquireWakeName;
4223 private int mInitialAcquireWakeUid = -1;
4224
Narayan Kamath81822022017-12-08 11:56:01 +00004225 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4226 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004227 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004228 if (type == WAKE_TYPE_PARTIAL) {
4229 // Only care about partial wake locks, since full wake locks
4230 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004231 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004232 if (historyName == null) {
4233 historyName = name;
4234 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004235 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004236 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4237 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004238 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004239 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004240 }
4241 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004242 if (mWakeLockNesting == 0) {
4243 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4244 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4245 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004246 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004247 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004248 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004249 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004250 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004251 } else if (!mWakeLockImportant && !unimportantForLogging
4252 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004253 if (mHistoryLastWritten.wakelockTag != null) {
4254 // We'll try to update the last tag.
4255 mHistoryLastWritten.wakelockTag = null;
4256 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004257 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004258 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004259 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004260 }
4261 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004262 }
4263 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004264 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004265 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004266 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4267 // We only update the cpu time when a wake lock is acquired if the screen is off.
4268 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4269 if (DEBUG_ENERGY_CPU) {
4270 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4271 }
4272 requestWakelockCpuUpdate();
4273 }
Narayan Kamath81822022017-12-08 11:56:01 +00004274
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004275 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004276
Yangster-mac20877162017-12-22 17:19:39 -08004277 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004278 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004279 getPowerManagerWakeLockLevel(type), name,
4280 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Yangster-macafad8c62018-01-05 22:30:49 -08004281 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004282 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004283 getPowerManagerWakeLockLevel(type), name,
4284 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Narayan Kamath81822022017-12-08 11:56:01 +00004285 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004286 }
4287 }
4288
Narayan Kamath81822022017-12-08 11:56:01 +00004289 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4290 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004291 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004292 if (type == WAKE_TYPE_PARTIAL) {
4293 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004294 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004295 if (historyName == null) {
4296 historyName = name;
4297 }
4298 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4299 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004300 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004301 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004302 }
4303 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004304 if (mWakeLockNesting == 0) {
4305 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4306 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4307 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004308 mInitialAcquireWakeName = null;
4309 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004310 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004311 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004312 }
4313 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004314 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4315 if (DEBUG_ENERGY_CPU) {
4316 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4317 }
4318 requestWakelockCpuUpdate();
4319 }
Narayan Kamath81822022017-12-08 11:56:01 +00004320
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004321 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004322 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004323 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004324 getPowerManagerWakeLockLevel(type), name,
4325 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Yangster-macafad8c62018-01-05 22:30:49 -08004326 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004327 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004328 getPowerManagerWakeLockLevel(type), name,
4329 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Narayan Kamath81822022017-12-08 11:56:01 +00004330 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004331 }
4332 }
4333
Bookatz1a1b0462018-01-12 11:47:03 -08004334 /**
4335 * Converts BatteryStats wakelock types back into PowerManager wakelock levels.
4336 * This is the inverse map of Notifier.getBatteryStatsWakeLockMonitorType().
4337 * These are estimations, since batterystats loses some of the original data.
4338 * TODO: Delete this. Instead, StatsLog.write should be called from PowerManager's Notifier.
4339 */
4340 private int getPowerManagerWakeLockLevel(int battertStatsWakelockType) {
4341 switch (battertStatsWakelockType) {
4342 // PowerManager.PARTIAL_WAKE_LOCK or PROXIMITY_SCREEN_OFF_WAKE_LOCK
4343 case BatteryStats.WAKE_TYPE_PARTIAL:
4344 return PowerManager.PARTIAL_WAKE_LOCK;
4345
4346 // PowerManager.SCREEN_DIM_WAKE_LOCK or SCREEN_BRIGHT_WAKE_LOCK
4347 case BatteryStats.WAKE_TYPE_FULL:
4348 return PowerManager.FULL_WAKE_LOCK;
4349
4350 case BatteryStats.WAKE_TYPE_DRAW:
4351 return PowerManager.DRAW_WAKE_LOCK;
4352
4353 // It appears that nothing can ever make a Window and PowerManager lacks an equivalent.
4354 case BatteryStats.WAKE_TYPE_WINDOW:
4355 Slog.e(TAG, "Illegal window wakelock type observed in batterystats.");
4356 return -1;
4357
4358 default:
4359 Slog.e(TAG, "Illegal wakelock type in batterystats: " + battertStatsWakelockType);
4360 return -1;
4361 }
4362 }
4363
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004364 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4365 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004366 final long elapsedRealtime = mClocks.elapsedRealtime();
4367 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004368 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004369 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004370 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4371 unimportantForLogging, elapsedRealtime, uptime);
4372 }
4373
4374 List<WorkChain> wcs = ws.getWorkChains();
4375 if (wcs != null) {
4376 for (int i = 0; i < wcs.size(); ++i) {
4377 final WorkChain wc = wcs.get(i);
4378 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4379 unimportantForLogging, elapsedRealtime, uptime);
4380 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004381 }
4382 }
4383
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004384 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4385 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004386 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004387 final long elapsedRealtime = mClocks.elapsedRealtime();
4388 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004389
4390 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4391
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004392 // For correct semantics, we start the need worksources first, so that we won't
4393 // make inappropriate history items as if all wake locks went away and new ones
4394 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004395 //
4396 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004397 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004398 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004399 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004400 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004401 }
Narayan Kamath81822022017-12-08 11:56:01 +00004402 if (wcs != null) {
4403 List<WorkChain> newChains = wcs[0];
4404 if (newChains != null) {
4405 for (int i = 0; i < newChains.size(); ++i) {
4406 final WorkChain newChain = newChains.get(i);
4407 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4408 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4409 uptime);
4410 }
4411 }
4412 }
4413
4414 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004415 final int NO = ws.size();
4416 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004417 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4418 uptime);
4419 }
4420 if (wcs != null) {
4421 List<WorkChain> goneChains = wcs[1];
4422 if (goneChains != null) {
4423 for (int i = 0; i < goneChains.size(); ++i) {
4424 final WorkChain goneChain = goneChains.get(i);
4425 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4426 historyName, type, elapsedRealtime, uptime);
4427 }
4428 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004429 }
4430 }
4431
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004432 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4433 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004434 final long elapsedRealtime = mClocks.elapsedRealtime();
4435 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004436 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004437 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004438 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4439 uptime);
4440 }
4441
4442 List<WorkChain> wcs = ws.getWorkChains();
4443 if (wcs != null) {
4444 for (int i = 0; i < wcs.size(); ++i) {
4445 final WorkChain wc = wcs.get(i);
4446 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4447 elapsedRealtime, uptime);
4448 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004449 }
4450 }
4451
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004452 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004453 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004454 uid, null, name, historyName,
4455 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08004456
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004457 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004458 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004459 }
4460
4461 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4462 WorkSource workSource) {
4463 final int N = workSource.size();
4464 for (int i = 0; i < N; ++i) {
4465 final int uid = mapUid(workSource.get(i));
4466 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004467 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004468 workSource.get(i), workSource.getName(i), name, historyName,
4469 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004470 }
4471
4472 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4473 if (workChains != null) {
4474 for (int i = 0; i < workChains.size(); ++i) {
4475 final WorkChain workChain = workChains.get(i);
4476 final int uid = workChain.getAttributionUid();
4477 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4478
Yangster-macafad8c62018-01-05 22:30:49 -08004479 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004480 workChain.getUids(), workChain.getTags(), name, historyName,
4481 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004482 }
4483 }
4484 }
4485
4486 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004487 final long elapsedRealtime = mClocks.elapsedRealtime();
4488 final long uptime = mClocks.uptimeMillis();
4489 if (historyName == null) {
4490 historyName = name;
4491 }
4492 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4493 0)) {
4494 return;
4495 }
4496 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4497 historyName, uid);
4498 }
4499
4500 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Bookatz90867622018-01-31 15:05:57 -08004501 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, null,
4502 name, historyName, StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08004503
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004504 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004505 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004506 }
4507
4508 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4509 WorkSource workSource) {
4510 final int N = workSource.size();
4511 for (int i = 0; i < N; ++i) {
4512 final int uid = mapUid(workSource.get(i));
4513 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004514 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004515 workSource.get(i), workSource.getName(i), name, historyName,
4516 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004517 }
4518
4519 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4520 if (workChains != null) {
4521 for (int i = 0; i < workChains.size(); ++i) {
4522 final WorkChain workChain = workChains.get(i);
4523 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004524 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004525 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004526 workChain.getUids(), workChain.getTags(), name, historyName,
4527 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004528 }
4529 }
4530 }
4531
4532 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004533 final long elapsedRealtime = mClocks.elapsedRealtime();
4534 final long uptime = mClocks.uptimeMillis();
4535 if (historyName == null) {
4536 historyName = name;
4537 }
4538 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4539 0)) {
4540 return;
4541 }
4542 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4543 historyName, uid);
4544 }
4545
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004546 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4547 if (mLastWakeupReason != null) {
4548 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004549 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004550 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz90867622018-01-31 15:05:57 -08004551 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
4552 /* duration_usec */ deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004553 mLastWakeupReason = null;
4554 }
4555 }
4556
4557 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004558 final long elapsedRealtime = mClocks.elapsedRealtime();
4559 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004560 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004561 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004562 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004563 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4564 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004565 mHistoryCur.wakeReasonTag.uid = 0;
4566 mLastWakeupReason = reason;
4567 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004568 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004569 }
4570
Adam Lesinski72478f02015-06-17 15:39:43 -07004571 public boolean startAddingCpuLocked() {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004572 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
Adam Lesinski72478f02015-06-17 15:39:43 -07004573 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004574 }
4575
Adam Lesinski72478f02015-06-17 15:39:43 -07004576 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4577 int statSystemTime, int statIOWaitTime, int statIrqTime,
4578 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004579 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4580 + " user=" + statUserTime + " sys=" + statSystemTime
4581 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4582 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4583 mCurStepCpuUserTime += totalUTime;
4584 mCurStepCpuSystemTime += totalSTime;
4585 mCurStepStatUserTime += statUserTime;
4586 mCurStepStatSystemTime += statSystemTime;
4587 mCurStepStatIOWaitTime += statIOWaitTime;
4588 mCurStepStatIrqTime += statIrqTime;
4589 mCurStepStatSoftIrqTime += statSoftIrqTime;
4590 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004591 }
4592
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004593 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004594 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004595 Uid u = mUidStats.get(uid);
4596 if (u != null) {
4597 u.mPids.remove(pid);
4598 }
4599 }
4600
4601 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004602 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004603 Uid u = mUidStats.get(uid);
4604 if (u != null) {
4605 Uid.Pid p = u.mPids.get(pid);
4606 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004607 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004608 }
4609 }
4610 return 0;
4611 }
4612
Dianne Hackborn287952c2010-09-22 22:34:31 -07004613 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004614 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004615 Uid u = mUidStats.get(uid);
4616 if (u != null) {
4617 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4618 }
4619 }
4620
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004621 int mSensorNesting;
4622
4623 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004624 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004625 final long elapsedRealtime = mClocks.elapsedRealtime();
4626 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004627 if (mSensorNesting == 0) {
4628 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4629 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4630 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004631 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004632 }
4633 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004634 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004635 }
4636
4637 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004638 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004639 final long elapsedRealtime = mClocks.elapsedRealtime();
4640 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004641 mSensorNesting--;
4642 if (mSensorNesting == 0) {
4643 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4644 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4645 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004646 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004647 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004648 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004649 }
4650
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004651 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004652
Narayan Kamath32684dd2018-01-08 17:32:51 +00004653 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4654 for (int i = 0; i < newWs.size(); ++i) {
4655 noteStartGpsLocked(newWs.get(i), null);
4656 }
4657
4658 for (int i = 0; i < oldWs.size(); ++i) {
4659 noteStopGpsLocked((oldWs.get(i)), null);
4660 }
4661
4662 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4663 if (wcs != null) {
4664 if (wcs[0] != null) {
4665 final List<WorkChain> newChains = wcs[0];
4666 for (int i = 0; i < newChains.size(); ++i) {
4667 noteStartGpsLocked(-1, newChains.get(i));
4668 }
4669 }
4670
4671 if (wcs[1] != null) {
4672 final List<WorkChain> goneChains = wcs[1];
4673 for (int i = 0; i < goneChains.size(); ++i) {
4674 noteStopGpsLocked(-1, goneChains.get(i));
4675 }
4676 }
4677 }
4678 }
4679
4680 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4681 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004682 final long elapsedRealtime = mClocks.elapsedRealtime();
4683 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004684 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004685 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004686 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4687 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004688 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004689 }
4690 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004691
4692 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004693 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4694 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004695 } else {
4696 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004697 workChain.getUids(), workChain.getTags(),
4698 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004699 }
4700
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004701 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004702 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004703
Narayan Kamath32684dd2018-01-08 17:32:51 +00004704 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4705 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004706 final long elapsedRealtime = mClocks.elapsedRealtime();
4707 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004708 mGpsNesting--;
4709 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004710 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004711 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4712 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004713 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004714 stopAllGpsSignalQualityTimersLocked(-1);
4715 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004716 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004717
4718 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004719 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4720 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004721 } else {
4722 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08004723 workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004724 }
4725
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004726 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004727 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004728
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004729 public void noteGpsSignalQualityLocked(int signalLevel) {
4730 if (mGpsNesting == 0) {
4731 return;
4732 }
4733 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4734 stopAllGpsSignalQualityTimersLocked(-1);
4735 return;
4736 }
4737 final long elapsedRealtime = mClocks.elapsedRealtime();
4738 final long uptime = mClocks.uptimeMillis();
4739 if (mGpsSignalQualityBin != signalLevel) {
4740 if (mGpsSignalQualityBin >= 0) {
4741 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4742 }
4743 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4744 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4745 }
4746 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4747 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4748 addHistoryRecordLocked(elapsedRealtime, uptime);
4749 mGpsSignalQualityBin = signalLevel;
4750 }
4751 return;
4752 }
4753
Jeff Browne95c3cd2014-05-02 16:59:26 -07004754 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004755 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004756
4757 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4758 // original 4 are mapped to one of the originals.
4759 if (state > MAX_TRACKED_SCREEN_STATE) {
4760 switch (state) {
4761 case Display.STATE_VR:
4762 state = Display.STATE_ON;
4763 break;
4764 default:
4765 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4766 break;
4767 }
4768 }
4769
Jeff Browne95c3cd2014-05-02 16:59:26 -07004770 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004771 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004772 final int oldState = mScreenState;
4773 mScreenState = state;
4774 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4775 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004776
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004777 if (state != Display.STATE_UNKNOWN) {
4778 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004779 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4780 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4781 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004782 } else {
4783 Slog.wtf(TAG, "Unexpected screen state: " + state);
4784 }
4785 }
4786
Mike Mac2f518a2017-09-19 16:06:03 -07004787 final long elapsedRealtime = mClocks.elapsedRealtime();
4788 final long uptime = mClocks.uptimeMillis();
4789
4790 boolean updateHistory = false;
4791 if (isScreenDoze(state)) {
4792 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4793 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4794 updateHistory = true;
4795 } else if (isScreenDoze(oldState)) {
4796 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4797 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4798 updateHistory = true;
4799 }
4800 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004801 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4802 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4803 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004804 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4805 if (mScreenBrightnessBin >= 0) {
4806 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4807 }
Mike Mac2f518a2017-09-19 16:06:03 -07004808 updateHistory = true;
4809 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004810 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4811 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4812 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004813 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4814 if (mScreenBrightnessBin >= 0) {
4815 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4816 }
Mike Mac2f518a2017-09-19 16:06:03 -07004817 updateHistory = true;
4818 }
4819 if (updateHistory) {
4820 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4821 + Display.stateToString(state));
4822 addHistoryRecordLocked(elapsedRealtime, uptime);
4823 }
4824 if (isScreenOn(state)) {
4825 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4826 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4827 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004828 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004829 elapsedRealtime, uptime);
4830 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004831 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004832 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004833 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004834 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004835 }
4836 // Update discharge amounts.
4837 if (mOnBatteryInternal) {
4838 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004839 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004840 }
4841 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004842
Dianne Hackborn617f8772009-03-31 15:04:46 -07004843 public void noteScreenBrightnessLocked(int brightness) {
4844 // Bin the brightness.
4845 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4846 if (bin < 0) bin = 0;
4847 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4848 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004849 final long elapsedRealtime = mClocks.elapsedRealtime();
4850 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004851 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4852 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004853 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4854 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004855 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004856 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004857 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004858 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004859 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004860 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004861 }
4862 mScreenBrightnessBin = bin;
4863 }
4864 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004865
Dianne Hackborn617f8772009-03-31 15:04:46 -07004866 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004867 if (mOnBatteryInternal) {
4868 uid = mapUid(uid);
4869 getUidStatsLocked(uid).noteUserActivityLocked(event);
4870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004871 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004872
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004873 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004874 final long elapsedRealtime = mClocks.elapsedRealtime();
4875 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004876 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4877 reason, reasonUid);
4878 }
4879
Jeff Browne95c3cd2014-05-02 16:59:26 -07004880 public void noteInteractiveLocked(boolean interactive) {
4881 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08004882 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004883 mInteractive = interactive;
4884 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
4885 if (interactive) {
4886 mInteractiveTimer.startRunningLocked(elapsedRealtime);
4887 } else {
4888 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
4889 }
4890 }
4891 }
4892
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004893 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004894 final long elapsedRealtime = mClocks.elapsedRealtime();
4895 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004896 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4897 extra, type);
4898 mNumConnectivityChange++;
4899 }
4900
Adam Lesinski5f056f62016-07-14 16:56:08 -07004901 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4902 final long uptimeMillis, int uid) {
4903 uid = mapUid(uid);
4904 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4905 uid);
4906 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4907 }
4908
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004909 /**
4910 * Updates the radio power state and returns true if an external stats collection should occur.
4911 */
4912 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004913 final long elapsedRealtime = mClocks.elapsedRealtime();
4914 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004915 if (mMobileRadioPowerState != powerState) {
4916 long realElapsedRealtimeMs;
4917 final boolean active =
4918 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4919 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4920 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004921 if (uid > 0) {
4922 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4923 }
4924
Adam Lesinski9acfd812016-04-19 18:29:50 -07004925 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004926 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4927 } else {
4928 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004929 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004930 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4931 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4932 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004933 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004934 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4935 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4936 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004937 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004938 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4939 }
4940 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4941 + Integer.toHexString(mHistoryCur.states));
4942 addHistoryRecordLocked(elapsedRealtime, uptime);
4943 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08004944 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004945 if (active) {
4946 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4947 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4948 } else {
4949 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004950 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004951 // Tell the caller to collect radio network/power stats.
4952 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004953 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004954 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004955 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004956 }
4957
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004958 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004959 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004960 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4961 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4962 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004963 final long elapsedRealtime = mClocks.elapsedRealtime();
4964 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004965 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004966 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004967 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4968 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004969 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004970 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004971 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004972 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4973 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004974 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004975 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004976 }
4977 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatz90867622018-01-31 15:05:57 -08004978 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
4979 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
4980 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004981 }
4982 }
4983
Bookatzddccf0a2017-11-28 16:48:14 -08004984 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004985 final long elapsedRealtime = mClocks.elapsedRealtime();
4986 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004987 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004988 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004989 // We don't go out of general idling mode until explicitly taken out of
4990 // device idle through going active or significant motion.
4991 nowIdling = true;
4992 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004993 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
4994 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
4995 // We don't go out of general light idling mode until explicitly taken out of
4996 // device idle through going active or significant motion.
4997 nowLightIdling = true;
4998 }
4999 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
5000 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
5001 activeReason, activeUid);
5002 }
Bookatzddccf0a2017-11-28 16:48:14 -08005003 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
5004 int statsmode;
5005 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
5006 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
5007 else statsmode = DEVICE_IDLE_MODE_OFF;
5008 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
5009 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005010 if (mDeviceIdling != nowIdling) {
5011 mDeviceIdling = nowIdling;
5012 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
5013 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
5014 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005015 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005016 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
5017 } else {
5018 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
5019 }
5020 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005021 if (mDeviceLightIdling != nowLightIdling) {
5022 mDeviceLightIdling = nowLightIdling;
5023 if (nowLightIdling) {
5024 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005025 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005026 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005027 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005028 }
5029 if (mDeviceIdleMode != mode) {
5030 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
5031 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
5032 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
5033 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005034 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005035 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
5036 mLastIdleTimeStart = elapsedRealtime;
5037 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
5038 if (lastDuration > mLongestLightIdleTime) {
5039 mLongestLightIdleTime = lastDuration;
5040 }
5041 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005042 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005043 if (lastDuration > mLongestFullIdleTime) {
5044 mLongestFullIdleTime = lastDuration;
5045 }
5046 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
5047 }
5048 if (mode == DEVICE_IDLE_MODE_LIGHT) {
5049 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005050 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005051 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
5052 }
5053 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08005054 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005055 }
5056 }
5057
Dianne Hackborn3accca02013-09-20 09:32:11 -07005058 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08005059 final long elapsedRealtime = mClocks.elapsedRealtime();
5060 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07005061 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005062 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07005063 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005064 PackageChange pc = new PackageChange();
5065 pc.mPackageName = pkgName;
5066 pc.mUpdate = true;
5067 pc.mVersionCode = versionCode;
5068 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005069 }
5070
5071 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005072 final long elapsedRealtime = mClocks.elapsedRealtime();
5073 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005074 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5075 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005076 PackageChange pc = new PackageChange();
5077 pc.mPackageName = pkgName;
5078 pc.mUpdate = true;
5079 addPackageChange(pc);
5080 }
5081
5082 private void addPackageChange(PackageChange pc) {
5083 if (mDailyPackageChanges == null) {
5084 mDailyPackageChanges = new ArrayList<>();
5085 }
5086 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005087 }
5088
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005089 void stopAllGpsSignalQualityTimersLocked(int except) {
5090 final long elapsedRealtime = mClocks.elapsedRealtime();
5091 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5092 if (i == except) {
5093 continue;
5094 }
5095 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5096 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5097 }
5098 }
5099 }
5100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005101 public void notePhoneOnLocked() {
5102 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005103 final long elapsedRealtime = mClocks.elapsedRealtime();
5104 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005105 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005106 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5107 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005108 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005110 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005111 }
5112 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005114 public void notePhoneOffLocked() {
5115 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005116 final long elapsedRealtime = mClocks.elapsedRealtime();
5117 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005118 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005119 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5120 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005121 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005122 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005123 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 }
5125 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005126
Dianne Hackborn3251b902014-06-20 14:40:53 -07005127 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005128 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005129 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005130 if (i == except) {
5131 continue;
5132 }
5133 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005134 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005135 }
5136 }
5137 }
5138
Dianne Hackborne4a59512010-12-07 11:08:07 -08005139 private int fixPhoneServiceState(int state, int signalBin) {
5140 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5141 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5142 // to infer that we are scanning from other data.
5143 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005144 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005145 state = ServiceState.STATE_IN_SERVICE;
5146 }
5147 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005148
Dianne Hackborne4a59512010-12-07 11:08:07 -08005149 return state;
5150 }
5151
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005152 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005153 boolean scanning = false;
5154 boolean newHistory = false;
5155
5156 mPhoneServiceStateRaw = state;
5157 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005158 mPhoneSignalStrengthBinRaw = strengthBin;
5159
Joe Onoratoabded112016-02-08 16:49:39 -08005160 final long elapsedRealtime = mClocks.elapsedRealtime();
5161 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005162
5163 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5164 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5165 // to infer that we are scanning from other data.
5166 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005167 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005168 state = ServiceState.STATE_IN_SERVICE;
5169 }
5170 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005171
5172 // If the phone is powered off, stop all timers.
5173 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005174 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005175
Dianne Hackborne4a59512010-12-07 11:08:07 -08005176 // If we are in service, make sure the correct signal string timer is running.
5177 } else if (state == ServiceState.STATE_IN_SERVICE) {
5178 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005179
5180 // If we're out of service, we are in the lowest signal strength
5181 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005182 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005183 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005184 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005185 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005186 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005187 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005188 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5189 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005190 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005191 }
5192 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005193
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005194 if (!scanning) {
5195 // If we are no longer scanning, then stop the scanning timer.
5196 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5197 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5198 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5199 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005200 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005201 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005202 }
5203 }
5204
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005205 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005206 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5207 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005208 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005209 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005210 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005211 mPhoneServiceState = state;
5212 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005213
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005214 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005215 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005216 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005217 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005218 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005219 if (strengthBin >= 0) {
5220 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005221 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005222 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005223 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5224 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005225 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005226 + Integer.toHexString(mHistoryCur.states));
5227 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005228 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005229 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005230 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005231 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005232 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005233 }
5234
5235 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005236 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005237 }
5238 }
5239
5240 /**
5241 * Telephony stack updates the phone state.
5242 * @param state phone state from ServiceState.getState()
5243 */
5244 public void notePhoneStateLocked(int state, int simState) {
5245 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005246 }
5247
Wink Savillee9b06d72009-05-18 21:47:50 -07005248 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005249 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005250 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005251 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005252 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005253
Dianne Hackborn627bba72009-03-24 22:32:56 -07005254 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
5255 int bin = DATA_CONNECTION_NONE;
5256 if (hasData) {
5257 switch (dataType) {
5258 case TelephonyManager.NETWORK_TYPE_EDGE:
5259 bin = DATA_CONNECTION_EDGE;
5260 break;
5261 case TelephonyManager.NETWORK_TYPE_GPRS:
5262 bin = DATA_CONNECTION_GPRS;
5263 break;
5264 case TelephonyManager.NETWORK_TYPE_UMTS:
5265 bin = DATA_CONNECTION_UMTS;
5266 break;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005267 case TelephonyManager.NETWORK_TYPE_CDMA:
5268 bin = DATA_CONNECTION_CDMA;
5269 break;
5270 case TelephonyManager.NETWORK_TYPE_EVDO_0:
5271 bin = DATA_CONNECTION_EVDO_0;
5272 break;
5273 case TelephonyManager.NETWORK_TYPE_EVDO_A:
5274 bin = DATA_CONNECTION_EVDO_A;
5275 break;
5276 case TelephonyManager.NETWORK_TYPE_1xRTT:
5277 bin = DATA_CONNECTION_1xRTT;
5278 break;
5279 case TelephonyManager.NETWORK_TYPE_HSDPA:
5280 bin = DATA_CONNECTION_HSDPA;
5281 break;
5282 case TelephonyManager.NETWORK_TYPE_HSUPA:
5283 bin = DATA_CONNECTION_HSUPA;
5284 break;
5285 case TelephonyManager.NETWORK_TYPE_HSPA:
5286 bin = DATA_CONNECTION_HSPA;
5287 break;
5288 case TelephonyManager.NETWORK_TYPE_IDEN:
5289 bin = DATA_CONNECTION_IDEN;
5290 break;
5291 case TelephonyManager.NETWORK_TYPE_EVDO_B:
5292 bin = DATA_CONNECTION_EVDO_B;
5293 break;
Robert Greenwalt962a9902010-11-02 11:10:25 -07005294 case TelephonyManager.NETWORK_TYPE_LTE:
5295 bin = DATA_CONNECTION_LTE;
5296 break;
5297 case TelephonyManager.NETWORK_TYPE_EHRPD:
5298 bin = DATA_CONNECTION_EHRPD;
5299 break;
Patrick Tjinb71703c2013-11-06 09:27:03 -08005300 case TelephonyManager.NETWORK_TYPE_HSPAP:
5301 bin = DATA_CONNECTION_HSPAP;
5302 break;
Siddharth Rayc72081d2018-02-13 11:31:54 -08005303 case TelephonyManager.NETWORK_TYPE_GSM:
5304 bin = DATA_CONNECTION_GSM;
5305 break;
5306 case TelephonyManager.NETWORK_TYPE_TD_SCDMA:
5307 bin = DATA_CONNECTION_TD_SCDMA;
5308 break;
5309 case TelephonyManager.NETWORK_TYPE_IWLAN:
5310 bin = DATA_CONNECTION_IWLAN;
5311 break;
5312 case TelephonyManager.NETWORK_TYPE_LTE_CA:
5313 bin = DATA_CONNECTION_LTE_CA;
5314 break;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005315 default:
5316 bin = DATA_CONNECTION_OTHER;
5317 break;
5318 }
5319 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005320 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005321 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005322 final long elapsedRealtime = mClocks.elapsedRealtime();
5323 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005324 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5325 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005326 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5327 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005328 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005329 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005330 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005331 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005332 }
5333 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005334 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005335 }
5336 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005337
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005338 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005339 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005340 final long elapsedRealtime = mClocks.elapsedRealtime();
5341 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005342 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005343 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5344 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005345 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005346 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005347 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005348 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005349 }
5350 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005351
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005352 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005353 final long elapsedRealtime = mClocks.elapsedRealtime();
5354 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005355 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005356 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005357 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5358 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005359 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005360 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005361 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005362 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005363 }
5364 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005365
5366 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005367 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005368 final long elapsedRealtime = mClocks.elapsedRealtime();
5369 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005370 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005371 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005372 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5373 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005374 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005375 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005376 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005377 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005378 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005379 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005380
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005381 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005382 if (mAudioOnNesting == 0) {
5383 return;
5384 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005385 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005386 final long elapsedRealtime = mClocks.elapsedRealtime();
5387 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005388 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005389 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005390 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5391 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005392 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005393 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005394 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005395 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005396 }
5397
5398 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005399 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005400 final long elapsedRealtime = mClocks.elapsedRealtime();
5401 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005402 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005403 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005404 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5405 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005406 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005407 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005408 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005409 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005410 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005411 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005412
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005413 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005414 if (mVideoOnNesting == 0) {
5415 return;
5416 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005417 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005418 final long elapsedRealtime = mClocks.elapsedRealtime();
5419 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005420 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005421 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005422 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5423 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005424 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005425 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005426 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005427 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005428 }
5429
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005430 public void noteResetAudioLocked() {
5431 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005432 final long elapsedRealtime = mClocks.elapsedRealtime();
5433 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005434 mAudioOnNesting = 0;
5435 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5436 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5437 + Integer.toHexString(mHistoryCur.states));
5438 addHistoryRecordLocked(elapsedRealtime, uptime);
5439 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5440 for (int i=0; i<mUidStats.size(); i++) {
5441 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5442 uid.noteResetAudioLocked(elapsedRealtime);
5443 }
5444 }
5445 }
5446
5447 public void noteResetVideoLocked() {
5448 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005449 final long elapsedRealtime = mClocks.elapsedRealtime();
5450 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005451 mAudioOnNesting = 0;
5452 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5453 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5454 + Integer.toHexString(mHistoryCur.states));
5455 addHistoryRecordLocked(elapsedRealtime, uptime);
5456 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5457 for (int i=0; i<mUidStats.size(); i++) {
5458 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5459 uid.noteResetVideoLocked(elapsedRealtime);
5460 }
5461 }
5462 }
5463
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005464 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005465 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005466 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005467 }
5468
5469 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005470 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005471 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005472 }
5473
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005474 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005475 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005476 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5477 }
5478
5479 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005480 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005481 getUidStatsLocked(uid).noteVibratorOffLocked();
5482 }
5483
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005484 public void noteFlashlightOnLocked(int uid) {
5485 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005486 final long elapsedRealtime = mClocks.elapsedRealtime();
5487 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005488 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005489 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5490 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005491 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005492 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005493 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5494 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005495 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5496 }
5497
5498 public void noteFlashlightOffLocked(int uid) {
5499 if (mFlashlightOnNesting == 0) {
5500 return;
5501 }
5502 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005503 final long elapsedRealtime = mClocks.elapsedRealtime();
5504 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005505 if (--mFlashlightOnNesting == 0) {
5506 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5507 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5508 + Integer.toHexString(mHistoryCur.states2));
5509 addHistoryRecordLocked(elapsedRealtime, uptime);
5510 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5511 }
5512 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5513 }
5514
5515 public void noteCameraOnLocked(int uid) {
5516 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005517 final long elapsedRealtime = mClocks.elapsedRealtime();
5518 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005519 if (mCameraOnNesting++ == 0) {
5520 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5521 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5522 + Integer.toHexString(mHistoryCur.states2));
5523 addHistoryRecordLocked(elapsedRealtime, uptime);
5524 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5525 }
5526 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5527 }
5528
5529 public void noteCameraOffLocked(int uid) {
5530 if (mCameraOnNesting == 0) {
5531 return;
5532 }
5533 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005534 final long elapsedRealtime = mClocks.elapsedRealtime();
5535 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005536 if (--mCameraOnNesting == 0) {
5537 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5538 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5539 + Integer.toHexString(mHistoryCur.states2));
5540 addHistoryRecordLocked(elapsedRealtime, uptime);
5541 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5542 }
5543 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5544 }
5545
5546 public void noteResetCameraLocked() {
5547 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005548 final long elapsedRealtime = mClocks.elapsedRealtime();
5549 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005550 mCameraOnNesting = 0;
5551 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5552 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5553 + Integer.toHexString(mHistoryCur.states2));
5554 addHistoryRecordLocked(elapsedRealtime, uptime);
5555 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5556 for (int i=0; i<mUidStats.size(); i++) {
5557 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5558 uid.noteResetCameraLocked(elapsedRealtime);
5559 }
5560 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005561 }
5562
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005563 public void noteResetFlashlightLocked() {
5564 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005565 final long elapsedRealtime = mClocks.elapsedRealtime();
5566 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005567 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005568 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5569 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005570 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005571 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005572 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5573 for (int i=0; i<mUidStats.size(); i++) {
5574 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5575 uid.noteResetFlashlightLocked(elapsedRealtime);
5576 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005577 }
5578 }
5579
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005580 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5581 boolean isUnoptimized) {
5582 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005583 final long elapsedRealtime = mClocks.elapsedRealtime();
5584 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005585 if (mBluetoothScanNesting == 0) {
5586 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5587 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5588 + Integer.toHexString(mHistoryCur.states2));
5589 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005590 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005591 }
5592 mBluetoothScanNesting++;
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005593
Yangster-macafad8c62018-01-05 22:30:49 -08005594 if (workChain != null) {
5595 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005596 workChain.getUids(), workChain.getTags(),
5597 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005598 if (isUnoptimized) {
5599 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005600 workChain.getUids(), workChain.getTags(),
5601 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005602 }
5603 } else {
Bookatz90867622018-01-31 15:05:57 -08005604 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null,
5605 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005606 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005607 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08005608 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005609 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005610 }
5611
Bookatzb1f04f32017-05-19 13:57:32 -07005612 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005613 if (workChain != null) {
5614 getUidStatsLocked(uid).addBluetoothWorkChain(workChain, isUnoptimized);
5615 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005616 }
5617
Bookatzb1f04f32017-05-19 13:57:32 -07005618 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005619 final int N = ws.size();
5620 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005621 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5622 }
5623
5624 final List<WorkChain> workChains = ws.getWorkChains();
5625 if (workChains != null) {
5626 for (int i = 0; i < workChains.size(); ++i) {
5627 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5628 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005629 }
5630 }
5631
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005632 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5633 boolean isUnoptimized) {
5634 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005635 final long elapsedRealtime = mClocks.elapsedRealtime();
5636 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005637 mBluetoothScanNesting--;
5638 if (mBluetoothScanNesting == 0) {
5639 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5640 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5641 + Integer.toHexString(mHistoryCur.states2));
5642 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005643 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005644 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005645
Yangster-macafad8c62018-01-05 22:30:49 -08005646 if (workChain != null) {
5647 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08005648 StatsLog.BLE_SCAN_STATE_CHANGED, workChain.getUids(), workChain.getTags(),
5649 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005650 if (isUnoptimized) {
5651 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005652 workChain.getUids(), workChain.getTags(),
5653 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005654 }
5655 } else {
Bookatz90867622018-01-31 15:05:57 -08005656 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null,
5657 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005658 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005659 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08005660 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005661 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005662 }
5663
Bookatz94c5a312017-07-11 16:49:17 -07005664 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005665 if (workChain != null) {
5666 getUidStatsLocked(uid).removeBluetoothWorkChain(workChain, isUnoptimized);
5667 }
5668 }
5669
5670 private int getAttributionUid(int uid, WorkChain workChain) {
5671 if (workChain != null) {
5672 return mapUid(workChain.getAttributionUid());
5673 }
5674
5675 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005676 }
5677
Bookatz94c5a312017-07-11 16:49:17 -07005678 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005679 final int N = ws.size();
5680 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005681 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5682 }
5683
5684 final List<WorkChain> workChains = ws.getWorkChains();
5685 if (workChains != null) {
5686 for (int i = 0; i < workChains.size(); ++i) {
5687 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5688 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005689 }
5690 }
5691
5692 public void noteResetBluetoothScanLocked() {
5693 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005694 final long elapsedRealtime = mClocks.elapsedRealtime();
5695 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005696 mBluetoothScanNesting = 0;
5697 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5698 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5699 + Integer.toHexString(mHistoryCur.states2));
5700 addHistoryRecordLocked(elapsedRealtime, uptime);
5701 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005702
5703
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005704 for (int i=0; i<mUidStats.size(); i++) {
5705 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5706 uid.noteResetBluetoothScanLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005707
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005708 List<WorkChain> allWorkChains = uid.getAllBluetoothWorkChains();
5709 if (allWorkChains != null) {
5710 for (int j = 0; j < allWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005711 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005712 allWorkChains.get(j).getUids(),
Bookatz90867622018-01-31 15:05:57 -08005713 allWorkChains.get(j).getTags(),
5714 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005715 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005716 allWorkChains.clear();
5717 }
5718
5719 List<WorkChain> unoptimizedWorkChains = uid.getUnoptimizedBluetoothWorkChains();
5720 if (unoptimizedWorkChains != null) {
5721 for (int j = 0; j < unoptimizedWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005722 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005723 unoptimizedWorkChains.get(j).getUids(),
Bookatz90867622018-01-31 15:05:57 -08005724 unoptimizedWorkChains.get(j).getTags(),
5725 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005726 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005727 unoptimizedWorkChains.clear();
5728 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005729 }
5730 }
5731 }
5732
Bookatz4ebc0642017-05-11 12:21:19 -07005733 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005734 final int N = ws.size();
5735 for (int i = 0; i < N; i++) {
5736 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005737 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005738 StatsLog.write_non_chained(StatsLog.BLE_SCAN_RESULT_RECEIVED, ws.get(i), ws.getName(i),
5739 numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005740 }
5741
5742 final List<WorkChain> workChains = ws.getWorkChains();
5743 if (workChains != null) {
5744 for (int i = 0; i < workChains.size(); ++i) {
5745 final WorkChain wc = workChains.get(i);
5746 int uid = mapUid(wc.getAttributionUid());
5747 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-macafad8c62018-01-05 22:30:49 -08005748 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED,
5749 wc.getUids(), wc.getTags(), numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005750 }
Bookatz956f36bf2017-04-28 09:48:17 -07005751 }
5752 }
5753
Adam Lesinski5f056f62016-07-14 16:56:08 -07005754 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5755 final long uptimeMillis, int uid) {
5756 uid = mapUid(uid);
5757 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5758 uid);
5759 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5760 }
5761
5762 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005763 final long elapsedRealtime = mClocks.elapsedRealtime();
5764 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005765 if (mWifiRadioPowerState != powerState) {
5766 final boolean active =
5767 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5768 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5769 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005770 if (uid > 0) {
5771 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5772 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005773 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005774 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005775 } else {
5776 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005777 mWifiActiveTimer.stopRunningLocked(
5778 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005779 }
5780 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5781 + Integer.toHexString(mHistoryCur.states));
5782 addHistoryRecordLocked(elapsedRealtime, uptime);
5783 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005784 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005785 }
5786 }
5787
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005788 public void noteWifiRunningLocked(WorkSource ws) {
5789 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005790 final long elapsedRealtime = mClocks.elapsedRealtime();
5791 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005792 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005793 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5794 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005795 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005796 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005797 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005798 int N = ws.size();
5799 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005800 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005801 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005802 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005803
5804 List<WorkChain> workChains = ws.getWorkChains();
5805 if (workChains != null) {
5806 for (int i = 0; i < workChains.size(); ++i) {
5807 int uid = mapUid(workChains.get(i).getAttributionUid());
5808 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5809 }
5810 }
5811
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005812 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005813 } else {
5814 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005815 }
5816 }
5817
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005818 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5819 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005820 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005821 int N = oldWs.size();
5822 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005823 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005824 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005825 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005826
5827 List<WorkChain> workChains = oldWs.getWorkChains();
5828 if (workChains != null) {
5829 for (int i = 0; i < workChains.size(); ++i) {
5830 int uid = mapUid(workChains.get(i).getAttributionUid());
5831 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5832 }
5833 }
5834
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005835 N = newWs.size();
5836 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005837 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005838 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005839 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005840
5841 workChains = newWs.getWorkChains();
5842 if (workChains != null) {
5843 for (int i = 0; i < workChains.size(); ++i) {
5844 int uid = mapUid(workChains.get(i).getAttributionUid());
5845 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5846 }
5847 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005848 } else {
5849 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5850 }
5851 }
5852
5853 public void noteWifiStoppedLocked(WorkSource ws) {
5854 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005855 final long elapsedRealtime = mClocks.elapsedRealtime();
5856 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005857 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005858 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5859 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005860 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005861 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005862 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005863 int N = ws.size();
5864 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005865 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005866 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005867 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005868
5869 List<WorkChain> workChains = ws.getWorkChains();
5870 if (workChains != null) {
5871 for (int i = 0; i < workChains.size(); ++i) {
5872 int uid = mapUid(workChains.get(i).getAttributionUid());
5873 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5874 }
5875 }
5876
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005877 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005878 } else {
5879 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005880 }
5881 }
5882
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005883 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5884 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5885 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005886 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005887 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005888 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005889 }
5890 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005891 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005892 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005893 }
5894 }
5895
Dianne Hackborn3251b902014-06-20 14:40:53 -07005896 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5897 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5898 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005899 final long elapsedRealtime = mClocks.elapsedRealtime();
5900 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005901 if (mWifiSupplState >= 0) {
5902 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5903 }
5904 mWifiSupplState = supplState;
5905 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5906 mHistoryCur.states2 =
5907 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5908 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5909 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5910 + Integer.toHexString(mHistoryCur.states2));
5911 addHistoryRecordLocked(elapsedRealtime, uptime);
5912 }
5913 }
5914
5915 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005916 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005917 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5918 if (i == except) {
5919 continue;
5920 }
5921 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5922 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5923 }
5924 }
5925 }
5926
5927 public void noteWifiRssiChangedLocked(int newRssi) {
5928 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5929 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5930 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005931 final long elapsedRealtime = mClocks.elapsedRealtime();
5932 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005933 if (mWifiSignalStrengthBin >= 0) {
5934 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5935 elapsedRealtime);
5936 }
5937 if (strengthBin >= 0) {
5938 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5939 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Bookatze5885242017-10-24 20:10:31 -07005940 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07005941 }
5942 mHistoryCur.states2 =
5943 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5944 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5945 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5946 + Integer.toHexString(mHistoryCur.states2));
5947 addHistoryRecordLocked(elapsedRealtime, uptime);
5948 } else {
5949 stopAllWifiSignalStrengthTimersLocked(-1);
5950 }
5951 mWifiSignalStrengthBin = strengthBin;
5952 }
5953 }
5954
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005955 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005956
The Android Open Source Project10592532009-03-18 17:39:46 -07005957 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005958 final long elapsedRealtime = mClocks.elapsedRealtime();
5959 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005960 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005961 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005962 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5963 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005964 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005965 }
5966 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005967 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005968 }
5969
5970 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005971 final long elapsedRealtime = mClocks.elapsedRealtime();
5972 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005973 mWifiFullLockNesting--;
5974 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005975 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005976 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
5977 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005978 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005979 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005980 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005981 }
5982
Nick Pelly6ccaa542012-06-15 15:22:47 -07005983 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005984
Nick Pelly6ccaa542012-06-15 15:22:47 -07005985 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005986 final long elapsedRealtime = mClocks.elapsedRealtime();
5987 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005988 if (mWifiScanNesting == 0) {
5989 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
5990 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005991 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005992 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005993 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07005994 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005995 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005996 }
5997
Nick Pelly6ccaa542012-06-15 15:22:47 -07005998 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005999 final long elapsedRealtime = mClocks.elapsedRealtime();
6000 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006001 mWifiScanNesting--;
6002 if (mWifiScanNesting == 0) {
6003 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
6004 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006005 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006006 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006007 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006008 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006009 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006010
Robert Greenwalta029ea12013-09-25 16:38:12 -07006011 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006012 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006013 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006014 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006015 }
6016
6017 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006018 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006019 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006020 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006021 }
6022
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006023 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006024
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006025 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006026 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006027 final long elapsedRealtime = mClocks.elapsedRealtime();
6028 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006029 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006030 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006031 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
6032 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006033 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006034
6035 // Start Wifi Multicast overall timer
6036 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
6037 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
6038 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
6039 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006040 }
6041 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006042 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006043 }
6044
6045 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006046 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006047 final long elapsedRealtime = mClocks.elapsedRealtime();
6048 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006049 mWifiMulticastNesting--;
6050 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006051 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006052 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
6053 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006054 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006055
6056 // Stop Wifi Multicast overall timer
6057 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
6058 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
6059 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
6060 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006061 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006062 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006063 }
6064
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006065 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
6066 int N = ws.size();
6067 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006068 final int uid = mapUid(ws.get(i));
6069 noteFullWifiLockAcquiredLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006070 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6071 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006072 }
6073
6074 final List<WorkChain> workChains = ws.getWorkChains();
6075 if (workChains != null) {
6076 for (int i = 0; i < workChains.size(); ++i) {
6077 final WorkChain workChain = workChains.get(i);
6078 final int uid = mapUid(workChain.getAttributionUid());
6079 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006080 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006081 workChain.getUids(), workChain.getTags(),
6082 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006083 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006084 }
6085 }
6086
6087 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
6088 int N = ws.size();
6089 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006090 final int uid = mapUid(ws.get(i));
6091 noteFullWifiLockReleasedLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006092 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6093 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006094 }
6095
6096 final List<WorkChain> workChains = ws.getWorkChains();
6097 if (workChains != null) {
6098 for (int i = 0; i < workChains.size(); ++i) {
6099 final WorkChain workChain = workChains.get(i);
6100 final int uid = mapUid(workChain.getAttributionUid());
6101 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006102 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006103 workChain.getUids(), workChain.getTags(),
6104 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006105 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006106 }
6107 }
6108
Nick Pelly6ccaa542012-06-15 15:22:47 -07006109 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006110 int N = ws.size();
6111 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006112 final int uid = mapUid(ws.get(i));
6113 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006114 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006115 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006116 }
6117
6118 final List<WorkChain> workChains = ws.getWorkChains();
6119 if (workChains != null) {
6120 for (int i = 0; i < workChains.size(); ++i) {
6121 final WorkChain workChain = workChains.get(i);
6122 final int uid = mapUid(workChain.getAttributionUid());
6123 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006124 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08006125 workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006126 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006127 }
6128 }
6129
Nick Pelly6ccaa542012-06-15 15:22:47 -07006130 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006131 int N = ws.size();
6132 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006133 final int uid = mapUid(ws.get(i));
6134 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006135 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006136 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006137 }
6138
6139 final List<WorkChain> workChains = ws.getWorkChains();
6140 if (workChains != null) {
6141 for (int i = 0; i < workChains.size(); ++i) {
6142 final WorkChain workChain = workChains.get(i);
6143 final int uid = mapUid(workChain.getAttributionUid());
6144 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006145 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006146 workChain.getUids(), workChain.getTags(),
6147 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006148 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006149 }
6150 }
6151
Robert Greenwalta029ea12013-09-25 16:38:12 -07006152 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6153 int N = ws.size();
6154 for (int i=0; i<N; i++) {
6155 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6156 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006157
6158 final List<WorkChain> workChains = ws.getWorkChains();
6159 if (workChains != null) {
6160 for (int i = 0; i < workChains.size(); ++i) {
6161 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6162 }
6163 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006164 }
6165
6166 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6167 int N = ws.size();
6168 for (int i=0; i<N; i++) {
6169 noteWifiBatchedScanStoppedLocked(ws.get(i));
6170 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006171
6172 final List<WorkChain> workChains = ws.getWorkChains();
6173 if (workChains != null) {
6174 for (int i = 0; i < workChains.size(); ++i) {
6175 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6176 }
6177 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006178 }
6179
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006180 private static String[] includeInStringArray(String[] array, String str) {
6181 if (ArrayUtils.indexOf(array, str) >= 0) {
6182 return array;
6183 }
6184 String[] newArray = new String[array.length+1];
6185 System.arraycopy(array, 0, newArray, 0, array.length);
6186 newArray[array.length] = str;
6187 return newArray;
6188 }
6189
6190 private static String[] excludeFromStringArray(String[] array, String str) {
6191 int index = ArrayUtils.indexOf(array, str);
6192 if (index >= 0) {
6193 String[] newArray = new String[array.length-1];
6194 if (index > 0) {
6195 System.arraycopy(array, 0, newArray, 0, index);
6196 }
6197 if (index < array.length-1) {
6198 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6199 }
6200 return newArray;
6201 }
6202 return array;
6203 }
6204
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006205 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006206 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006207
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006208 synchronized (mModemNetworkLock) {
6209 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6210 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6211 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6212 } else {
6213 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6214 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6215 }
6216 }
6217
6218 synchronized (mWifiNetworkLock) {
6219 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6220 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6221 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6222 } else {
6223 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6224 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6225 }
6226 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006227 }
6228
David Chenc8a43242017-10-17 16:23:28 -07006229 public String[] getWifiIfaces() {
6230 synchronized (mWifiNetworkLock) {
6231 return mWifiIfaces;
6232 }
6233 }
6234
6235 public String[] getMobileIfaces() {
6236 synchronized (mModemNetworkLock) {
6237 return mModemIfaces;
6238 }
6239 }
6240
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006241 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6242 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006244
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006245 @Override public int getScreenOnCount(int which) {
6246 return mScreenOnTimer.getCountLocked(which);
6247 }
6248
Mike Mac2f518a2017-09-19 16:06:03 -07006249 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6250 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6251 }
6252
6253 @Override public int getScreenDozeCount(int which) {
6254 return mScreenDozeTimer.getCountLocked(which);
6255 }
6256
Dianne Hackborn617f8772009-03-31 15:04:46 -07006257 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006258 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006259 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006260 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006261 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006262
Kweku Adams87b19ec2017-10-09 12:40:03 -07006263 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6264 return mScreenBrightnessTimer[brightnessBin];
6265 }
6266
Jeff Browne95c3cd2014-05-02 16:59:26 -07006267 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6268 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006269 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006270
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006271 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6272 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006273 }
6274
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006275 @Override public int getPowerSaveModeEnabledCount(int which) {
6276 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6277 }
6278
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006279 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6280 int which) {
6281 switch (mode) {
6282 case DEVICE_IDLE_MODE_LIGHT:
6283 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006284 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006285 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6286 }
6287 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006288 }
6289
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006290 @Override public int getDeviceIdleModeCount(int mode, int which) {
6291 switch (mode) {
6292 case DEVICE_IDLE_MODE_LIGHT:
6293 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006294 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006295 return mDeviceIdleModeFullTimer.getCountLocked(which);
6296 }
6297 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006298 }
6299
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006300 @Override public long getLongestDeviceIdleModeTime(int mode) {
6301 switch (mode) {
6302 case DEVICE_IDLE_MODE_LIGHT:
6303 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006304 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006305 return mLongestFullIdleTime;
6306 }
6307 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006308 }
6309
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006310 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6311 switch (mode) {
6312 case DEVICE_IDLE_MODE_LIGHT:
6313 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006314 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006315 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6316 }
6317 return 0;
6318 }
6319
6320 @Override public int getDeviceIdlingCount(int mode, int which) {
6321 switch (mode) {
6322 case DEVICE_IDLE_MODE_LIGHT:
6323 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006324 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006325 return mDeviceIdlingTimer.getCountLocked(which);
6326 }
6327 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006328 }
6329
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006330 @Override public int getNumConnectivityChange(int which) {
6331 int val = mNumConnectivityChange;
6332 if (which == STATS_CURRENT) {
6333 val -= mLoadedNumConnectivityChange;
6334 } else if (which == STATS_SINCE_UNPLUGGED) {
6335 val -= mUnpluggedNumConnectivityChange;
6336 }
6337 return val;
6338 }
6339
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006340 @Override public long getGpsSignalQualityTime(int strengthBin,
6341 long elapsedRealtimeUs, int which) {
6342 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6343 return 0;
6344 }
6345 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6346 elapsedRealtimeUs, which);
6347 }
6348
6349 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006350 final double opVolt = mPowerProfile.getAveragePower(
6351 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6352 if (opVolt == 0) {
6353 return 0;
6354 }
6355 double energyUsedMaMs = 0.0;
6356 final int which = STATS_SINCE_CHARGED;
6357 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6358 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6359 energyUsedMaMs
6360 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6361 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6362 }
6363 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006364 }
6365
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006366 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6367 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006369
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006370 @Override public int getPhoneOnCount(int which) {
6371 return mPhoneOnTimer.getCountLocked(which);
6372 }
6373
Dianne Hackborn627bba72009-03-24 22:32:56 -07006374 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006375 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006376 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006377 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006378 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006379
6380 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006381 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006382 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006383 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006384 }
6385
Kweku Adams87b19ec2017-10-09 12:40:03 -07006386 @Override public Timer getPhoneSignalScanningTimer() {
6387 return mPhoneSignalScanningTimer;
6388 }
6389
Catherine Liufb900812012-07-17 14:12:56 -05006390 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6391 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006392 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006393
Kweku Adams87b19ec2017-10-09 12:40:03 -07006394 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6395 return mPhoneSignalStrengthsTimer[strengthBin];
6396 }
6397
Dianne Hackborn627bba72009-03-24 22:32:56 -07006398 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006399 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006400 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006401 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006402 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006403
Dianne Hackborn617f8772009-03-31 15:04:46 -07006404 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006405 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006406 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006407
Kweku Adams87b19ec2017-10-09 12:40:03 -07006408 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6409 return mPhoneDataConnectionsTimer[dataType];
6410 }
6411
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006412 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6413 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006414 }
6415
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006416 @Override public int getMobileRadioActiveCount(int which) {
6417 return mMobileRadioActiveTimer.getCountLocked(which);
6418 }
6419
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006420 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6421 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6422 }
6423
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006424 @Override public long getMobileRadioActiveUnknownTime(int which) {
6425 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6426 }
6427
6428 @Override public int getMobileRadioActiveUnknownCount(int which) {
6429 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6430 }
6431
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006432 @Override public long getWifiMulticastWakelockTime(
6433 long elapsedRealtimeUs, int which) {
6434 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6435 elapsedRealtimeUs, which);
6436 }
6437
6438 @Override public int getWifiMulticastWakelockCount(int which) {
6439 return mWifiMulticastWakelockTimer.getCountLocked(which);
6440 }
6441
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006442 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6443 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006444 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006445
Siddharth Rayb50a6842017-12-14 15:15:28 -08006446 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6447 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6448 }
6449
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006450 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6451 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006452 }
6453
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006454 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006455 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006456 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006457 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006458 }
6459
6460 @Override public int getWifiStateCount(int wifiState, int which) {
6461 return mWifiStateTimer[wifiState].getCountLocked(which);
6462 }
6463
Kweku Adams87b19ec2017-10-09 12:40:03 -07006464 @Override public Timer getWifiStateTimer(int wifiState) {
6465 return mWifiStateTimer[wifiState];
6466 }
6467
Dianne Hackborn3251b902014-06-20 14:40:53 -07006468 @Override public long getWifiSupplStateTime(int state,
6469 long elapsedRealtimeUs, int which) {
6470 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6471 elapsedRealtimeUs, which);
6472 }
6473
6474 @Override public int getWifiSupplStateCount(int state, int which) {
6475 return mWifiSupplStateTimer[state].getCountLocked(which);
6476 }
6477
Kweku Adams87b19ec2017-10-09 12:40:03 -07006478 @Override public Timer getWifiSupplStateTimer(int state) {
6479 return mWifiSupplStateTimer[state];
6480 }
6481
Dianne Hackborn3251b902014-06-20 14:40:53 -07006482 @Override public long getWifiSignalStrengthTime(int strengthBin,
6483 long elapsedRealtimeUs, int which) {
6484 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6485 elapsedRealtimeUs, which);
6486 }
6487
6488 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6489 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6490 }
6491
Kweku Adams87b19ec2017-10-09 12:40:03 -07006492 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6493 return mWifiSignalStrengthsTimer[strengthBin];
6494 }
6495
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006496 @Override
6497 public ControllerActivityCounter getBluetoothControllerActivity() {
6498 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006499 }
6500
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006501 @Override
6502 public ControllerActivityCounter getWifiControllerActivity() {
6503 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006504 }
6505
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006506 @Override
6507 public ControllerActivityCounter getModemControllerActivity() {
6508 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006509 }
6510
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006511 @Override
6512 public boolean hasBluetoothActivityReporting() {
6513 return mHasBluetoothReporting;
6514 }
6515
6516 @Override
6517 public boolean hasWifiActivityReporting() {
6518 return mHasWifiReporting;
6519 }
6520
6521 @Override
6522 public boolean hasModemActivityReporting() {
6523 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006524 }
6525
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006526 @Override
6527 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006528 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6529 }
6530
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006531 @Override
6532 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006533 return mFlashlightOnTimer.getCountLocked(which);
6534 }
6535
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006536 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006537 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6538 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6539 }
6540
6541 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006542 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6543 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6544 }
6545
6546 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006547 public long getNetworkActivityBytes(int type, int which) {
6548 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6549 return mNetworkByteActivityCounters[type].getCountLocked(which);
6550 } else {
6551 return 0;
6552 }
6553 }
6554
6555 @Override
6556 public long getNetworkActivityPackets(int type, int which) {
6557 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6558 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006559 } else {
6560 return 0;
6561 }
6562 }
6563
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006564 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006565 final long currentTime = System.currentTimeMillis();
6566 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006567 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6568 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006569 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006570 return mStartClockTime;
6571 }
6572
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006573 @Override public String getStartPlatformVersion() {
6574 return mStartPlatformVersion;
6575 }
6576
6577 @Override public String getEndPlatformVersion() {
6578 return mEndPlatformVersion;
6579 }
6580
6581 @Override public int getParcelVersion() {
6582 return VERSION;
6583 }
6584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 @Override public boolean getIsOnBattery() {
6586 return mOnBattery;
6587 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6590 return mUidStats;
6591 }
6592
Adam Lesinski5f056f62016-07-14 16:56:08 -07006593 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6594 if (timer != null) {
6595 timer.detach();
6596 }
6597 }
6598
6599 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6600 boolean detachIfReset) {
6601 if (timer != null) {
6602 return timer.reset(detachIfReset);
6603 }
6604 return true;
6605 }
6606
Bookatz867c0d72017-03-07 18:23:42 -08006607 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6608 if (timer != null) {
6609 return timer.reset(detachIfReset);
6610 }
6611 return true;
6612 }
6613
Adam Lesinski5f056f62016-07-14 16:56:08 -07006614 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6615 if (counter != null) {
6616 counter.detach();
6617 }
6618 }
6619
6620 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6621 boolean detachIfReset) {
6622 if (counter != null) {
6623 counter.reset(detachIfReset);
6624 }
6625 }
6626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627 /**
6628 * The statistics associated with a particular uid.
6629 */
Joe Onoratoabded112016-02-08 16:49:39 -08006630 public static class Uid extends BatteryStats.Uid {
6631 /**
6632 * BatteryStatsImpl that we are associated with.
6633 */
6634 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006637
Bookatz867c0d72017-03-07 18:23:42 -08006638 /** TimeBase for when uid is in background and device is on battery. */
6639 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6640 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006641 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6642 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006643
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006644 boolean mWifiRunning;
6645 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006646
The Android Open Source Project10592532009-03-18 17:39:46 -07006647 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006648 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006649
Nick Pelly6ccaa542012-06-15 15:22:47 -07006650 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006651 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006652
Dianne Hackborn61659e52014-07-09 16:13:01 -07006653 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006654 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6655 StopwatchTimer[] mWifiBatchedScanTimer;
6656
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006657 boolean mWifiMulticastEnabled;
6658 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006659
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006660 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006661 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006662 StopwatchTimer mFlashlightTurnedOnTimer;
6663 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006664 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006665 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006666 /** Total time spent by the uid holding any partial wakelocks. */
6667 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006668 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006669 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006670 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006671 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006672
Dianne Hackborna8d10942015-11-19 17:55:19 -08006673 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006674 StopwatchTimer[] mProcessStateTimer;
6675
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006676 boolean mInForegroundService = false;
6677
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006678 BatchTimer mVibratorOnTimer;
6679
Dianne Hackborn617f8772009-03-31 15:04:46 -07006680 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006681
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006682 LongSamplingCounter[] mNetworkByteActivityCounters;
6683 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006684 LongSamplingCounter mMobileRadioActiveTime;
6685 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006688 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6689 */
6690 private LongSamplingCounter mMobileRadioApWakeupCount;
6691
6692 /**
6693 * How many times this UID woke up the Application Processor due to a Wifi packet.
6694 */
6695 private LongSamplingCounter mWifiRadioApWakeupCount;
6696
6697 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006698 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006699 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006700 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006701 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006702
6703 /**
6704 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006705 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006706 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006707 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6708
6709 /**
6710 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6711 * Can be null if the UID has had no such activity.
6712 */
6713 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006714
6715 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006716 * The CPU times we had at the last history details update.
6717 */
6718 long mLastStepUserTime;
6719 long mLastStepSystemTime;
6720 long mCurStepUserTime;
6721 long mCurStepSystemTime;
6722
Joe Onoratoabded112016-02-08 16:49:39 -08006723 LongSamplingCounter mUserCpuTime;
6724 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006725 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006726 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006727
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006728 LongSamplingCounterArray mCpuFreqTimeMs;
6729 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006730 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006731
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006732 LongSamplingCounterArray[] mProcStateTimeMs;
6733 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6734
6735 IntArray mChildUids;
6736
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006737 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 * The statistics we have collected for this uid's wake locks.
6739 */
Joe Onoratoabded112016-02-08 16:49:39 -08006740 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741
6742 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006743 * The statistics we have collected for this uid's syncs.
6744 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006745 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006746
6747 /**
6748 * The statistics we have collected for this uid's jobs.
6749 */
Bookatzaa4594a2017-03-24 12:39:56 -07006750 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006751
6752 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006753 * Count of the jobs that have completed and the reasons why they completed.
6754 */
6755 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6756
6757 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 * The statistics we have collected for this uid's sensor activations.
6759 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006760 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761
6762 /**
6763 * The statistics we have collected for this uid's processes.
6764 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006765 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766
6767 /**
6768 * The statistics we have collected for this uid's processes.
6769 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006770 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006771
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006772 /**
6773 * The transient wake stats we have collected for this uid's pids.
6774 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006775 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006776
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00006777 /**
6778 * The list of WorkChains associated with active bluetooth scans.
6779 *
6780 * NOTE: This is a hack and it only needs to exist because there's a "reset" API that is
6781 * supposed to stop and log all WorkChains that were currently active.
6782 */
6783 ArrayList<WorkChain> mAllBluetoothChains = null;
6784 ArrayList<WorkChain> mUnoptimizedBluetoothChains = null;
6785
Joe Onoratoabded112016-02-08 16:49:39 -08006786 public Uid(BatteryStatsImpl bsi, int uid) {
6787 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006788 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006789
Bookatz867c0d72017-03-07 18:23:42 -08006790 mOnBatteryBackgroundTimeBase = new TimeBase();
6791 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6792 mBsi.mClocks.elapsedRealtime() * 1000);
6793
Bookatzc8c44962017-05-11 12:12:54 -07006794 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6795 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6796 mBsi.mClocks.elapsedRealtime() * 1000);
6797
Joe Onoratoabded112016-02-08 16:49:39 -08006798 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6799 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006800 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6801 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006802
Dianne Hackborn657153b2016-07-29 14:54:14 -07006803 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006804 @Override public Wakelock instantiateObject() {
6805 return new Wakelock(mBsi, Uid.this);
6806 }
6807 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006808 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6809 @Override public DualTimer instantiateObject() {
6810 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6811 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006812 }
6813 };
Bookatzaa4594a2017-03-24 12:39:56 -07006814 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6815 @Override public DualTimer instantiateObject() {
6816 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6817 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006818 }
6819 };
6820
6821 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6822 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6823 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6824 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006825 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6826 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006827 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006828 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6829 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006830 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006831 }
6832
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006833 @VisibleForTesting
6834 public void setProcessStateForTest(int procState) {
6835 mProcessState = procState;
6836 }
6837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006839 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006840 return nullIfAllZeros(mCpuFreqTimeMs, which);
6841 }
6842
6843 @Override
6844 public long[] getScreenOffCpuFreqTimes(int which) {
6845 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6846 }
6847
6848 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006849 public long getCpuActiveTime() {
6850 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6851 }
6852
6853 @Override
6854 public long[] getCpuClusterTimes() {
6855 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6856 }
6857
6858
6859 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006860 public long[] getCpuFreqTimes(int which, int procState) {
6861 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006862 return null;
6863 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006864 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006865 return null;
6866 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006867 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6868 mProcStateTimeMs = null;
6869 return null;
6870 }
6871 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6872 }
6873
6874 @Override
6875 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6876 if (which < 0 || which >= NUM_PROCESS_STATE) {
6877 return null;
6878 }
6879 if (mProcStateScreenOffTimeMs == null) {
6880 return null;
6881 }
6882 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6883 mProcStateScreenOffTimeMs = null;
6884 return null;
6885 }
6886 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6887 }
6888
6889 public void addIsolatedUid(int isolatedUid) {
6890 if (mChildUids == null) {
6891 mChildUids = new IntArray();
6892 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6893 return;
6894 }
6895 mChildUids.add(isolatedUid);
6896 }
6897
6898 public void removeIsolatedUid(int isolatedUid) {
6899 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6900 if (idx < 0) {
6901 return;
6902 }
6903 mChildUids.remove(idx);
6904 }
6905
6906 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6907 if (cpuTimesMs == null) {
6908 return null;
6909 }
6910 final long[] counts = cpuTimesMs.getCountsLocked(which);
6911 if (counts == null) {
6912 return null;
6913 }
6914 // Return counts only if at least one of the elements is non-zero.
6915 for (int i = counts.length - 1; i >= 0; --i) {
6916 if (counts[i] != 0) {
6917 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006918 }
6919 }
6920 return null;
6921 }
6922
Sudheer Shankae544d162017-12-28 17:06:20 -08006923 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006924 if (mProcStateTimeMs == null) {
6925 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006926 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006927 if (mProcStateTimeMs[procState] == null
6928 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
6929 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6930 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006931 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006932 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006933 }
6934
Sudheer Shankae544d162017-12-28 17:06:20 -08006935 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6936 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006937 if (mProcStateScreenOffTimeMs == null) {
6938 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006939 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006940 if (mProcStateScreenOffTimeMs[procState] == null
6941 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
6942 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
6943 mBsi.mOnBatteryScreenOffTimeBase);
6944 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006945 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006946 }
6947
6948 @Override
Bookatzc8c44962017-05-11 12:12:54 -07006949 public Timer getAggregatedPartialWakelockTimer() {
6950 return mAggregatedPartialWakelockTimer;
6951 }
6952
6953 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006954 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006955 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006956 }
6957
6958 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07006959 public Timer getMulticastWakelockStats() {
6960 return mWifiMulticastTimer;
6961 }
6962
6963 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006964 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006965 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006966 }
6967
6968 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006969 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006970 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006971 }
6972
6973 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006974 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
6975 return mJobCompletions;
6976 }
6977
6978 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07006979 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006980 return mSensorStats;
6981 }
6982
6983 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006984 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006985 return mProcessStats;
6986 }
6987
6988 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006989 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006990 return mPackageStats;
6991 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006992
6993 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006994 public int getUid() {
6995 return mUid;
6996 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006997
6998 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006999 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007000 if (!mWifiRunning) {
7001 mWifiRunning = true;
7002 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007003 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7004 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007005 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007006 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007007 }
7008 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007009
Dianne Hackborn617f8772009-03-31 15:04:46 -07007010 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007011 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007012 if (mWifiRunning) {
7013 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007014 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007015 }
7016 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007017
Dianne Hackborn617f8772009-03-31 15:04:46 -07007018 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007019 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007020 if (!mFullWifiLockOut) {
7021 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007022 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007023 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7024 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007025 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007026 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007027 }
7028 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007029
The Android Open Source Project10592532009-03-18 17:39:46 -07007030 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007031 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007032 if (mFullWifiLockOut) {
7033 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007034 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007035 }
7036 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007037
The Android Open Source Project10592532009-03-18 17:39:46 -07007038 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007039 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007040 if (!mWifiScanStarted) {
7041 mWifiScanStarted = true;
7042 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007043 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7044 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
7045 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007046 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007047 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007048 }
7049 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007050
The Android Open Source Project10592532009-03-18 17:39:46 -07007051 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007052 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007053 if (mWifiScanStarted) {
7054 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007055 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007056 }
7057 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007058
7059 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007060 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007061 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007062 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007063 csph = csph >> 3;
7064 bin++;
7065 }
7066
7067 if (mWifiBatchedScanBinStarted == bin) return;
7068
7069 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7070 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007071 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007072 }
7073 mWifiBatchedScanBinStarted = bin;
7074 if (mWifiBatchedScanTimer[bin] == null) {
7075 makeWifiBatchedScanBin(bin, null);
7076 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007077 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007078 }
7079
7080 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007081 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007082 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7083 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007084 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007085 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7086 }
7087 }
7088
7089 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007090 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007091 if (!mWifiMulticastEnabled) {
7092 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007093 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007094 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7095 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007096 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007097 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007098 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007099 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7100 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007101 }
7102 }
7103
7104 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007105 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007106 if (mWifiMulticastEnabled) {
7107 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007108 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007109 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007110 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7111 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007112 }
7113 }
7114
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007115 @Override
7116 public ControllerActivityCounter getWifiControllerActivity() {
7117 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007118 }
7119
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007120 @Override
7121 public ControllerActivityCounter getBluetoothControllerActivity() {
7122 return mBluetoothControllerActivity;
7123 }
7124
7125 @Override
7126 public ControllerActivityCounter getModemControllerActivity() {
7127 return mModemControllerActivity;
7128 }
7129
7130 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7131 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007132 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007133 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007134 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007135 return mWifiControllerActivity;
7136 }
7137
7138 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7139 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007140 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007141 NUM_BT_TX_LEVELS);
7142 }
7143 return mBluetoothControllerActivity;
7144 }
7145
7146 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7147 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007148 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007149 ModemActivityInfo.TX_POWER_LEVELS);
7150 }
7151 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007152 }
7153
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007154 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7155 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007156 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7157 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007158 }
7159 return mAudioTurnedOnTimer;
7160 }
7161
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007162 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007163 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007164 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7165 StatsLog.AUDIO_STATE_CHANGED__STATE__ON);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007166 }
7167
7168 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7169 if (mAudioTurnedOnTimer != null) {
7170 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007171 if (!mAudioTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08007172 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7173 StatsLog.AUDIO_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007174 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007175 }
7176 }
7177
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007178 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7179 if (mAudioTurnedOnTimer != null) {
7180 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007181 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7182 StatsLog.AUDIO_STATE_CHANGED__STATE__OFF);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007183 }
7184 }
7185
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007186 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7187 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007188 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7189 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007190 }
7191 return mVideoTurnedOnTimer;
7192 }
7193
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007194 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007195 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007196 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
7197 StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__ON);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007198 }
7199
7200 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7201 if (mVideoTurnedOnTimer != null) {
7202 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007203 if (!mVideoTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007204 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(),
Bookatz90867622018-01-31 15:05:57 -08007205 null, StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007206 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007207 }
7208 }
7209
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007210 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7211 if (mVideoTurnedOnTimer != null) {
7212 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007213 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08007214 StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__OFF);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007215 }
7216 }
7217
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007218 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7219 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007220 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7221 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007222 }
7223 return mFlashlightTurnedOnTimer;
7224 }
7225
7226 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7227 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007228 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7229 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__ON);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007230 }
7231
7232 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7233 if (mFlashlightTurnedOnTimer != null) {
7234 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007235 if (!mFlashlightTurnedOnTimer.isRunningLocked()) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08007236 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08007237 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007238 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007239 }
7240 }
7241
7242 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7243 if (mFlashlightTurnedOnTimer != null) {
7244 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007245 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7246 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__OFF);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007247 }
7248 }
7249
7250 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7251 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007252 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7253 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007254 }
7255 return mCameraTurnedOnTimer;
7256 }
7257
7258 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7259 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007260 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7261 StatsLog.CAMERA_STATE_CHANGED__STATE__ON);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007262 }
7263
7264 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7265 if (mCameraTurnedOnTimer != null) {
7266 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007267 if (!mCameraTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08007268 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7269 StatsLog.CAMERA_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007270 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007271 }
7272 }
7273
7274 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7275 if (mCameraTurnedOnTimer != null) {
7276 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007277 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7278 StatsLog.CAMERA_STATE_CHANGED__STATE__OFF);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007279 }
7280 }
7281
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007282 public StopwatchTimer createForegroundActivityTimerLocked() {
7283 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007284 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7285 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007286 }
7287 return mForegroundActivityTimer;
7288 }
7289
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007290 public StopwatchTimer createForegroundServiceTimerLocked() {
7291 if (mForegroundServiceTimer == null) {
7292 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7293 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7294 }
7295 return mForegroundServiceTimer;
7296 }
7297
Bookatzc8c44962017-05-11 12:12:54 -07007298 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7299 if (mAggregatedPartialWakelockTimer == null) {
7300 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7301 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7302 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7303 }
7304 return mAggregatedPartialWakelockTimer;
7305 }
7306
Bookatz867c0d72017-03-07 18:23:42 -08007307 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007308 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007309 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7310 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7311 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007312 }
7313 return mBluetoothScanTimer;
7314 }
7315
Bookatzb1f04f32017-05-19 13:57:32 -07007316 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7317 if (mBluetoothUnoptimizedScanTimer == null) {
7318 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7319 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7320 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7321 }
7322 return mBluetoothUnoptimizedScanTimer;
7323 }
7324
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007325 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7326 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007327 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007328 if (isUnoptimized) {
7329 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7330 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007331 }
7332
Bookatz94c5a312017-07-11 16:49:17 -07007333 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007334 if (mBluetoothScanTimer != null) {
7335 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7336 }
Bookatz94c5a312017-07-11 16:49:17 -07007337 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007338 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7339 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007340 }
7341
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007342 public void addBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7343 if (mAllBluetoothChains == null) {
7344 mAllBluetoothChains = new ArrayList<WorkChain>(4);
7345 }
7346
7347 if (isUnoptimized && mUnoptimizedBluetoothChains == null) {
7348 mUnoptimizedBluetoothChains = new ArrayList<WorkChain>(4);
7349 }
7350
7351 mAllBluetoothChains.add(workChain);
7352 if (isUnoptimized) {
7353 mUnoptimizedBluetoothChains.add(workChain);
7354 }
7355 }
7356
7357 public void removeBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7358 if (mAllBluetoothChains != null) {
7359 mAllBluetoothChains.remove(workChain);
7360 }
7361
7362 if (isUnoptimized && mUnoptimizedBluetoothChains != null) {
7363 mUnoptimizedBluetoothChains.remove(workChain);
7364 }
7365 }
7366
7367 public List<WorkChain> getAllBluetoothWorkChains() {
7368 return mAllBluetoothChains;
7369 }
7370
7371 public List<WorkChain> getUnoptimizedBluetoothWorkChains() {
7372 return mUnoptimizedBluetoothChains;
7373 }
7374
7375
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007376 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7377 if (mBluetoothScanTimer != null) {
7378 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7379 }
Bookatzb1f04f32017-05-19 13:57:32 -07007380 if (mBluetoothUnoptimizedScanTimer != null) {
7381 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7382 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007383 }
7384
Bookatz956f36bf2017-04-28 09:48:17 -07007385 public Counter createBluetoothScanResultCounterLocked() {
7386 if (mBluetoothScanResultCounter == null) {
7387 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7388 }
7389 return mBluetoothScanResultCounter;
7390 }
7391
Bookatzb1f04f32017-05-19 13:57:32 -07007392 public Counter createBluetoothScanResultBgCounterLocked() {
7393 if (mBluetoothScanResultBgCounter == null) {
7394 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7395 }
7396 return mBluetoothScanResultBgCounter;
7397 }
7398
Bookatz4ebc0642017-05-11 12:21:19 -07007399 public void noteBluetoothScanResultsLocked(int numNewResults) {
7400 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007401 // Uses background timebase, so the count will only be incremented if uid in background.
7402 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007403 }
7404
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007405 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007406 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007407 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007408 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007409 }
7410
7411 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007412 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007413 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007414 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007415 }
7416 }
7417
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007418 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7419 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7420 }
7421
7422 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7423 if (mForegroundServiceTimer != null) {
7424 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7425 }
7426 }
7427
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007428 public BatchTimer createVibratorOnTimerLocked() {
7429 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007430 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7431 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007432 }
7433 return mVibratorOnTimer;
7434 }
7435
7436 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007437 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007438 }
7439
7440 public void noteVibratorOffLocked() {
7441 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007442 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007443 }
7444 }
7445
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007446 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007447 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007448 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007449 return 0;
7450 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007451 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007452 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007453
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007454 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007455 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007456 if (mFullWifiLockTimer == null) {
7457 return 0;
7458 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007459 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007460 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007461
7462 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007463 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007464 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007465 return 0;
7466 }
Bookatzaa4594a2017-03-24 12:39:56 -07007467 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007468 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007469
7470 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007471 public int getWifiScanCount(int which) {
7472 if (mWifiScanTimer == null) {
7473 return 0;
7474 }
Bookatzaa4594a2017-03-24 12:39:56 -07007475 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007476 }
7477
7478 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007479 public Timer getWifiScanTimer() {
7480 return mWifiScanTimer;
7481 }
7482
7483 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007484 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007485 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007486 return 0;
7487 }
7488 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7489 }
7490
7491 @Override
7492 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7493 if (mWifiScanTimer == null) {
7494 return 0;
7495 }
7496 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007497 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007498 }
7499
7500 @Override
7501 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007502 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007503 return 0;
7504 }
7505 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7506 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007507 }
7508
7509 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007510 public Timer getWifiScanBackgroundTimer() {
7511 if (mWifiScanTimer == null) {
7512 return null;
7513 }
7514 return mWifiScanTimer.getSubTimer();
7515 }
7516
7517 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007518 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007519 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7520 if (mWifiBatchedScanTimer[csphBin] == null) {
7521 return 0;
7522 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007523 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007524 }
7525
7526 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007527 public int getWifiBatchedScanCount(int csphBin, int which) {
7528 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7529 if (mWifiBatchedScanTimer[csphBin] == null) {
7530 return 0;
7531 }
7532 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7533 }
7534
7535 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007536 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007537 if (mWifiMulticastTimer == null) {
7538 return 0;
7539 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007540 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007541 }
7542
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007543 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007544 public Timer getAudioTurnedOnTimer() {
7545 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007546 }
7547
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007548 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007549 public Timer getVideoTurnedOnTimer() {
7550 return mVideoTurnedOnTimer;
7551 }
7552
7553 @Override
7554 public Timer getFlashlightTurnedOnTimer() {
7555 return mFlashlightTurnedOnTimer;
7556 }
7557
7558 @Override
7559 public Timer getCameraTurnedOnTimer() {
7560 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007561 }
7562
Dianne Hackborn617f8772009-03-31 15:04:46 -07007563 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007564 public Timer getForegroundActivityTimer() {
7565 return mForegroundActivityTimer;
7566 }
7567
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007568 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007569 public Timer getForegroundServiceTimer() {
7570 return mForegroundServiceTimer;
7571 }
7572
7573 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007574 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007575 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007576 }
7577
7578 @Override
7579 public Timer getBluetoothScanBackgroundTimer() {
7580 if (mBluetoothScanTimer == null) {
7581 return null;
7582 }
7583 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007584 }
7585
Bookatz956f36bf2017-04-28 09:48:17 -07007586 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007587 public Timer getBluetoothUnoptimizedScanTimer() {
7588 return mBluetoothUnoptimizedScanTimer;
7589 }
7590
7591 @Override
7592 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7593 if (mBluetoothUnoptimizedScanTimer == null) {
7594 return null;
7595 }
7596 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7597 }
7598
7599 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007600 public Counter getBluetoothScanResultCounter() {
7601 return mBluetoothScanResultCounter;
7602 }
7603
Bookatzb1f04f32017-05-19 13:57:32 -07007604 @Override
7605 public Counter getBluetoothScanResultBgCounter() {
7606 return mBluetoothScanResultBgCounter;
7607 }
7608
Dianne Hackborn61659e52014-07-09 16:13:01 -07007609 void makeProcessState(int i, Parcel in) {
7610 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7611
7612 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007613 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7614 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007615 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007616 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7617 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007618 }
7619 }
7620
7621 @Override
7622 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7623 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7624 if (mProcessStateTimer[state] == null) {
7625 return 0;
7626 }
7627 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7628 }
7629
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007630 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007631 public Timer getProcessStateTimer(int state) {
7632 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7633 return mProcessStateTimer[state];
7634 }
7635
7636 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007637 public Timer getVibratorOnTimer() {
7638 return mVibratorOnTimer;
7639 }
7640
7641 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007642 public void noteUserActivityLocked(int type) {
7643 if (mUserActivityCounters == null) {
7644 initUserActivityLocked();
7645 }
Jeff Browndf693de2012-07-27 12:03:38 -07007646 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7647 mUserActivityCounters[type].stepAtomic();
7648 } else {
7649 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7650 new Throwable());
7651 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007652 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007653
Dianne Hackborn617f8772009-03-31 15:04:46 -07007654 @Override
7655 public boolean hasUserActivity() {
7656 return mUserActivityCounters != null;
7657 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007658
Dianne Hackborn617f8772009-03-31 15:04:46 -07007659 @Override
7660 public int getUserActivityCount(int type, int which) {
7661 if (mUserActivityCounters == null) {
7662 return 0;
7663 }
Evan Millarc64edde2009-04-18 12:26:32 -07007664 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007665 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007666
Robert Greenwalta029ea12013-09-25 16:38:12 -07007667 void makeWifiBatchedScanBin(int i, Parcel in) {
7668 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7669
Joe Onoratoabded112016-02-08 16:49:39 -08007670 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007671 if (collected == null) {
7672 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007673 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007674 }
7675 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007676 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7677 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007678 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007679 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7680 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007681 }
7682 }
7683
7684
Dianne Hackborn617f8772009-03-31 15:04:46 -07007685 void initUserActivityLocked() {
7686 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7687 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007688 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007689 }
7690 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007691
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007692 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7693 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007694 initNetworkActivityLocked();
7695 }
7696 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007697 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7698 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007699 } else {
7700 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7701 new Throwable());
7702 }
7703 }
7704
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007705 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7706 if (mNetworkByteActivityCounters == null) {
7707 initNetworkActivityLocked();
7708 }
7709 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7710 mMobileRadioActiveCount.addCountLocked(1);
7711 }
7712
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007713 @Override
7714 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007715 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007716 }
7717
7718 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007719 public long getNetworkActivityBytes(int type, int which) {
7720 if (mNetworkByteActivityCounters != null && type >= 0
7721 && type < mNetworkByteActivityCounters.length) {
7722 return mNetworkByteActivityCounters[type].getCountLocked(which);
7723 } else {
7724 return 0;
7725 }
7726 }
7727
7728 @Override
7729 public long getNetworkActivityPackets(int type, int which) {
7730 if (mNetworkPacketActivityCounters != null && type >= 0
7731 && type < mNetworkPacketActivityCounters.length) {
7732 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007733 } else {
7734 return 0;
7735 }
7736 }
7737
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007738 @Override
7739 public long getMobileRadioActiveTime(int which) {
7740 return mMobileRadioActiveTime != null
7741 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7742 }
7743
7744 @Override
7745 public int getMobileRadioActiveCount(int which) {
7746 return mMobileRadioActiveCount != null
7747 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7748 }
7749
Adam Lesinskie08af192015-03-25 16:42:59 -07007750 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007751 public long getUserCpuTimeUs(int which) {
7752 return mUserCpuTime.getCountLocked(which);
7753 }
7754
7755 @Override
7756 public long getSystemCpuTimeUs(int which) {
7757 return mSystemCpuTime.getCountLocked(which);
7758 }
7759
7760 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007761 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007762 if (mCpuClusterSpeedTimesUs != null) {
7763 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7764 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7765 if (cpuSpeedTimesUs != null) {
7766 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7767 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007768 if (c != null) {
7769 return c.getCountLocked(which);
7770 }
7771 }
7772 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007773 }
7774 }
7775 return 0;
7776 }
7777
Adam Lesinski5f056f62016-07-14 16:56:08 -07007778 public void noteMobileRadioApWakeupLocked() {
7779 if (mMobileRadioApWakeupCount == null) {
7780 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7781 }
7782 mMobileRadioApWakeupCount.addCountLocked(1);
7783 }
7784
7785 @Override
7786 public long getMobileRadioApWakeupCount(int which) {
7787 if (mMobileRadioApWakeupCount != null) {
7788 return mMobileRadioApWakeupCount.getCountLocked(which);
7789 }
7790 return 0;
7791 }
7792
7793 public void noteWifiRadioApWakeupLocked() {
7794 if (mWifiRadioApWakeupCount == null) {
7795 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7796 }
7797 mWifiRadioApWakeupCount.addCountLocked(1);
7798 }
7799
7800 @Override
7801 public long getWifiRadioApWakeupCount(int which) {
7802 if (mWifiRadioApWakeupCount != null) {
7803 return mWifiRadioApWakeupCount.getCountLocked(which);
7804 }
7805 return 0;
7806 }
7807
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007808 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007809 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7810 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007811 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007812 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7813 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007814 }
Joe Onoratoabded112016-02-08 16:49:39 -08007815 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7816 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007818
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007819 /**
7820 * Clear all stats for this uid. Returns true if the uid is completely
7821 * inactive so can be dropped.
7822 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007823 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007824 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007825 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007826
Bookatz993a0be2017-07-21 09:03:23 -07007827 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7828 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7829
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007830 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007831 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007832 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007833 }
7834 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007835 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007836 active |= mFullWifiLockOut;
7837 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007838 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007839 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007840 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007841 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007842 if (mWifiBatchedScanTimer != null) {
7843 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7844 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007845 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007846 }
7847 }
7848 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7849 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007850 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007851 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007852 active |= mWifiMulticastEnabled;
7853 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007854
7855 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7856 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7857 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7858 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7859 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007860 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007861 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007862 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007863 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007864 if (mBluetoothScanResultCounter != null) {
7865 mBluetoothScanResultCounter.reset(false);
7866 }
Bookatzb1f04f32017-05-19 13:57:32 -07007867 if (mBluetoothScanResultBgCounter != null) {
7868 mBluetoothScanResultBgCounter.reset(false);
7869 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007870
Dianne Hackborn61659e52014-07-09 16:13:01 -07007871 if (mProcessStateTimer != null) {
7872 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7873 if (mProcessStateTimer[i] != null) {
7874 active |= !mProcessStateTimer[i].reset(false);
7875 }
7876 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007877 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007878 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007879 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007880 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007881 mVibratorOnTimer.detach();
7882 mVibratorOnTimer = null;
7883 } else {
7884 active = true;
7885 }
7886 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007887
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007888 if (mUserActivityCounters != null) {
7889 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7890 mUserActivityCounters[i].reset(false);
7891 }
7892 }
7893
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007894 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007895 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007896 mNetworkByteActivityCounters[i].reset(false);
7897 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007898 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007899 mMobileRadioActiveTime.reset(false);
7900 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007901 }
7902
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007903 if (mWifiControllerActivity != null) {
7904 mWifiControllerActivity.reset(false);
7905 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007906
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007907 if (mBluetoothControllerActivity != null) {
7908 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007909 }
7910
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007911 if (mModemControllerActivity != null) {
7912 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007913 }
7914
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007915 mUserCpuTime.reset(false);
7916 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007917
Sudheer Shankaaf857412017-07-21 00:14:24 -07007918 if (mCpuClusterSpeedTimesUs != null) {
7919 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007920 if (speeds != null) {
7921 for (LongSamplingCounter speed : speeds) {
7922 if (speed != null) {
7923 speed.reset(false);
7924 }
7925 }
7926 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007927 }
7928 }
7929
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007930 if (mCpuFreqTimeMs != null) {
7931 mCpuFreqTimeMs.reset(false);
7932 }
7933 if (mScreenOffCpuFreqTimeMs != null) {
7934 mScreenOffCpuFreqTimeMs.reset(false);
7935 }
7936
Mike Ma3d422c32017-10-25 11:08:57 -07007937 mCpuActiveTimeMs.reset(false);
7938 mCpuClusterTimesMs.reset(false);
7939
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007940 if (mProcStateTimeMs != null) {
7941 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7942 if (counters != null) {
7943 counters.reset(false);
7944 }
7945 }
7946 }
7947 if (mProcStateScreenOffTimeMs != null) {
7948 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7949 if (counters != null) {
7950 counters.reset(false);
7951 }
7952 }
7953 }
7954
Adam Lesinski5f056f62016-07-14 16:56:08 -07007955 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
7956 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
7957
Dianne Hackbornd953c532014-08-16 18:17:38 -07007958 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7959 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
7960 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007961 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007962 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007963 } else {
7964 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007965 }
7966 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007967 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07007968 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007969 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07007970 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007971 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007972 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007973 timer.detach();
7974 } else {
7975 active = true;
7976 }
7977 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007978 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07007979 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007980 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07007981 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007982 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007983 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007984 timer.detach();
7985 } else {
7986 active = true;
7987 }
7988 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007989 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007990 mJobCompletions.clear();
Dianne Hackborn61659e52014-07-09 16:13:01 -07007991 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
7992 Sensor s = mSensorStats.valueAt(ise);
7993 if (s.reset()) {
7994 mSensorStats.removeAt(ise);
7995 } else {
7996 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007997 }
7998 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07007999 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
8000 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008001 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008002 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008003 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008004 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008005 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008006 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008007 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008008 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008009 } else {
8010 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008011 }
8012 }
8013 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008014 if (mPackageStats.size() > 0) {
8015 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
8016 while (it.hasNext()) {
8017 Map.Entry<String, Pkg> pkgEntry = it.next();
8018 Pkg p = pkgEntry.getValue();
8019 p.detach();
8020 if (p.mServiceStats.size() > 0) {
8021 Iterator<Map.Entry<String, Pkg.Serv>> it2
8022 = p.mServiceStats.entrySet().iterator();
8023 while (it2.hasNext()) {
8024 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
8025 servEntry.getValue().detach();
8026 }
8027 }
8028 }
8029 mPackageStats.clear();
8030 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008031
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008032 mLastStepUserTime = mLastStepSystemTime = 0;
8033 mCurStepUserTime = mCurStepSystemTime = 0;
8034
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008035 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008036 if (mWifiRunningTimer != null) {
8037 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008038 }
8039 if (mFullWifiLockTimer != null) {
8040 mFullWifiLockTimer.detach();
8041 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008042 if (mWifiScanTimer != null) {
8043 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008044 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008045 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8046 if (mWifiBatchedScanTimer[i] != null) {
8047 mWifiBatchedScanTimer[i].detach();
8048 }
8049 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008050 if (mWifiMulticastTimer != null) {
8051 mWifiMulticastTimer.detach();
8052 }
8053 if (mAudioTurnedOnTimer != null) {
8054 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008055 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008056 }
8057 if (mVideoTurnedOnTimer != null) {
8058 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008059 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008060 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008061 if (mFlashlightTurnedOnTimer != null) {
8062 mFlashlightTurnedOnTimer.detach();
8063 mFlashlightTurnedOnTimer = null;
8064 }
8065 if (mCameraTurnedOnTimer != null) {
8066 mCameraTurnedOnTimer.detach();
8067 mCameraTurnedOnTimer = null;
8068 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008069 if (mForegroundActivityTimer != null) {
8070 mForegroundActivityTimer.detach();
8071 mForegroundActivityTimer = null;
8072 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008073 if (mForegroundServiceTimer != null) {
8074 mForegroundServiceTimer.detach();
8075 mForegroundServiceTimer = null;
8076 }
Bookatzc8c44962017-05-11 12:12:54 -07008077 if (mAggregatedPartialWakelockTimer != null) {
8078 mAggregatedPartialWakelockTimer.detach();
8079 mAggregatedPartialWakelockTimer = null;
8080 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008081 if (mBluetoothScanTimer != null) {
8082 mBluetoothScanTimer.detach();
8083 mBluetoothScanTimer = null;
8084 }
Bookatzb1f04f32017-05-19 13:57:32 -07008085 if (mBluetoothUnoptimizedScanTimer != null) {
8086 mBluetoothUnoptimizedScanTimer.detach();
8087 mBluetoothUnoptimizedScanTimer = null;
8088 }
Bookatz956f36bf2017-04-28 09:48:17 -07008089 if (mBluetoothScanResultCounter != null) {
8090 mBluetoothScanResultCounter.detach();
8091 mBluetoothScanResultCounter = null;
8092 }
Bookatzb1f04f32017-05-19 13:57:32 -07008093 if (mBluetoothScanResultBgCounter != null) {
8094 mBluetoothScanResultBgCounter.detach();
8095 mBluetoothScanResultBgCounter = null;
8096 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008097 if (mUserActivityCounters != null) {
8098 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8099 mUserActivityCounters[i].detach();
8100 }
8101 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008102 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008103 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008104 mNetworkByteActivityCounters[i].detach();
8105 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008106 }
8107 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008108
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008109 if (mWifiControllerActivity != null) {
8110 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008111 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008112
8113 if (mBluetoothControllerActivity != null) {
8114 mBluetoothControllerActivity.detach();
8115 }
8116
8117 if (mModemControllerActivity != null) {
8118 mModemControllerActivity.detach();
8119 }
8120
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008121 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008122
8123 mUserCpuTime.detach();
8124 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008125
Sudheer Shankaaf857412017-07-21 00:14:24 -07008126 if (mCpuClusterSpeedTimesUs != null) {
8127 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008128 if (cpuSpeeds != null) {
8129 for (LongSamplingCounter c : cpuSpeeds) {
8130 if (c != null) {
8131 c.detach();
8132 }
8133 }
8134 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008135 }
8136 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008137
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008138 if (mCpuFreqTimeMs != null) {
8139 mCpuFreqTimeMs.detach();
8140 }
8141 if (mScreenOffCpuFreqTimeMs != null) {
8142 mScreenOffCpuFreqTimeMs.detach();
8143 }
Mike Ma3d422c32017-10-25 11:08:57 -07008144 mCpuActiveTimeMs.detach();
8145 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008146
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008147 if (mProcStateTimeMs != null) {
8148 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8149 if (counters != null) {
8150 counters.detach();
8151 }
8152 }
8153 }
8154 if (mProcStateScreenOffTimeMs != null) {
8155 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8156 if (counters != null) {
8157 counters.detach();
8158 }
8159 }
8160 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008161 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8162 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008163 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008164
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008165 return !active;
8166 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008167
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008168 void writeJobCompletionsToParcelLocked(Parcel out) {
8169 int NJC = mJobCompletions.size();
8170 out.writeInt(NJC);
8171 for (int ijc=0; ijc<NJC; ijc++) {
8172 out.writeString(mJobCompletions.keyAt(ijc));
8173 SparseIntArray types = mJobCompletions.valueAt(ijc);
8174 int NT = types.size();
8175 out.writeInt(NT);
8176 for (int it=0; it<NT; it++) {
8177 out.writeInt(types.keyAt(it));
8178 out.writeInt(types.valueAt(it));
8179 }
8180 }
8181 }
8182
Bookatz867c0d72017-03-07 18:23:42 -08008183 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8184 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008185 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008186
Dianne Hackbornd953c532014-08-16 18:17:38 -07008187 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8188 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008189 out.writeInt(NW);
8190 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008191 out.writeString(wakeStats.keyAt(iw));
8192 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008193 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008194 }
8195
Bookatz2bffb5b2017-04-13 11:59:33 -07008196 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008197 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008198 out.writeInt(NS);
8199 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008200 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008201 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008202 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8203 }
8204
Bookatzaa4594a2017-03-24 12:39:56 -07008205 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008206 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008207 out.writeInt(NJ);
8208 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008209 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008210 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008211 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8212 }
8213
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008214 writeJobCompletionsToParcelLocked(out);
8215
Dianne Hackborn61659e52014-07-09 16:13:01 -07008216 int NSE = mSensorStats.size();
8217 out.writeInt(NSE);
8218 for (int ise=0; ise<NSE; ise++) {
8219 out.writeInt(mSensorStats.keyAt(ise));
8220 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008221 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 }
8223
Dianne Hackborn61659e52014-07-09 16:13:01 -07008224 int NP = mProcessStats.size();
8225 out.writeInt(NP);
8226 for (int ip=0; ip<NP; ip++) {
8227 out.writeString(mProcessStats.keyAt(ip));
8228 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008229 proc.writeToParcelLocked(out);
8230 }
8231
8232 out.writeInt(mPackageStats.size());
8233 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8234 out.writeString(pkgEntry.getKey());
8235 Uid.Pkg pkg = pkgEntry.getValue();
8236 pkg.writeToParcelLocked(out);
8237 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008238
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008239 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008240 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008241 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008242 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008243 out.writeInt(0);
8244 }
8245 if (mFullWifiLockTimer != null) {
8246 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008247 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008248 } else {
8249 out.writeInt(0);
8250 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008251 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008252 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008253 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008254 } else {
8255 out.writeInt(0);
8256 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008257 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8258 if (mWifiBatchedScanTimer[i] != null) {
8259 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008260 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008261 } else {
8262 out.writeInt(0);
8263 }
8264 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008265 if (mWifiMulticastTimer != null) {
8266 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008267 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008268 } else {
8269 out.writeInt(0);
8270 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008271
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008272 if (mAudioTurnedOnTimer != null) {
8273 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008274 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008275 } else {
8276 out.writeInt(0);
8277 }
8278 if (mVideoTurnedOnTimer != null) {
8279 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008280 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008281 } else {
8282 out.writeInt(0);
8283 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008284 if (mFlashlightTurnedOnTimer != null) {
8285 out.writeInt(1);
8286 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8287 } else {
8288 out.writeInt(0);
8289 }
8290 if (mCameraTurnedOnTimer != null) {
8291 out.writeInt(1);
8292 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8293 } else {
8294 out.writeInt(0);
8295 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008296 if (mForegroundActivityTimer != null) {
8297 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008298 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008299 } else {
8300 out.writeInt(0);
8301 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008302 if (mForegroundServiceTimer != null) {
8303 out.writeInt(1);
8304 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8305 } else {
8306 out.writeInt(0);
8307 }
Bookatzc8c44962017-05-11 12:12:54 -07008308 if (mAggregatedPartialWakelockTimer != null) {
8309 out.writeInt(1);
8310 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8311 } else {
8312 out.writeInt(0);
8313 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008314 if (mBluetoothScanTimer != null) {
8315 out.writeInt(1);
8316 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8317 } else {
8318 out.writeInt(0);
8319 }
Bookatzb1f04f32017-05-19 13:57:32 -07008320 if (mBluetoothUnoptimizedScanTimer != null) {
8321 out.writeInt(1);
8322 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8323 } else {
8324 out.writeInt(0);
8325 }
Bookatz956f36bf2017-04-28 09:48:17 -07008326 if (mBluetoothScanResultCounter != null) {
8327 out.writeInt(1);
8328 mBluetoothScanResultCounter.writeToParcel(out);
8329 } else {
8330 out.writeInt(0);
8331 }
Bookatzb1f04f32017-05-19 13:57:32 -07008332 if (mBluetoothScanResultBgCounter != null) {
8333 out.writeInt(1);
8334 mBluetoothScanResultBgCounter.writeToParcel(out);
8335 } else {
8336 out.writeInt(0);
8337 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008338 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8339 if (mProcessStateTimer[i] != null) {
8340 out.writeInt(1);
8341 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8342 } else {
8343 out.writeInt(0);
8344 }
8345 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008346 if (mVibratorOnTimer != null) {
8347 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008348 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008349 } else {
8350 out.writeInt(0);
8351 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008352 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008353 out.writeInt(1);
8354 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8355 mUserActivityCounters[i].writeToParcel(out);
8356 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008357 } else {
8358 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008359 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008360 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008361 out.writeInt(1);
8362 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008363 mNetworkByteActivityCounters[i].writeToParcel(out);
8364 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008365 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008366 mMobileRadioActiveTime.writeToParcel(out);
8367 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008368 } else {
8369 out.writeInt(0);
8370 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008371
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008372 if (mWifiControllerActivity != null) {
8373 out.writeInt(1);
8374 mWifiControllerActivity.writeToParcel(out, 0);
8375 } else {
8376 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008377 }
8378
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008379 if (mBluetoothControllerActivity != null) {
8380 out.writeInt(1);
8381 mBluetoothControllerActivity.writeToParcel(out, 0);
8382 } else {
8383 out.writeInt(0);
8384 }
8385
8386 if (mModemControllerActivity != null) {
8387 out.writeInt(1);
8388 mModemControllerActivity.writeToParcel(out, 0);
8389 } else {
8390 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008391 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008392
8393 mUserCpuTime.writeToParcel(out);
8394 mSystemCpuTime.writeToParcel(out);
8395
Sudheer Shankaaf857412017-07-21 00:14:24 -07008396 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008397 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008398 out.writeInt(mCpuClusterSpeedTimesUs.length);
8399 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008400 if (cpuSpeeds != null) {
8401 out.writeInt(1);
8402 out.writeInt(cpuSpeeds.length);
8403 for (LongSamplingCounter c : cpuSpeeds) {
8404 if (c != null) {
8405 out.writeInt(1);
8406 c.writeToParcel(out);
8407 } else {
8408 out.writeInt(0);
8409 }
8410 }
8411 } else {
8412 out.writeInt(0);
8413 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008414 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008415 } else {
8416 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008417 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008418
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008419 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8420 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008421
8422 mCpuActiveTimeMs.writeToParcel(out);
8423 mCpuClusterTimesMs.writeToParcel(out);
8424
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008425 if (mProcStateTimeMs != null) {
8426 out.writeInt(mProcStateTimeMs.length);
8427 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8428 LongSamplingCounterArray.writeToParcel(out, counters);
8429 }
8430 } else {
8431 out.writeInt(0);
8432 }
8433 if (mProcStateScreenOffTimeMs != null) {
8434 out.writeInt(mProcStateScreenOffTimeMs.length);
8435 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8436 LongSamplingCounterArray.writeToParcel(out, counters);
8437 }
8438 } else {
8439 out.writeInt(0);
8440 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008441
Adam Lesinski5f056f62016-07-14 16:56:08 -07008442 if (mMobileRadioApWakeupCount != null) {
8443 out.writeInt(1);
8444 mMobileRadioApWakeupCount.writeToParcel(out);
8445 } else {
8446 out.writeInt(0);
8447 }
8448
8449 if (mWifiRadioApWakeupCount != null) {
8450 out.writeInt(1);
8451 mWifiRadioApWakeupCount.writeToParcel(out);
8452 } else {
8453 out.writeInt(0);
8454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008455 }
8456
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008457 void readJobCompletionsFromParcelLocked(Parcel in) {
8458 int numJobCompletions = in.readInt();
8459 mJobCompletions.clear();
8460 for (int j = 0; j < numJobCompletions; j++) {
8461 String jobName = in.readString();
8462 int numTypes = in.readInt();
8463 if (numTypes > 0) {
8464 SparseIntArray types = new SparseIntArray();
8465 for (int k = 0; k < numTypes; k++) {
8466 int type = in.readInt();
8467 int count = in.readInt();
8468 types.put(type, count);
8469 }
8470 mJobCompletions.put(jobName, types);
8471 }
8472 }
8473 }
8474
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008475 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008476 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008477 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008479 int numWakelocks = in.readInt();
8480 mWakelockStats.clear();
8481 for (int j = 0; j < numWakelocks; j++) {
8482 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008483 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008484 wakelock.readFromParcelLocked(
8485 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008486 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008487 }
8488
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008489 int numSyncs = in.readInt();
8490 mSyncStats.clear();
8491 for (int j = 0; j < numSyncs; j++) {
8492 String syncName = in.readString();
8493 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008494 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8495 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008496 }
8497 }
8498
8499 int numJobs = in.readInt();
8500 mJobStats.clear();
8501 for (int j = 0; j < numJobs; j++) {
8502 String jobName = in.readString();
8503 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008504 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8505 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008506 }
8507 }
8508
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008509 readJobCompletionsFromParcelLocked(in);
8510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008511 int numSensors = in.readInt();
8512 mSensorStats.clear();
8513 for (int k = 0; k < numSensors; k++) {
8514 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008515 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008516 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8517 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008518 mSensorStats.put(sensorNumber, sensor);
8519 }
8520
8521 int numProcs = in.readInt();
8522 mProcessStats.clear();
8523 for (int k = 0; k < numProcs; k++) {
8524 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008525 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008526 proc.readFromParcelLocked(in);
8527 mProcessStats.put(processName, proc);
8528 }
8529
8530 int numPkgs = in.readInt();
8531 mPackageStats.clear();
8532 for (int l = 0; l < numPkgs; l++) {
8533 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008534 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008535 pkg.readFromParcelLocked(in);
8536 mPackageStats.put(packageName, pkg);
8537 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008538
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008539 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008540 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008541 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8542 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008543 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008544 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008545 }
8546 mFullWifiLockOut = false;
8547 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008548 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8549 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008550 } else {
8551 mFullWifiLockTimer = null;
8552 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008553 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008554 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008555 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8556 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8557 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008558 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008559 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008560 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008561 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8562 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8563 if (in.readInt() != 0) {
8564 makeWifiBatchedScanBin(i, in);
8565 } else {
8566 mWifiBatchedScanTimer[i] = null;
8567 }
8568 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008569 mWifiMulticastEnabled = false;
8570 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008571 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8572 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008573 } else {
8574 mWifiMulticastTimer = null;
8575 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008576 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008577 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8578 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008579 } else {
8580 mAudioTurnedOnTimer = null;
8581 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008582 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008583 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8584 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008585 } else {
8586 mVideoTurnedOnTimer = null;
8587 }
8588 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008589 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8590 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008591 } else {
8592 mFlashlightTurnedOnTimer = null;
8593 }
8594 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008595 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8596 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008597 } else {
8598 mCameraTurnedOnTimer = null;
8599 }
8600 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008601 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8602 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008603 } else {
8604 mForegroundActivityTimer = null;
8605 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008606 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008607 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8608 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8609 } else {
8610 mForegroundServiceTimer = null;
8611 }
8612 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008613 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8614 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8615 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8616 in);
8617 } else {
8618 mAggregatedPartialWakelockTimer = null;
8619 }
8620 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008621 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8622 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8623 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008624 } else {
8625 mBluetoothScanTimer = null;
8626 }
Bookatz956f36bf2017-04-28 09:48:17 -07008627 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008628 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8629 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8630 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8631 } else {
8632 mBluetoothUnoptimizedScanTimer = null;
8633 }
8634 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008635 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8636 } else {
8637 mBluetoothScanResultCounter = null;
8638 }
Bookatzb1f04f32017-05-19 13:57:32 -07008639 if (in.readInt() != 0) {
8640 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8641 } else {
8642 mBluetoothScanResultBgCounter = null;
8643 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008644 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008645 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8646 if (in.readInt() != 0) {
8647 makeProcessState(i, in);
8648 } else {
8649 mProcessStateTimer[i] = null;
8650 }
8651 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008652 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008653 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8654 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008655 } else {
8656 mVibratorOnTimer = null;
8657 }
8658 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008659 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8660 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008661 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008662 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008663 } else {
8664 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008665 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008666 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008667 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8668 mNetworkPacketActivityCounters
8669 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008670 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008671 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008672 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008673 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008674 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008675 }
Joe Onoratoabded112016-02-08 16:49:39 -08008676 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8677 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008678 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008679 mNetworkByteActivityCounters = null;
8680 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008681 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008682
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008683 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008684 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008685 NUM_WIFI_TX_LEVELS, in);
8686 } else {
8687 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008688 }
8689
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008690 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008691 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008692 NUM_BT_TX_LEVELS, in);
8693 } else {
8694 mBluetoothControllerActivity = null;
8695 }
8696
8697 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008698 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008699 ModemActivityInfo.TX_POWER_LEVELS, in);
8700 } else {
8701 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008702 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008703
Joe Onoratoabded112016-02-08 16:49:39 -08008704 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8705 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008706
Adam Lesinski6832f392015-09-05 18:05:40 -07008707 if (in.readInt() != 0) {
8708 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008709 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008710 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008711 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008712
Sudheer Shankaaf857412017-07-21 00:14:24 -07008713 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008714 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8715 if (in.readInt() != 0) {
8716 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008717 if (mBsi.mPowerProfile != null &&
8718 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008719 throw new ParcelFormatException("Incompatible number of cpu speeds");
8720 }
8721
8722 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008723 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008724 for (int speed = 0; speed < numSpeeds; speed++) {
8725 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008726 cpuSpeeds[speed] = new LongSamplingCounter(
8727 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008728 }
8729 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008730 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008731 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008732 }
8733 }
8734 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008735 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008736 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008737
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008738 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8739 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8740 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008741
Mike Ma3d422c32017-10-25 11:08:57 -07008742 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8743 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8744
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008745 int length = in.readInt();
8746 if (length == NUM_PROCESS_STATE) {
8747 mProcStateTimeMs = new LongSamplingCounterArray[length];
8748 for (int procState = 0; procState < length; ++procState) {
8749 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8750 in, mBsi.mOnBatteryTimeBase);
8751 }
8752 } else {
8753 mProcStateTimeMs = null;
8754 }
8755 length = in.readInt();
8756 if (length == NUM_PROCESS_STATE) {
8757 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8758 for (int procState = 0; procState < length; ++procState) {
8759 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8760 in, mBsi.mOnBatteryScreenOffTimeBase);
8761 }
8762 } else {
8763 mProcStateScreenOffTimeMs = null;
8764 }
8765
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008766 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008767 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8768 } else {
8769 mMobileRadioApWakeupCount = null;
8770 }
8771
8772 if (in.readInt() != 0) {
8773 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8774 } else {
8775 mWifiRadioApWakeupCount = null;
8776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008777 }
8778
8779 /**
8780 * The statistics associated with a particular wake lock.
8781 */
Joe Onoratoabded112016-02-08 16:49:39 -08008782 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8783 /**
8784 * BatteryStatsImpl that we are associated with.
8785 */
8786 protected BatteryStatsImpl mBsi;
8787
8788 /**
8789 * BatteryStatsImpl that we are associated with.
8790 */
8791 protected Uid mUid;
8792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008793 /**
8794 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008795 * 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 -08008796 */
Bookatz5b5ec322017-05-26 09:40:38 -07008797 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008798
8799 /**
8800 * How long (in ms) this uid has been keeping the device fully awake.
8801 */
Evan Millarc64edde2009-04-18 12:26:32 -07008802 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008803
8804 /**
8805 * How long (in ms) this uid has had a window keeping the device awake.
8806 */
Evan Millarc64edde2009-04-18 12:26:32 -07008807 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008808
8809 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008810 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008811 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008812 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008813
Joe Onoratoabded112016-02-08 16:49:39 -08008814 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8815 mBsi = bsi;
8816 mUid = uid;
8817 }
8818
Adam Lesinski9425fe22015-06-19 12:02:13 -07008819 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008820 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8821 * proper timer pool from the given BatteryStatsImpl object.
8822 *
8823 * @param in the Parcel to be read from.
8824 * return a new Timer, or null.
8825 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008826 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8827 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008828 if (in.readInt() == 0) {
8829 return null;
8830 }
8831
Joe Onoratoabded112016-02-08 16:49:39 -08008832 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008833 }
8834
Joe Onorato92fd23f2016-07-25 11:18:42 -07008835 /**
8836 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8837 * proper timer pool from the given BatteryStatsImpl object.
8838 *
8839 * @param in the Parcel to be read from.
8840 * return a new Timer, or null.
8841 */
Bookatz5b5ec322017-05-26 09:40:38 -07008842 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8843 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008844 if (in.readInt() == 0) {
8845 return null;
8846 }
8847
Bookatz5b5ec322017-05-26 09:40:38 -07008848 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008849 }
8850
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008851 boolean reset() {
8852 boolean wlactive = false;
8853 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008854 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008855 }
8856 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008857 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008858 }
8859 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008860 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008861 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008862 if (mTimerDraw != null) {
8863 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008864 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008865 if (!wlactive) {
8866 if (mTimerFull != null) {
8867 mTimerFull.detach();
8868 mTimerFull = null;
8869 }
8870 if (mTimerPartial != null) {
8871 mTimerPartial.detach();
8872 mTimerPartial = null;
8873 }
8874 if (mTimerWindow != null) {
8875 mTimerWindow.detach();
8876 mTimerWindow = null;
8877 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008878 if (mTimerDraw != null) {
8879 mTimerDraw.detach();
8880 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008881 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008882 }
8883 return !wlactive;
8884 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008885
Bookatz5b5ec322017-05-26 09:40:38 -07008886 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
8887 TimeBase screenOffBgTimeBase, Parcel in) {
8888 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
8889 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008890 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
8891 mBsi.mFullTimers, timeBase, in);
8892 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
8893 mBsi.mWindowTimers, timeBase, in);
8894 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
8895 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008896 }
8897
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008898 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
8899 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
8900 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
8901 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008902 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008903 }
8904
8905 @Override
8906 public Timer getWakeTime(int type) {
8907 switch (type) {
8908 case WAKE_TYPE_FULL: return mTimerFull;
8909 case WAKE_TYPE_PARTIAL: return mTimerPartial;
8910 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008911 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008912 default: throw new IllegalArgumentException("type = " + type);
8913 }
8914 }
8915 }
8916
Joe Onoratoabded112016-02-08 16:49:39 -08008917 public static class Sensor extends BatteryStats.Uid.Sensor {
8918 /**
8919 * BatteryStatsImpl that we are associated with.
8920 */
8921 protected BatteryStatsImpl mBsi;
8922
8923 /**
Bookatz867c0d72017-03-07 18:23:42 -08008924 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08008925 */
8926 protected Uid mUid;
8927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08008929 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008930
Joe Onoratoabded112016-02-08 16:49:39 -08008931 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
8932 mBsi = bsi;
8933 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 mHandle = handle;
8935 }
8936
Bookatz867c0d72017-03-07 18:23:42 -08008937 private DualTimer readTimersFromParcel(
8938 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939 if (in.readInt() == 0) {
8940 return null;
8941 }
8942
Joe Onoratoabded112016-02-08 16:49:39 -08008943 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07008945 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08008946 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 }
Bookatz867c0d72017-03-07 18:23:42 -08008948 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008949 }
8950
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008951 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008952 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008953 mTimer = null;
8954 return true;
8955 }
8956 return false;
8957 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008958
Bookatz867c0d72017-03-07 18:23:42 -08008959 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
8960 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008961 }
8962
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008963 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07008964 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 }
8966
8967 @Override
8968 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07008969 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008970 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008971
8972 @Override
Bookatz867c0d72017-03-07 18:23:42 -08008973 public Timer getSensorBackgroundTime() {
8974 if (mTimer == null) {
8975 return null;
8976 }
8977 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008978 }
8979
8980 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008981 public int getHandle() {
8982 return mHandle;
8983 }
8984 }
8985
8986 /**
8987 * The statistics associated with a particular process.
8988 */
Joe Onoratoabded112016-02-08 16:49:39 -08008989 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
8990 /**
8991 * BatteryStatsImpl that we are associated with.
8992 */
8993 protected BatteryStatsImpl mBsi;
8994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008995 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008996 * The name of this process.
8997 */
8998 final String mName;
8999
9000 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08009001 * Remains true until removed from the stats.
9002 */
9003 boolean mActive = true;
9004
9005 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009006 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009007 */
9008 long mUserTime;
9009
9010 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009011 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009012 */
9013 long mSystemTime;
9014
9015 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009016 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009017 */
9018 long mForegroundTime;
9019
9020 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009021 * Number of times the process has been started.
9022 */
9023 int mStarts;
9024
9025 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009026 * Number of times the process has crashed.
9027 */
9028 int mNumCrashes;
9029
9030 /**
9031 * Number of times the process has had an ANR.
9032 */
9033 int mNumAnrs;
9034
9035 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009036 * The amount of user time loaded from a previous save.
9037 */
9038 long mLoadedUserTime;
9039
9040 /**
9041 * The amount of system time loaded from a previous save.
9042 */
9043 long mLoadedSystemTime;
9044
9045 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009046 * The amount of foreground time loaded from a previous save.
9047 */
9048 long mLoadedForegroundTime;
9049
9050 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009051 * The number of times the process has started from a previous save.
9052 */
9053 int mLoadedStarts;
9054
9055 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009056 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009057 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009058 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009059
9060 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009061 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009062 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009063 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009064
9065 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009066 * The amount of user time when last unplugged.
9067 */
9068 long mUnpluggedUserTime;
9069
9070 /**
9071 * The amount of system time when last unplugged.
9072 */
9073 long mUnpluggedSystemTime;
9074
9075 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009076 * The amount of foreground time since unplugged.
9077 */
9078 long mUnpluggedForegroundTime;
9079
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009080 /**
9081 * The number of times the process has started before unplugged.
9082 */
9083 int mUnpluggedStarts;
9084
Dianne Hackborn61659e52014-07-09 16:13:01 -07009085 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009086 * Number of times the process has crashed before unplugged.
9087 */
9088 int mUnpluggedNumCrashes;
9089
9090 /**
9091 * Number of times the process has had an ANR before unplugged.
9092 */
9093 int mUnpluggedNumAnrs;
9094
Dianne Hackborn287952c2010-09-22 22:34:31 -07009095 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009096
Joe Onoratoabded112016-02-08 16:49:39 -08009097 public Proc(BatteryStatsImpl bsi, String name) {
9098 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009099 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08009100 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009101 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009102
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009103 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009104 mUnpluggedUserTime = mUserTime;
9105 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009106 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009107 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009108 mUnpluggedNumCrashes = mNumCrashes;
9109 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009110 }
9111
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009112 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009113 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009114
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009115 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009116 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009117 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009118 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009119
Dianne Hackborn287952c2010-09-22 22:34:31 -07009120 public int countExcessivePowers() {
9121 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009122 }
9123
Dianne Hackborn287952c2010-09-22 22:34:31 -07009124 public ExcessivePower getExcessivePower(int i) {
9125 if (mExcessivePower != null) {
9126 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009127 }
9128 return null;
9129 }
9130
Dianne Hackborn287952c2010-09-22 22:34:31 -07009131 public void addExcessiveCpu(long overTime, long usedTime) {
9132 if (mExcessivePower == null) {
9133 mExcessivePower = new ArrayList<ExcessivePower>();
9134 }
9135 ExcessivePower ew = new ExcessivePower();
9136 ew.type = ExcessivePower.TYPE_CPU;
9137 ew.overTime = overTime;
9138 ew.usedTime = usedTime;
9139 mExcessivePower.add(ew);
9140 }
9141
9142 void writeExcessivePowerToParcelLocked(Parcel out) {
9143 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009144 out.writeInt(0);
9145 return;
9146 }
9147
Dianne Hackborn287952c2010-09-22 22:34:31 -07009148 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009149 out.writeInt(N);
9150 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009151 ExcessivePower ew = mExcessivePower.get(i);
9152 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009153 out.writeLong(ew.overTime);
9154 out.writeLong(ew.usedTime);
9155 }
9156 }
9157
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009158 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009159 final int N = in.readInt();
9160 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009161 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009162 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009163 }
9164
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009165 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009166 throw new ParcelFormatException(
9167 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009168 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009169
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009170 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009171 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009172 ExcessivePower ew = new ExcessivePower();
9173 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009174 ew.overTime = in.readLong();
9175 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009176 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009177 }
9178 }
9179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009180 void writeToParcelLocked(Parcel out) {
9181 out.writeLong(mUserTime);
9182 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009183 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009184 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009185 out.writeInt(mNumCrashes);
9186 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009187 out.writeLong(mLoadedUserTime);
9188 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009189 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009190 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009191 out.writeInt(mLoadedNumCrashes);
9192 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 out.writeLong(mUnpluggedUserTime);
9194 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009195 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009196 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009197 out.writeInt(mUnpluggedNumCrashes);
9198 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009199 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009200 }
9201
9202 void readFromParcelLocked(Parcel in) {
9203 mUserTime = in.readLong();
9204 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009205 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009206 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009207 mNumCrashes = in.readInt();
9208 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009209 mLoadedUserTime = in.readLong();
9210 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009211 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009212 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009213 mLoadedNumCrashes = in.readInt();
9214 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009215 mUnpluggedUserTime = in.readLong();
9216 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009217 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009218 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009219 mUnpluggedNumCrashes = in.readInt();
9220 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009221 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009222 }
9223
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009224 public void addCpuTimeLocked(int utime, int stime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009225 mUserTime += utime;
9226 mSystemTime += stime;
9227 }
9228
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009229 public void addForegroundTimeLocked(long ttime) {
9230 mForegroundTime += ttime;
9231 }
9232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009233 public void incStartsLocked() {
9234 mStarts++;
9235 }
9236
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009237 public void incNumCrashesLocked() {
9238 mNumCrashes++;
9239 }
9240
9241 public void incNumAnrsLocked() {
9242 mNumAnrs++;
9243 }
9244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009245 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009246 public boolean isActive() {
9247 return mActive;
9248 }
9249
9250 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009251 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009252 long val = mUserTime;
9253 if (which == STATS_CURRENT) {
9254 val -= mLoadedUserTime;
9255 } else if (which == STATS_SINCE_UNPLUGGED) {
9256 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009257 }
9258 return val;
9259 }
9260
9261 @Override
9262 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009263 long val = mSystemTime;
9264 if (which == STATS_CURRENT) {
9265 val -= mLoadedSystemTime;
9266 } else if (which == STATS_SINCE_UNPLUGGED) {
9267 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009268 }
9269 return val;
9270 }
9271
9272 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009273 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009274 long val = mForegroundTime;
9275 if (which == STATS_CURRENT) {
9276 val -= mLoadedForegroundTime;
9277 } else if (which == STATS_SINCE_UNPLUGGED) {
9278 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009279 }
9280 return val;
9281 }
9282
9283 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009284 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009285 int val = mStarts;
9286 if (which == STATS_CURRENT) {
9287 val -= mLoadedStarts;
9288 } else if (which == STATS_SINCE_UNPLUGGED) {
9289 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009290 }
9291 return val;
9292 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009293
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009294 @Override
9295 public int getNumCrashes(int which) {
9296 int val = mNumCrashes;
9297 if (which == STATS_CURRENT) {
9298 val -= mLoadedNumCrashes;
9299 } else if (which == STATS_SINCE_UNPLUGGED) {
9300 val -= mUnpluggedNumCrashes;
9301 }
9302 return val;
9303 }
9304
9305 @Override
9306 public int getNumAnrs(int which) {
9307 int val = mNumAnrs;
9308 if (which == STATS_CURRENT) {
9309 val -= mLoadedNumAnrs;
9310 } else if (which == STATS_SINCE_UNPLUGGED) {
9311 val -= mUnpluggedNumAnrs;
9312 }
9313 return val;
9314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009315 }
9316
9317 /**
9318 * The statistics associated with a particular package.
9319 */
Joe Onoratoabded112016-02-08 16:49:39 -08009320 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9321 /**
9322 * BatteryStatsImpl that we are associated with.
9323 */
9324 protected BatteryStatsImpl mBsi;
9325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009326 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009327 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009328 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009329 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009330 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331
9332 /**
9333 * The statics we have collected for this package's services.
9334 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009335 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009336
Joe Onoratoabded112016-02-08 16:49:39 -08009337 public Pkg(BatteryStatsImpl bsi) {
9338 mBsi = bsi;
9339 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009340 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009341
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009342 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009343 }
9344
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009345 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009347
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009348 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009349 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009350 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009353 int numWA = in.readInt();
9354 mWakeupAlarms.clear();
9355 for (int i=0; i<numWA; i++) {
9356 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009357 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009359
9360 int numServs = in.readInt();
9361 mServiceStats.clear();
9362 for (int m = 0; m < numServs; m++) {
9363 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009364 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009365 mServiceStats.put(serviceName, serv);
9366
9367 serv.readFromParcelLocked(in);
9368 }
9369 }
9370
9371 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009372 int numWA = mWakeupAlarms.size();
9373 out.writeInt(numWA);
9374 for (int i=0; i<numWA; i++) {
9375 out.writeString(mWakeupAlarms.keyAt(i));
9376 mWakeupAlarms.valueAt(i).writeToParcel(out);
9377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009378
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009379 final int NS = mServiceStats.size();
9380 out.writeInt(NS);
9381 for (int i=0; i<NS; i++) {
9382 out.writeString(mServiceStats.keyAt(i));
9383 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009384 serv.writeToParcelLocked(out);
9385 }
9386 }
9387
9388 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009389 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9390 return mWakeupAlarms;
9391 }
9392
9393 public void noteWakeupAlarmLocked(String tag) {
9394 Counter c = mWakeupAlarms.get(tag);
9395 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009396 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009397 mWakeupAlarms.put(tag, c);
9398 }
9399 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009400 }
9401
9402 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009403 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9404 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009405 }
9406
9407 /**
9408 * The statistics associated with a particular service.
9409 */
Joe Onoratoabded112016-02-08 16:49:39 -08009410 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9411 /**
9412 * BatteryStatsImpl that we are associated with.
9413 */
9414 protected BatteryStatsImpl mBsi;
9415
9416 /**
9417 * The android package in which this service resides.
9418 */
9419 protected Pkg mPkg;
9420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009421 /**
9422 * Total time (ms in battery uptime) the service has been left started.
9423 */
Joe Onoratoabded112016-02-08 16:49:39 -08009424 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009425
9426 /**
9427 * If service has been started and not yet stopped, this is
9428 * when it was started.
9429 */
Joe Onoratoabded112016-02-08 16:49:39 -08009430 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009431
9432 /**
9433 * True if we are currently running.
9434 */
Joe Onoratoabded112016-02-08 16:49:39 -08009435 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436
9437 /**
9438 * Total number of times startService() has been called.
9439 */
Joe Onoratoabded112016-02-08 16:49:39 -08009440 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009441
9442 /**
9443 * Total time (ms in battery uptime) the service has been left launched.
9444 */
Joe Onoratoabded112016-02-08 16:49:39 -08009445 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009446
9447 /**
9448 * If service has been launched and not yet exited, this is
9449 * when it was launched (ms in battery uptime).
9450 */
Joe Onoratoabded112016-02-08 16:49:39 -08009451 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009452
9453 /**
9454 * True if we are currently launched.
9455 */
Joe Onoratoabded112016-02-08 16:49:39 -08009456 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009457
9458 /**
9459 * Total number times the service has been launched.
9460 */
Joe Onoratoabded112016-02-08 16:49:39 -08009461 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009462
9463 /**
9464 * The amount of time spent started loaded from a previous save
9465 * (ms in battery uptime).
9466 */
Joe Onoratoabded112016-02-08 16:49:39 -08009467 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009468
9469 /**
9470 * The number of starts loaded from a previous save.
9471 */
Joe Onoratoabded112016-02-08 16:49:39 -08009472 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009473
9474 /**
9475 * The number of launches loaded from a previous save.
9476 */
Joe Onoratoabded112016-02-08 16:49:39 -08009477 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009478
9479 /**
9480 * The amount of time spent started as of the last run (ms
9481 * in battery uptime).
9482 */
Joe Onoratoabded112016-02-08 16:49:39 -08009483 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009484
9485 /**
9486 * The number of starts as of the last run.
9487 */
Joe Onoratoabded112016-02-08 16:49:39 -08009488 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009489
9490 /**
9491 * The number of launches as of the last run.
9492 */
Joe Onoratoabded112016-02-08 16:49:39 -08009493 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009494
9495 /**
9496 * The amount of time spent started when last unplugged (ms
9497 * in battery uptime).
9498 */
Joe Onoratoabded112016-02-08 16:49:39 -08009499 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009500
9501 /**
9502 * The number of starts when last unplugged.
9503 */
Joe Onoratoabded112016-02-08 16:49:39 -08009504 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009505
9506 /**
9507 * The number of launches when last unplugged.
9508 */
Joe Onoratoabded112016-02-08 16:49:39 -08009509 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009510
Joe Onoratoabded112016-02-08 16:49:39 -08009511 /**
9512 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9513 */
9514 public Serv(BatteryStatsImpl bsi) {
9515 mBsi = bsi;
9516 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009517 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009518
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009519 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9520 long baseRealtime) {
9521 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009522 mUnpluggedStarts = mStarts;
9523 mUnpluggedLaunches = mLaunches;
9524 }
9525
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009526 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9527 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009528 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009529
Joe Onoratoabded112016-02-08 16:49:39 -08009530 /**
9531 * Remove this Serv as a listener from the time base.
9532 */
9533 public void detach() {
9534 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009535 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009536
Joe Onoratoabded112016-02-08 16:49:39 -08009537 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009538 mStartTime = in.readLong();
9539 mRunningSince = in.readLong();
9540 mRunning = in.readInt() != 0;
9541 mStarts = in.readInt();
9542 mLaunchedTime = in.readLong();
9543 mLaunchedSince = in.readLong();
9544 mLaunched = in.readInt() != 0;
9545 mLaunches = in.readInt();
9546 mLoadedStartTime = in.readLong();
9547 mLoadedStarts = in.readInt();
9548 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009549 mLastStartTime = 0;
9550 mLastStarts = 0;
9551 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009552 mUnpluggedStartTime = in.readLong();
9553 mUnpluggedStarts = in.readInt();
9554 mUnpluggedLaunches = in.readInt();
9555 }
9556
Joe Onoratoabded112016-02-08 16:49:39 -08009557 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009558 out.writeLong(mStartTime);
9559 out.writeLong(mRunningSince);
9560 out.writeInt(mRunning ? 1 : 0);
9561 out.writeInt(mStarts);
9562 out.writeLong(mLaunchedTime);
9563 out.writeLong(mLaunchedSince);
9564 out.writeInt(mLaunched ? 1 : 0);
9565 out.writeInt(mLaunches);
9566 out.writeLong(mLoadedStartTime);
9567 out.writeInt(mLoadedStarts);
9568 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569 out.writeLong(mUnpluggedStartTime);
9570 out.writeInt(mUnpluggedStarts);
9571 out.writeInt(mUnpluggedLaunches);
9572 }
9573
Joe Onoratoabded112016-02-08 16:49:39 -08009574 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009575 if (!mLaunched) return mLaunchedTime;
9576 return mLaunchedTime + batteryUptime - mLaunchedSince;
9577 }
9578
Joe Onoratoabded112016-02-08 16:49:39 -08009579 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009580 if (!mRunning) return mStartTime;
9581 return mStartTime + batteryUptime - mRunningSince;
9582 }
9583
9584 public void startLaunchedLocked() {
9585 if (!mLaunched) {
9586 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009587 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009588 mLaunched = true;
9589 }
9590 }
9591
9592 public void stopLaunchedLocked() {
9593 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009594 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009595 if (time > 0) {
9596 mLaunchedTime += time;
9597 } else {
9598 mLaunches--;
9599 }
9600 mLaunched = false;
9601 }
9602 }
9603
9604 public void startRunningLocked() {
9605 if (!mRunning) {
9606 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009607 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009608 mRunning = true;
9609 }
9610 }
9611
9612 public void stopRunningLocked() {
9613 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009614 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009615 if (time > 0) {
9616 mStartTime += time;
9617 } else {
9618 mStarts--;
9619 }
9620 mRunning = false;
9621 }
9622 }
9623
9624 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009625 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009626 }
9627
9628 @Override
9629 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009630 int val = mLaunches;
9631 if (which == STATS_CURRENT) {
9632 val -= mLoadedLaunches;
9633 } else if (which == STATS_SINCE_UNPLUGGED) {
9634 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009636 return val;
9637 }
9638
9639 @Override
9640 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009641 long val = getStartTimeToNowLocked(now);
9642 if (which == STATS_CURRENT) {
9643 val -= mLoadedStartTime;
9644 } else if (which == STATS_SINCE_UNPLUGGED) {
9645 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009647 return val;
9648 }
9649
9650 @Override
9651 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009652 int val = mStarts;
9653 if (which == STATS_CURRENT) {
9654 val -= mLoadedStarts;
9655 } else if (which == STATS_SINCE_UNPLUGGED) {
9656 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009657 }
9658
9659 return val;
9660 }
9661 }
9662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009663 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009664 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009665 }
9666 }
9667
9668 /**
9669 * Retrieve the statistics object for a particular process, creating
9670 * if needed.
9671 */
9672 public Proc getProcessStatsLocked(String name) {
9673 Proc ps = mProcessStats.get(name);
9674 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009675 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009676 mProcessStats.put(name, ps);
9677 }
9678
9679 return ps;
9680 }
9681
Dianne Hackborna8d10942015-11-19 17:55:19 -08009682 public void updateUidProcessStateLocked(int procState) {
9683 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009684 // Make special note of Foreground Services
9685 final boolean userAwareService =
9686 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009687 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009688
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009689 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9690 return;
9691 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009692
Bookatz867c0d72017-03-07 18:23:42 -08009693 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009694 if (mProcessState != uidRunningState) {
9695 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009696
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009697 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9698 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009699
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009700 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009701 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009702 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9703 mBsi.mOnBatteryTimeBase.isRunning(),
9704 mBsi.mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009705 }
9706 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9707 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9708 mBsi.mPendingUids.put(mUid, mProcessState);
9709 }
9710 } else {
9711 mBsi.mPendingUids.clear();
9712 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009713 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009714 mProcessState = uidRunningState;
9715 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9716 if (mProcessStateTimer[uidRunningState] == null) {
9717 makeProcessState(uidRunningState, null);
9718 }
9719 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9720 }
9721
9722 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9723 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009724 }
Bookatz867c0d72017-03-07 18:23:42 -08009725
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009726 if (userAwareService != mInForegroundService) {
9727 if (userAwareService) {
9728 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9729 } else {
9730 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9731 }
9732 mInForegroundService = userAwareService;
9733 }
Bookatz867c0d72017-03-07 18:23:42 -08009734 }
9735
Bookatzc8c44962017-05-11 12:12:54 -07009736 /** Whether to consider Uid to be in the background for background timebase purposes. */
9737 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009738 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9739 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009740 return mProcessState >= PROCESS_STATE_BACKGROUND;
9741 }
9742
9743 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9744 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9745 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9746 }
9747
9748 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9749 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9750 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009751 }
9752
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009753 public SparseArray<? extends Pid> getPidStats() {
9754 return mPids;
9755 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009756
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009757 public Pid getPidStatsLocked(int pid) {
9758 Pid p = mPids.get(pid);
9759 if (p == null) {
9760 p = new Pid();
9761 mPids.put(pid, p);
9762 }
9763 return p;
9764 }
9765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009766 /**
9767 * Retrieve the statistics object for a particular service, creating
9768 * if needed.
9769 */
9770 public Pkg getPackageStatsLocked(String name) {
9771 Pkg ps = mPackageStats.get(name);
9772 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009773 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009774 mPackageStats.put(name, ps);
9775 }
9776
9777 return ps;
9778 }
9779
9780 /**
9781 * Retrieve the statistics object for a particular service, creating
9782 * if needed.
9783 */
9784 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9785 Pkg ps = getPackageStatsLocked(pkg);
9786 Pkg.Serv ss = ps.mServiceStats.get(serv);
9787 if (ss == null) {
9788 ss = ps.newServiceStatsLocked();
9789 ps.mServiceStats.put(serv, ss);
9790 }
9791
9792 return ss;
9793 }
9794
Dianne Hackbornd953c532014-08-16 18:17:38 -07009795 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009796 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009797 timer.readSummaryFromParcelLocked(in);
9798 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009799 }
9800
Dianne Hackbornd953c532014-08-16 18:17:38 -07009801 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009802 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009803 timer.readSummaryFromParcelLocked(in);
9804 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009805 }
9806
Dianne Hackbornd953c532014-08-16 18:17:38 -07009807 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009808 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009809 mWakelockStats.add(wlName, wl);
9810 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009811 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009812 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009813 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009814 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009815 }
9816 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009817 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009818 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009819 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009820 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009822 }
9823
Bookatz867c0d72017-03-07 18:23:42 -08009824 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009825 Sensor se = mSensorStats.get(sensor);
9826 if (se == null) {
9827 if (!create) {
9828 return null;
9829 }
Joe Onoratoabded112016-02-08 16:49:39 -08009830 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009831 mSensorStats.put(sensor, se);
9832 }
Bookatz867c0d72017-03-07 18:23:42 -08009833 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009834 if (t != null) {
9835 return t;
9836 }
Joe Onoratoabded112016-02-08 16:49:39 -08009837 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009838 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009839 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009840 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009841 }
Bookatz867c0d72017-03-07 18:23:42 -08009842 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9843 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009844 se.mTimer = t;
9845 return t;
9846 }
9847
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009848 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009849 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009850 if (t != null) {
9851 t.startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08009852 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name,
9853 StatsLog.SYNC_STATE_CHANGED__STATE__ON);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009854 }
9855 }
9856
9857 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009858 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009859 if (t != null) {
9860 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009861 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08009862 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name,
9863 StatsLog.SYNC_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07009864 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009865 }
9866 }
9867
9868 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009869 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009870 if (t != null) {
9871 t.startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08009872 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08009873 name, StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__STARTED);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009874 }
9875 }
9876
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009877 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07009878 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009879 if (t != null) {
9880 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009881 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08009882 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08009883 name, StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__FINISHED);
Bookatzc1a050a2017-10-10 15:49:28 -07009884 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009885 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009886 if (mBsi.mOnBatteryTimeBase.isRunning()) {
9887 SparseIntArray types = mJobCompletions.get(name);
9888 if (types == null) {
9889 types = new SparseIntArray();
9890 mJobCompletions.put(name, types);
9891 }
9892 int last = types.get(stopReason, 0);
9893 types.put(stopReason, last + 1);
9894 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009895 }
9896
Bookatz5b5ec322017-05-26 09:40:38 -07009897 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
9898 if (wl == null) {
9899 return null;
9900 }
9901 switch (type) {
9902 case WAKE_TYPE_PARTIAL: {
9903 DualTimer t = wl.mTimerPartial;
9904 if (t == null) {
9905 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
9906 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
9907 mOnBatteryScreenOffBackgroundTimeBase);
9908 wl.mTimerPartial = t;
9909 }
9910 return t;
9911 }
9912 case WAKE_TYPE_FULL: {
9913 StopwatchTimer t = wl.mTimerFull;
9914 if (t == null) {
9915 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
9916 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
9917 wl.mTimerFull = t;
9918 }
9919 return t;
9920 }
9921 case WAKE_TYPE_WINDOW: {
9922 StopwatchTimer t = wl.mTimerWindow;
9923 if (t == null) {
9924 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
9925 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
9926 wl.mTimerWindow = t;
9927 }
9928 return t;
9929 }
9930 case WAKE_TYPE_DRAW: {
9931 StopwatchTimer t = wl.mTimerDraw;
9932 if (t == null) {
9933 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
9934 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
9935 wl.mTimerDraw = t;
9936 }
9937 return t;
9938 }
9939 default:
9940 throw new IllegalArgumentException("type=" + type);
9941 }
9942 }
9943
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009944 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009945 Wakelock wl = mWakelockStats.startObject(name);
9946 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07009947 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009948 }
Bookatzc8c44962017-05-11 12:12:54 -07009949 if (type == WAKE_TYPE_PARTIAL) {
9950 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
9951 if (pid >= 0) {
9952 Pid p = getPidStatsLocked(pid);
9953 if (p.mWakeNesting++ == 0) {
9954 p.mWakeStartMs = elapsedRealtimeMs;
9955 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -07009956 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009958 }
9959
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009960 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009961 Wakelock wl = mWakelockStats.stopObject(name);
9962 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -07009963 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
9964 wlt.stopRunningLocked(elapsedRealtimeMs);
9965 if (!wlt.isRunningLocked()) { // only tell statsd if truly stopped
Bookatzd6746242017-10-24 18:39:35 -07009966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009967 }
Bookatzc8c44962017-05-11 12:12:54 -07009968 if (type == WAKE_TYPE_PARTIAL) {
9969 if (mAggregatedPartialWakelockTimer != null) {
9970 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
9971 }
9972 if (pid >= 0) {
9973 Pid p = mPids.get(pid);
9974 if (p != null && p.mWakeNesting > 0) {
9975 if (p.mWakeNesting-- == 1) {
9976 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
9977 p.mWakeStartMs = 0;
9978 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08009979 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009980 }
9981 }
9982 }
9983
Dianne Hackborn287952c2010-09-22 22:34:31 -07009984 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
9985 Proc p = getProcessStatsLocked(proc);
9986 if (p != null) {
9987 p.addExcessiveCpu(overTime, usedTime);
9988 }
9989 }
9990
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009991 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009992 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -08009993 t.startRunningLocked(elapsedRealtimeMs);
Narayan Kamath32684dd2018-01-08 17:32:51 +00009994 if (sensor != Sensor.GPS) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08009995 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null, sensor,
Bookatz90867622018-01-31 15:05:57 -08009996 StatsLog.SENSOR_STATE_CHANGED__STATE__ON);
Bookatzc1a050a2017-10-10 15:49:28 -07009997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009998 }
9999
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010000 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010001 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -080010002 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010003 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010004 t.stopRunningLocked(elapsedRealtimeMs);
Narayan Kamath32684dd2018-01-08 17:32:51 +000010005 if (sensor != Sensor.GPS) {
10006 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -080010007 sensor, StatsLog.SENSOR_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -070010008 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010010 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010011
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010012 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010013 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010014 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010015
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010016 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010017 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010018 }
10019
10020 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -080010021 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010022 }
10023 }
10024
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010025 public long[] getCpuFreqs() {
10026 return mCpuFreqs;
10027 }
10028
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010029 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
10030 UserInfoProvider userInfoProvider) {
10031 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010032 }
10033
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010034 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
10035 PlatformIdleStateCallback cb,
10036 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -080010037 init(clocks);
10038
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010039 if (systemDir != null) {
10040 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
10041 new File(systemDir, "batterystats.bin.tmp"));
10042 } else {
10043 mFile = null;
10044 }
10045 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010046 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -080010047 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010048 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010049 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -080010050 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010051 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010052 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010053 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010054 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010055 }
Joe Onoratoabded112016-02-08 16:49:39 -080010056 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
10057 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
10058 mOnBatteryTimeBase);
10059 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
10060 mOnBatteryTimeBase);
10061 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
10062 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
10063 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
10064 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
10065 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10066 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
10067 mOnBatteryTimeBase);
10068 }
10069 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
10070 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010071 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010072 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010073 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010074 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010075 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010076 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
10077 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010078 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010079 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
10080 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10081 NUM_BT_TX_LEVELS);
10082 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10083 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -080010084 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
10085 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
10086 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010087 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010088 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
10089 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010090 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
10091 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -080010092 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
10093 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010094 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010095 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -070010096 mOnBatteryTimeBase);
10097 }
Joe Onoratoabded112016-02-08 16:49:39 -080010098 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10099 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
10100 mOnBatteryTimeBase);
10101 }
10102 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10103 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
10104 mOnBatteryTimeBase);
10105 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010106 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010107 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10108 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10109 mOnBatteryTimeBase);
10110 }
Joe Onoratoabded112016-02-08 16:49:39 -080010111 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10112 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10113 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10114 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10115 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010116 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010117 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010118 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10119 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010120 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010121 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010122 long uptime = mClocks.uptimeMillis() * 1000;
10123 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010124 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010125 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010126 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010127 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010128 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010129 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010130 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010131 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010132 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010133 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010134 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010135 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010136 }
10137
10138 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010139 this(new SystemClocks(), p);
10140 }
10141
10142 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10143 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010144 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010145 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010146 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010147 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010148 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010149 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010150 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010151 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010152 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010153 }
10154
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010155 public void setPowerProfileLocked(PowerProfile profile) {
10156 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010157
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010158 // We need to initialize the KernelCpuSpeedReaders to read from
10159 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10160 // information.
10161 final int numClusters = mPowerProfile.getNumCpuClusters();
10162 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10163 int firstCpuOfCluster = 0;
10164 for (int i = 0; i < numClusters; i++) {
10165 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10166 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10167 numSpeedSteps);
10168 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10169 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010170
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010171 if (mEstimatedBatteryCapacity == -1) {
10172 // Initialize the estimated battery capacity to a known preset one.
10173 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010174 }
10175 }
10176
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010177 public void setCallback(BatteryCallback cb) {
10178 mCallback = cb;
10179 }
10180
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010181 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010182 if (mPhoneSignalScanningTimer != null) {
10183 mPhoneSignalScanningTimer.setTimeout(timeout);
10184 }
10185 }
10186
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010187 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10188 mExternalSync = sync;
10189 }
10190
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010191 public void updateDailyDeadlineLocked() {
10192 // Get the current time.
10193 long currentTime = mDailyStartTime = System.currentTimeMillis();
10194 Calendar calDeadline = Calendar.getInstance();
10195 calDeadline.setTimeInMillis(currentTime);
10196
10197 // Move time up to the next day, ranging from 1am to 3pm.
10198 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10199 calDeadline.set(Calendar.MILLISECOND, 0);
10200 calDeadline.set(Calendar.SECOND, 0);
10201 calDeadline.set(Calendar.MINUTE, 0);
10202 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10203 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10204 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10205 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10206 }
10207
10208 public void recordDailyStatsIfNeededLocked(boolean settled) {
10209 long currentTime = System.currentTimeMillis();
10210 if (currentTime >= mNextMaxDailyDeadline) {
10211 recordDailyStatsLocked();
10212 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10213 recordDailyStatsLocked();
10214 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10215 recordDailyStatsLocked();
10216 }
10217 }
10218
10219 public void recordDailyStatsLocked() {
10220 DailyItem item = new DailyItem();
10221 item.mStartTime = mDailyStartTime;
10222 item.mEndTime = System.currentTimeMillis();
10223 boolean hasData = false;
10224 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10225 hasData = true;
10226 item.mDischargeSteps = new LevelStepTracker(
10227 mDailyDischargeStepTracker.mNumStepDurations,
10228 mDailyDischargeStepTracker.mStepDurations);
10229 }
10230 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10231 hasData = true;
10232 item.mChargeSteps = new LevelStepTracker(
10233 mDailyChargeStepTracker.mNumStepDurations,
10234 mDailyChargeStepTracker.mStepDurations);
10235 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010236 if (mDailyPackageChanges != null) {
10237 hasData = true;
10238 item.mPackageChanges = mDailyPackageChanges;
10239 mDailyPackageChanges = null;
10240 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010241 mDailyDischargeStepTracker.init();
10242 mDailyChargeStepTracker.init();
10243 updateDailyDeadlineLocked();
10244
10245 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010246 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010247 mDailyItems.add(item);
10248 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10249 mDailyItems.remove(0);
10250 }
10251 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10252 try {
10253 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010254 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010255 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010256 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010257 BackgroundThread.getHandler().post(new Runnable() {
10258 @Override
10259 public void run() {
10260 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010261 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010262 FileOutputStream stream = null;
10263 try {
10264 stream = mDailyFile.startWrite();
10265 memStream.writeTo(stream);
10266 stream.flush();
10267 FileUtils.sync(stream);
10268 stream.close();
10269 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010270 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
10271 "batterystats-daily",
10272 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010273 } catch (IOException e) {
10274 Slog.w("BatteryStats",
10275 "Error writing battery daily items", e);
10276 mDailyFile.failWrite(stream);
10277 }
10278 }
10279 }
10280 });
10281 } catch (IOException e) {
10282 }
10283 }
10284 }
10285
10286 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10287 StringBuilder sb = new StringBuilder(64);
10288 out.startDocument(null, true);
10289 out.startTag(null, "daily-items");
10290 for (int i=0; i<mDailyItems.size(); i++) {
10291 final DailyItem dit = mDailyItems.get(i);
10292 out.startTag(null, "item");
10293 out.attribute(null, "start", Long.toString(dit.mStartTime));
10294 out.attribute(null, "end", Long.toString(dit.mEndTime));
10295 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10296 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010297 if (dit.mPackageChanges != null) {
10298 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10299 PackageChange pc = dit.mPackageChanges.get(j);
10300 if (pc.mUpdate) {
10301 out.startTag(null, "upd");
10302 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010303 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010304 out.endTag(null, "upd");
10305 } else {
10306 out.startTag(null, "rem");
10307 out.attribute(null, "pkg", pc.mPackageName);
10308 out.endTag(null, "rem");
10309 }
10310 }
10311 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010312 out.endTag(null, "item");
10313 }
10314 out.endTag(null, "daily-items");
10315 out.endDocument();
10316 }
10317
10318 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10319 StringBuilder tmpBuilder) throws IOException {
10320 if (steps != null) {
10321 out.startTag(null, tag);
10322 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10323 for (int i=0; i<steps.mNumStepDurations; i++) {
10324 out.startTag(null, "s");
10325 tmpBuilder.setLength(0);
10326 steps.encodeEntryAt(i, tmpBuilder);
10327 out.attribute(null, "v", tmpBuilder.toString());
10328 out.endTag(null, "s");
10329 }
10330 out.endTag(null, tag);
10331 }
10332 }
10333
10334 public void readDailyStatsLocked() {
10335 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10336 mDailyItems.clear();
10337 FileInputStream stream;
10338 try {
10339 stream = mDailyFile.openRead();
10340 } catch (FileNotFoundException e) {
10341 return;
10342 }
10343 try {
10344 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010345 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010346 readDailyItemsLocked(parser);
10347 } catch (XmlPullParserException e) {
10348 } finally {
10349 try {
10350 stream.close();
10351 } catch (IOException e) {
10352 }
10353 }
10354 }
10355
10356 private void readDailyItemsLocked(XmlPullParser parser) {
10357 try {
10358 int type;
10359 while ((type = parser.next()) != XmlPullParser.START_TAG
10360 && type != XmlPullParser.END_DOCUMENT) {
10361 ;
10362 }
10363
10364 if (type != XmlPullParser.START_TAG) {
10365 throw new IllegalStateException("no start tag found");
10366 }
10367
10368 int outerDepth = parser.getDepth();
10369 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10370 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10371 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10372 continue;
10373 }
10374
10375 String tagName = parser.getName();
10376 if (tagName.equals("item")) {
10377 readDailyItemTagLocked(parser);
10378 } else {
10379 Slog.w(TAG, "Unknown element under <daily-items>: "
10380 + parser.getName());
10381 XmlUtils.skipCurrentTag(parser);
10382 }
10383 }
10384
10385 } catch (IllegalStateException e) {
10386 Slog.w(TAG, "Failed parsing daily " + e);
10387 } catch (NullPointerException e) {
10388 Slog.w(TAG, "Failed parsing daily " + e);
10389 } catch (NumberFormatException e) {
10390 Slog.w(TAG, "Failed parsing daily " + e);
10391 } catch (XmlPullParserException e) {
10392 Slog.w(TAG, "Failed parsing daily " + e);
10393 } catch (IOException e) {
10394 Slog.w(TAG, "Failed parsing daily " + e);
10395 } catch (IndexOutOfBoundsException e) {
10396 Slog.w(TAG, "Failed parsing daily " + e);
10397 }
10398 }
10399
10400 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10401 XmlPullParserException, IOException {
10402 DailyItem dit = new DailyItem();
10403 String attr = parser.getAttributeValue(null, "start");
10404 if (attr != null) {
10405 dit.mStartTime = Long.parseLong(attr);
10406 }
10407 attr = parser.getAttributeValue(null, "end");
10408 if (attr != null) {
10409 dit.mEndTime = Long.parseLong(attr);
10410 }
10411 int outerDepth = parser.getDepth();
10412 int type;
10413 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10414 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10415 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10416 continue;
10417 }
10418
10419 String tagName = parser.getName();
10420 if (tagName.equals("dis")) {
10421 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10422 } else if (tagName.equals("chg")) {
10423 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010424 } else if (tagName.equals("upd")) {
10425 if (dit.mPackageChanges == null) {
10426 dit.mPackageChanges = new ArrayList<>();
10427 }
10428 PackageChange pc = new PackageChange();
10429 pc.mUpdate = true;
10430 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10431 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010432 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010433 dit.mPackageChanges.add(pc);
10434 XmlUtils.skipCurrentTag(parser);
10435 } else if (tagName.equals("rem")) {
10436 if (dit.mPackageChanges == null) {
10437 dit.mPackageChanges = new ArrayList<>();
10438 }
10439 PackageChange pc = new PackageChange();
10440 pc.mUpdate = false;
10441 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10442 dit.mPackageChanges.add(pc);
10443 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010444 } else {
10445 Slog.w(TAG, "Unknown element under <item>: "
10446 + parser.getName());
10447 XmlUtils.skipCurrentTag(parser);
10448 }
10449 }
10450 mDailyItems.add(dit);
10451 }
10452
10453 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10454 String tag)
10455 throws NumberFormatException, XmlPullParserException, IOException {
10456 final String numAttr = parser.getAttributeValue(null, "n");
10457 if (numAttr == null) {
10458 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10459 XmlUtils.skipCurrentTag(parser);
10460 return;
10461 }
10462 final int num = Integer.parseInt(numAttr);
10463 LevelStepTracker steps = new LevelStepTracker(num);
10464 if (isCharge) {
10465 dit.mChargeSteps = steps;
10466 } else {
10467 dit.mDischargeSteps = steps;
10468 }
10469 int i = 0;
10470 int outerDepth = parser.getDepth();
10471 int type;
10472 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10473 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10474 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10475 continue;
10476 }
10477
10478 String tagName = parser.getName();
10479 if ("s".equals(tagName)) {
10480 if (i < num) {
10481 String valueAttr = parser.getAttributeValue(null, "v");
10482 if (valueAttr != null) {
10483 steps.decodeEntryAt(i, valueAttr);
10484 i++;
10485 }
10486 }
10487 } else {
10488 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10489 + parser.getName());
10490 XmlUtils.skipCurrentTag(parser);
10491 }
10492 }
10493 steps.mNumStepDurations = i;
10494 }
10495
10496 @Override
10497 public DailyItem getDailyItemLocked(int daysAgo) {
10498 int index = mDailyItems.size()-1-daysAgo;
10499 return index >= 0 ? mDailyItems.get(index) : null;
10500 }
10501
10502 @Override
10503 public long getCurrentDailyStartTime() {
10504 return mDailyStartTime;
10505 }
10506
10507 @Override
10508 public long getNextMinDailyDeadline() {
10509 return mNextMinDailyDeadline;
10510 }
10511
10512 @Override
10513 public long getNextMaxDailyDeadline() {
10514 return mNextMaxDailyDeadline;
10515 }
10516
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010517 @Override
10518 public boolean startIteratingOldHistoryLocked() {
10519 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10520 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010521 if ((mHistoryIterator = mHistory) == null) {
10522 return false;
10523 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010524 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010525 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010526 mReadOverflow = false;
10527 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010528 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010529 }
10530
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010531 @Override
10532 public boolean getNextOldHistoryLocked(HistoryItem out) {
10533 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10534 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010535 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010536 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010537 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010538 HistoryItem cur = mHistoryIterator;
10539 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010540 if (!mReadOverflow && !end) {
10541 Slog.w(TAG, "Old history ends before new history!");
10542 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010543 return false;
10544 }
10545 out.setTo(cur);
10546 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010547 if (!mReadOverflow) {
10548 if (end) {
10549 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010550 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010551 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010552 pw.println("Histories differ!");
10553 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010554 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010555 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010556 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10557 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010558 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010559 }
10560 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010561 return true;
10562 }
10563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010564 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010565 public void finishIteratingOldHistoryLocked() {
10566 mIteratingHistory = false;
10567 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010568 mHistoryIterator = null;
10569 }
10570
10571 public int getHistoryTotalSize() {
10572 return MAX_HISTORY_BUFFER;
10573 }
10574
10575 public int getHistoryUsedSize() {
10576 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010577 }
10578
10579 @Override
10580 public boolean startIteratingHistoryLocked() {
10581 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10582 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010583 if (mHistoryBuffer.dataSize() <= 0) {
10584 return false;
10585 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010586 mHistoryBuffer.setDataPosition(0);
10587 mReadOverflow = false;
10588 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010589 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10590 mReadHistoryUids = new int[mHistoryTagPool.size()];
10591 mReadHistoryChars = 0;
10592 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10593 final HistoryTag tag = ent.getKey();
10594 final int idx = ent.getValue();
10595 mReadHistoryStrings[idx] = tag.string;
10596 mReadHistoryUids[idx] = tag.uid;
10597 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010598 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010599 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010600 }
10601
10602 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010603 public int getHistoryStringPoolSize() {
10604 return mReadHistoryStrings.length;
10605 }
10606
10607 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010608 public int getHistoryStringPoolBytes() {
10609 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10610 // Each string character is 2 bytes.
10611 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10612 }
10613
10614 @Override
10615 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010616 return mReadHistoryStrings[index];
10617 }
10618
10619 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010620 public int getHistoryTagPoolUid(int index) {
10621 return mReadHistoryUids[index];
10622 }
10623
10624 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010625 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010626 final int pos = mHistoryBuffer.dataPosition();
10627 if (pos == 0) {
10628 out.clear();
10629 }
10630 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010631 if (end) {
10632 return false;
10633 }
10634
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010635 final long lastRealtime = out.time;
10636 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010637 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010638 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10639 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010640 out.currentTime = lastWalltime + (out.time - lastRealtime);
10641 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010642 return true;
10643 }
10644
10645 @Override
10646 public void finishIteratingHistoryLocked() {
10647 mIteratingHistory = false;
10648 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010649 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010650 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010651
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010652 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010653 public long getHistoryBaseTime() {
10654 return mHistoryBaseTime;
10655 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010656
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010657 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010658 public int getStartCount() {
10659 return mStartCount;
10660 }
10661
10662 public boolean isOnBattery() {
10663 return mOnBattery;
10664 }
10665
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010666 public boolean isCharging() {
10667 return mCharging;
10668 }
10669
Mike Mac2f518a2017-09-19 16:06:03 -070010670 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010671 return state == Display.STATE_ON || state == Display.STATE_VR
10672 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010673 }
10674
10675 public boolean isScreenOff(int state) {
10676 return state == Display.STATE_OFF;
10677 }
10678
10679 public boolean isScreenDoze(int state) {
10680 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010681 }
10682
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010683 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010684 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010685 mOnBatteryTimeBase.init(uptime, realtime);
10686 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010687 mRealtime = 0;
10688 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010689 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010690 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010691 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010692
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010693 void initDischarge() {
10694 mLowDischargeAmountSinceCharge = 0;
10695 mHighDischargeAmountSinceCharge = 0;
10696 mDischargeAmountScreenOn = 0;
10697 mDischargeAmountScreenOnSinceCharge = 0;
10698 mDischargeAmountScreenOff = 0;
10699 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010700 mDischargeAmountScreenDoze = 0;
10701 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010702 mDischargeStepTracker.init();
10703 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010704 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010705 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010706 mDischargeLightDozeCounter.reset(false);
10707 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010708 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010709 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010710
10711 public void resetAllStatsCmdLocked() {
10712 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010713 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010714 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010715 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010716 long realtime = mSecRealtime * 1000;
10717 mDischargeStartLevel = mHistoryCur.batteryLevel;
10718 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010719 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010720 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10721 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010722 mOnBatteryTimeBase.reset(uptime, realtime);
10723 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10724 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010725 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010726 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010727 mDischargeScreenDozeUnplugLevel = 0;
10728 mDischargeScreenOffUnplugLevel = 0;
10729 } else if (isScreenDoze(mScreenState)) {
10730 mDischargeScreenOnUnplugLevel = 0;
10731 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010732 mDischargeScreenOffUnplugLevel = 0;
10733 } else {
10734 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010735 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010736 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10737 }
10738 mDischargeAmountScreenOn = 0;
10739 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010740 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010741 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010742 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010743 }
10744
10745 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010746 final long uptimeMillis = mClocks.uptimeMillis();
10747 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010748 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010749 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010750 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010751 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010752 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010753 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010754 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010755
10756 if (mPowerProfile != null) {
10757 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10758 } else {
10759 mEstimatedBatteryCapacity = -1;
10760 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010761 mMinLearnedBatteryCapacity = -1;
10762 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010763 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010764 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010765 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010766 mLongestLightIdleTime = 0;
10767 mLongestFullIdleTime = 0;
10768 mDeviceIdleModeLightTimer.reset(false);
10769 mDeviceIdleModeFullTimer.reset(false);
10770 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010771 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010772 mPhoneOnTimer.reset(false);
10773 mAudioOnTimer.reset(false);
10774 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010775 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010776 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010777 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010778 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010779 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010780 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010781 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010782 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010783 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010784 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010785 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010786 mNetworkByteActivityCounters[i].reset(false);
10787 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010788 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010789 mMobileRadioActiveTimer.reset(false);
10790 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010791 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010792 mMobileRadioActiveUnknownTime.reset(false);
10793 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010794 mWifiOnTimer.reset(false);
10795 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010796 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010797 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010798 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010799 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10800 mWifiSupplStateTimer[i].reset(false);
10801 }
10802 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10803 mWifiSignalStrengthsTimer[i].reset(false);
10804 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010805 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010806 mWifiActiveTimer.reset(false);
10807 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010808 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10809 mGpsSignalQualityTimer[i].reset(false);
10810 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010811 mBluetoothActivity.reset(false);
10812 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010813 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010814
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010815 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010816 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010817 mUidStats.remove(mUidStats.keyAt(i));
10818 i--;
10819 }
10820 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010821
Bookatz50df7112017-08-04 14:53:26 -070010822 if (mRpmStats.size() > 0) {
10823 for (SamplingTimer timer : mRpmStats.values()) {
10824 mOnBatteryTimeBase.remove(timer);
10825 }
10826 mRpmStats.clear();
10827 }
10828 if (mScreenOffRpmStats.size() > 0) {
10829 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10830 mOnBatteryScreenOffTimeBase.remove(timer);
10831 }
10832 mScreenOffRpmStats.clear();
10833 }
10834
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010835 if (mKernelWakelockStats.size() > 0) {
10836 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010837 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010838 }
10839 mKernelWakelockStats.clear();
10840 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010841
James Carr3a226052016-07-01 14:49:52 -070010842 if (mKernelMemoryStats.size() > 0) {
10843 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10844 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10845 }
10846 mKernelMemoryStats.clear();
10847 }
10848
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010849 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010850 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10851 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010852 }
10853 mWakeupReasonStats.clear();
10854 }
10855
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010856 mLastHistoryStepDetails = null;
10857 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10858 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10859 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10860 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10861 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10862 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10863 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
10864 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
10865 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
10866 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
10867
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010868 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010869
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010870 clearHistoryLocked();
10871 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010872
Dianne Hackborn40c87252014-03-19 16:55:40 -070010873 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010874 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010875 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
10876 // Not recording process starts/stops.
10877 continue;
10878 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010879 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010880 if (active == null) {
10881 continue;
10882 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010883 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
10884 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010885 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070010886 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
10887 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010888 }
10889 }
10890 }
10891 }
10892
Mike Mac2f518a2017-09-19 16:06:03 -070010893 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
10894 updateOldDischargeScreenLevelLocked(oldState);
10895 updateNewDischargeScreenLevelLocked(newState);
10896 }
10897
10898 private void updateOldDischargeScreenLevelLocked(int state) {
10899 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010900 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
10901 if (diff > 0) {
10902 mDischargeAmountScreenOn += diff;
10903 mDischargeAmountScreenOnSinceCharge += diff;
10904 }
Mike Mac2f518a2017-09-19 16:06:03 -070010905 } else if (isScreenDoze(state)) {
10906 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
10907 if (diff > 0) {
10908 mDischargeAmountScreenDoze += diff;
10909 mDischargeAmountScreenDozeSinceCharge += diff;
10910 }
10911 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010912 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
10913 if (diff > 0) {
10914 mDischargeAmountScreenOff += diff;
10915 mDischargeAmountScreenOffSinceCharge += diff;
10916 }
10917 }
Mike Mac2f518a2017-09-19 16:06:03 -070010918 }
10919
10920 private void updateNewDischargeScreenLevelLocked(int state) {
10921 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010922 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
10923 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010924 mDischargeScreenDozeUnplugLevel = 0;
10925 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010926 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010927 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
10928 mDischargeScreenOffUnplugLevel = 0;
10929 } else if (isScreenOff(state)) {
10930 mDischargeScreenOnUnplugLevel = 0;
10931 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010932 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
10933 }
10934 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010935
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010936 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010937 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070010938 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010939 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010940 }
10941
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010942 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
10943 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
10944
10945 private final Object mWifiNetworkLock = new Object();
10946
10947 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010948 private String[] mWifiIfaces = EmptyArray.STRING;
10949
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010950 @GuardedBy("mWifiNetworkLock")
10951 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010952
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010953 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010954
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010955 @GuardedBy("mModemNetworkLock")
10956 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010957
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010958 @GuardedBy("mModemNetworkLock")
10959 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
10960
10961 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
10962 try {
10963 if (!ArrayUtils.isEmpty(ifaces)) {
10964 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
10965 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
10966 }
10967 } catch (IOException e) {
10968 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010969 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010970 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010971 }
10972
Chenjie Yu89083392018-01-11 14:53:31 -080010973 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010974 * Distribute WiFi energy info and network traffic to apps.
10975 * @param info The energy information from the WiFi controller.
10976 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010977 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010978 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010979 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010980 }
10981
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010982 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070010983 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010984 synchronized (mWifiNetworkLock) {
10985 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
10986 if (latestStats != null) {
10987 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
10988 mNetworkStatsPool.acquire());
10989 mNetworkStatsPool.release(mLastWifiNetworkStats);
10990 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070010991 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010992 }
10993
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010994 synchronized (this) {
10995 if (!mOnBatteryInternal) {
10996 if (delta != null) {
10997 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010998 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010999 return;
11000 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011001
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011002 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
11003 SparseLongArray rxPackets = new SparseLongArray();
11004 SparseLongArray txPackets = new SparseLongArray();
11005 long totalTxPackets = 0;
11006 long totalRxPackets = 0;
11007 if (delta != null) {
11008 NetworkStats.Entry entry = new NetworkStats.Entry();
11009 final int size = delta.size();
11010 for (int i = 0; i < size; i++) {
11011 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011012
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011013 if (DEBUG_ENERGY) {
11014 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
11015 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11016 + " txPackets=" + entry.txPackets);
11017 }
11018
11019 if (entry.rxBytes == 0 && entry.txBytes == 0) {
11020 // Skip the lookup below since there is no work to do.
11021 continue;
11022 }
11023
11024 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11025 if (entry.rxBytes != 0) {
11026 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011027 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011028 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11029 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
11030 entry.rxPackets);
11031 }
11032 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11033 entry.rxBytes);
11034 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11035 entry.rxPackets);
11036
11037 rxPackets.put(u.getUid(), entry.rxPackets);
11038
11039 // Sum the total number of packets so that the Rx Power can
11040 // be evenly distributed amongst the apps.
11041 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011042 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011043
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011044 if (entry.txBytes != 0) {
11045 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011046 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011047 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11048 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
11049 entry.txPackets);
11050 }
11051 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11052 entry.txBytes);
11053 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11054 entry.txPackets);
11055
11056 txPackets.put(u.getUid(), entry.txPackets);
11057
11058 // Sum the total number of packets so that the Tx Power can
11059 // be evenly distributed amongst the apps.
11060 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011061 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080011062 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011063 mNetworkStatsPool.release(delta);
11064 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070011065 }
11066
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011067 if (info != null) {
11068 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070011069
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011070 // Measured in mAms
11071 final long txTimeMs = info.getControllerTxTimeMillis();
11072 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080011073 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011074 final long idleTimeMs = info.getControllerIdleTimeMillis();
11075 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011076
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011077 long leftOverRxTimeMs = rxTimeMs;
11078 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011079
Adam Lesinskie08af192015-03-25 16:42:59 -070011080 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011081 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
11082 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11083 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11084 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
11085 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080011086 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011087 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011088
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011089 long totalWifiLockTimeMs = 0;
11090 long totalScanTimeMs = 0;
11091
11092 // On the first pass, collect some totals so that we can normalize power
11093 // calculations if we need to.
11094 final int uidStatsSize = mUidStats.size();
11095 for (int i = 0; i < uidStatsSize; i++) {
11096 final Uid uid = mUidStats.valueAt(i);
11097
11098 // Sum the total scan power for all apps.
11099 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
11100 elapsedRealtimeMs * 1000) / 1000;
11101
11102 // Sum the total time holding wifi lock for all apps.
11103 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11104 elapsedRealtimeMs * 1000) / 1000;
11105 }
11106
11107 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
11108 Slog.d(TAG,
11109 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
11110 + rxTimeMs + " ms). Normalizing scan time.");
11111 }
11112 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11113 Slog.d(TAG,
11114 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11115 + txTimeMs + " ms). Normalizing scan time.");
11116 }
11117
11118 // Actually assign and distribute power usage to apps.
11119 for (int i = 0; i < uidStatsSize; i++) {
11120 final Uid uid = mUidStats.valueAt(i);
11121
11122 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11123 elapsedRealtimeMs * 1000) / 1000;
11124 if (scanTimeSinceMarkMs > 0) {
11125 // Set the new mark so that next time we get new data since this point.
11126 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11127
11128 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11129 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11130
11131 // Our total scan time is more than the reported Tx/Rx time.
11132 // This is possible because the cost of a scan is approximate.
11133 // Let's normalize the result so that we evenly blame each app
11134 // scanning.
11135 //
11136 // This means that we may have apps that transmitted/received packets not be
11137 // blamed for this, but this is fine as scans are relatively more expensive.
11138 if (totalScanTimeMs > rxTimeMs) {
11139 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11140 totalScanTimeMs;
11141 }
11142 if (totalScanTimeMs > txTimeMs) {
11143 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11144 totalScanTimeMs;
11145 }
11146
11147 if (DEBUG_ENERGY) {
11148 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11149 + scanRxTimeSinceMarkMs + " ms Tx:"
11150 + scanTxTimeSinceMarkMs + " ms)");
11151 }
11152
11153 ControllerActivityCounterImpl activityCounter =
11154 uid.getOrCreateWifiControllerActivityLocked();
11155 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11156 activityCounter.getTxTimeCounters()[0].addCountLocked(
11157 scanTxTimeSinceMarkMs);
11158 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11159 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11160 }
11161
11162 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11163 // lock.
11164 final long wifiLockTimeSinceMarkMs =
11165 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11166 elapsedRealtimeMs * 1000) / 1000;
11167 if (wifiLockTimeSinceMarkMs > 0) {
11168 // Set the new mark so that next time we get new data since this point.
11169 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11170
11171 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11172 / totalWifiLockTimeMs;
11173 if (DEBUG_ENERGY) {
11174 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11175 + myIdleTimeMs + " ms");
11176 }
11177 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11178 .addCountLocked(myIdleTimeMs);
11179 }
11180 }
11181
Adam Lesinskie08af192015-03-25 16:42:59 -070011182 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011183 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11184 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011185 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011186
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011187 // Distribute the remaining Tx power appropriately between all apps that transmitted
11188 // packets.
11189 for (int i = 0; i < txPackets.size(); i++) {
11190 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11191 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11192 / totalTxPackets;
11193 if (DEBUG_ENERGY) {
11194 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11195 }
11196 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11197 .addCountLocked(myTxTimeMs);
11198 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011199
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011200 // Distribute the remaining Rx power appropriately between all apps that received
11201 // packets.
11202 for (int i = 0; i < rxPackets.size(); i++) {
11203 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11204 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11205 / totalRxPackets;
11206 if (DEBUG_ENERGY) {
11207 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11208 }
11209 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11210 .addCountLocked(myRxTimeMs);
11211 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011212
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011213 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11214
11215
11216 // Update WiFi controller stats.
11217 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11218 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11219 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011220 mWifiActivity.getScanTimeCounter().addCountLocked(
11221 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011222 mWifiActivity.getIdleTimeCounter().addCountLocked(
11223 info.getControllerIdleTimeMillis());
11224
11225 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11226 final double opVolt = mPowerProfile.getAveragePower(
11227 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11228 if (opVolt != 0) {
11229 // We store the power drain as mAms.
11230 mWifiActivity.getPowerCounter().addCountLocked(
11231 (long) (info.getControllerEnergyUsed() / opVolt));
11232 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011233 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011234 }
11235 }
11236
Chenjie Yu89083392018-01-11 14:53:31 -080011237 private ModemActivityInfo mLastModemActivityInfo =
11238 new ModemActivityInfo(0, 0, 0, new int[0], 0, 0);
11239
Chenjie Yua54e54d2018-02-14 20:12:52 -080011240 private ModemActivityInfo getDeltaModemActivityInfo(ModemActivityInfo activityInfo) {
11241 if (activityInfo == null) {
11242 return null;
11243 }
11244 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
11245 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
11246 txTimeMs[i] = activityInfo.getTxTimeMillis()[i]
11247 - mLastModemActivityInfo.getTxTimeMillis()[i];
11248 }
11249 ModemActivityInfo deltaInfo = new ModemActivityInfo(activityInfo.getTimestamp(),
11250 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis(),
11251 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis(),
11252 txTimeMs,
11253 activityInfo.getRxTimeMillis() - mLastModemActivityInfo.getRxTimeMillis(),
11254 activityInfo.getEnergyUsed() - mLastModemActivityInfo.getEnergyUsed());
11255 mLastModemActivityInfo = activityInfo;
11256 return deltaInfo;
11257 }
11258
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011259 /**
11260 * Distribute Cell radio energy info and network traffic to apps.
11261 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011262 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011263 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011264 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011265 }
Chenjie Yua54e54d2018-02-14 20:12:52 -080011266 ModemActivityInfo deltaInfo = getDeltaModemActivityInfo(activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011267
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011268 // Add modem tx power to history.
Chenjie Yua54e54d2018-02-14 20:12:52 -080011269 addModemTxPowerToHistory(deltaInfo);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011270
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011271 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011272 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011273 synchronized (mModemNetworkLock) {
11274 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11275 if (latestStats != null) {
11276 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11277 mNetworkStatsPool.acquire());
11278 mNetworkStatsPool.release(mLastModemNetworkStats);
11279 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011280 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011281 }
11282
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011283 synchronized (this) {
11284 if (!mOnBatteryInternal) {
11285 if (delta != null) {
11286 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011287 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011288 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011289 }
11290
Chenjie Yua54e54d2018-02-14 20:12:52 -080011291 if (deltaInfo != null) {
Siddharth Ray2038af82018-01-17 17:40:26 -080011292 mHasModemReporting = true;
11293 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011294 deltaInfo.getIdleTimeMillis());
Siddharth Rayed754702018-02-15 12:44:37 -080011295 mModemActivity.getSleepTimeCounter().addCountLocked(
11296 deltaInfo.getSleepTimeMillis());
Chenjie Yua54e54d2018-02-14 20:12:52 -080011297 mModemActivity.getRxTimeCounter().addCountLocked(deltaInfo.getRxTimeMillis());
Siddharth Ray2038af82018-01-17 17:40:26 -080011298 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11299 mModemActivity.getTxTimeCounters()[lvl]
Chenjie Yua54e54d2018-02-14 20:12:52 -080011300 .addCountLocked(deltaInfo.getTxTimeMillis()[lvl]);
Siddharth Ray2038af82018-01-17 17:40:26 -080011301 }
11302
11303 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11304 final double opVolt = mPowerProfile.getAveragePower(
11305 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11306 if (opVolt != 0) {
11307 double energyUsed =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011308 deltaInfo.getSleepTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011309 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011310 + deltaInfo.getIdleTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011311 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011312 + deltaInfo.getRxTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011313 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chenjie Yua54e54d2018-02-14 20:12:52 -080011314 int[] txTimeMs = deltaInfo.getTxTimeMillis();
Chenjie Yu89083392018-01-11 14:53:31 -080011315 for (int i = 0; i < Math.min(txTimeMs.length,
Chenjie Yua54e54d2018-02-14 20:12:52 -080011316 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chenjie Yu89083392018-01-11 14:53:31 -080011317 energyUsed += txTimeMs[i] * mPowerProfile.getAveragePower(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011318 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
Siddharth Ray2038af82018-01-17 17:40:26 -080011319 }
11320
11321 // We store the power drain as mAms.
11322 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11323 }
11324 }
11325
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011326 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011327 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11328 elapsedRealtimeMs * 1000);
11329 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11330
11331 long totalRxPackets = 0;
11332 long totalTxPackets = 0;
11333 if (delta != null) {
11334 NetworkStats.Entry entry = new NetworkStats.Entry();
11335 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011336 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011337 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011338 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11339 continue;
11340 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011341
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011342 if (DEBUG_ENERGY) {
11343 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11344 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11345 + " txPackets=" + entry.txPackets);
11346 }
11347
11348 totalRxPackets += entry.rxPackets;
11349 totalTxPackets += entry.txPackets;
11350
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011351 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011352 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11353 entry.rxPackets);
11354 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11355 entry.txPackets);
11356 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11357 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11358 entry.rxBytes, entry.rxPackets);
11359 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11360 entry.txBytes, entry.txPackets);
11361 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011362
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011363 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11364 entry.rxBytes);
11365 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11366 entry.txBytes);
11367 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11368 entry.rxPackets);
11369 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11370 entry.txPackets);
11371 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011372
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011373 // Now distribute proportional blame to the apps that did networking.
11374 long totalPackets = totalRxPackets + totalTxPackets;
11375 if (totalPackets > 0) {
11376 for (int i = 0; i < size; i++) {
11377 entry = delta.getValues(i, entry);
11378 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11379 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011380 }
11381
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011382 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11383
11384 // Distribute total radio active time in to this app.
11385 final long appPackets = entry.rxPackets + entry.txPackets;
11386 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11387 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11388
11389 // Remove this app from the totals, so that we don't lose any time
11390 // due to rounding.
11391 radioTime -= appRadioTime;
11392 totalPackets -= appPackets;
11393
Chenjie Yua54e54d2018-02-14 20:12:52 -080011394 if (deltaInfo != null) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011395 ControllerActivityCounterImpl activityCounter =
11396 u.getOrCreateModemControllerActivityLocked();
11397 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chenjie Yua54e54d2018-02-14 20:12:52 -080011398 final long rxMs = (entry.rxPackets * deltaInfo.getRxTimeMillis())
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011399 / totalRxPackets;
11400 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11401 }
11402
11403 if (totalTxPackets > 0 && entry.txPackets > 0) {
11404 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11405 long txMs =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011406 entry.txPackets * deltaInfo.getTxTimeMillis()[lvl];
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011407 txMs /= totalTxPackets;
11408 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11409 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011410 }
11411 }
11412 }
11413 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011414
11415 if (radioTime > 0) {
11416 // Whoops, there is some radio time we can't blame on an app!
11417 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11418 mMobileRadioActiveUnknownCount.addCountLocked(1);
11419 }
11420
11421 mNetworkStatsPool.release(delta);
11422 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011423 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011424 }
11425 }
11426
Chenjie Yu89083392018-01-11 14:53:31 -080011427 // Cache last value for comparison.
11428 private BluetoothActivityEnergyInfo mLastBluetoothActivityEnergyInfo =
11429 new BluetoothActivityEnergyInfo(0, 0, 0, 0, 0, 0);
11430
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011431 /**
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011432 * Add modem tx power to history
11433 * Device is said to be in high cellular transmit power when it has spent most of the transmit
11434 * time at the highest power level.
11435 * @param activityInfo
11436 */
11437 private void addModemTxPowerToHistory(final ModemActivityInfo activityInfo) {
11438 if (activityInfo == null) {
11439 return;
11440 }
11441 int[] txTimeMs = activityInfo.getTxTimeMillis();
11442 if (txTimeMs == null || txTimeMs.length != ModemActivityInfo.TX_POWER_LEVELS) {
11443 return;
11444 }
11445 final long elapsedRealtime = mClocks.elapsedRealtime();
11446 final long uptime = mClocks.uptimeMillis();
11447 int levelMaxTimeSpent = 0;
11448 for (int i = 1; i < txTimeMs.length; i++) {
11449 if (txTimeMs[i] > txTimeMs[levelMaxTimeSpent]) {
11450 levelMaxTimeSpent = i;
11451 }
11452 }
11453 if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
11454 if (!mIsCellularTxPowerHigh) {
11455 mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11456 addHistoryRecordLocked(elapsedRealtime, uptime);
11457 mIsCellularTxPowerHigh = true;
11458 }
11459 return;
11460 }
11461 if (mIsCellularTxPowerHigh) {
11462 mHistoryCur.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11463 addHistoryRecordLocked(elapsedRealtime, uptime);
11464 mIsCellularTxPowerHigh = false;
11465 }
11466 return;
11467 }
11468
11469 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011470 * Distribute Bluetooth energy info and network traffic to apps.
11471 * @param info The energy information from the bluetooth controller.
11472 */
11473 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011474 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011475 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011476 }
11477
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011478 if (info == null || !mOnBatteryInternal) {
11479 return;
11480 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011481
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011482 mHasBluetoothReporting = true;
11483
Bookatz867c0d72017-03-07 18:23:42 -080011484 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Chenjie Yu89083392018-01-11 14:53:31 -080011485 final long rxTimeMs = info.getControllerRxTimeMillis() -
11486 mLastBluetoothActivityEnergyInfo.getControllerRxTimeMillis();
11487 final long txTimeMs = info.getControllerTxTimeMillis() -
11488 mLastBluetoothActivityEnergyInfo.getControllerTxTimeMillis();
11489 final long idleTimeMs = info.getControllerIdleTimeMillis() -
11490 mLastBluetoothActivityEnergyInfo.getControllerIdleTimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011491 if (DEBUG_ENERGY) {
11492 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11493 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11494 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011495 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011496 }
11497
11498 long totalScanTimeMs = 0;
11499
11500 final int uidCount = mUidStats.size();
11501 for (int i = 0; i < uidCount; i++) {
11502 final Uid u = mUidStats.valueAt(i);
11503 if (u.mBluetoothScanTimer == null) {
11504 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011505 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011506
Bookatzaa4594a2017-03-24 12:39:56 -070011507 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011508 elapsedRealtimeMs * 1000) / 1000;
11509 }
11510
11511 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11512 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11513
11514 if (DEBUG_ENERGY) {
11515 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11516 + " TX=" + normalizeScanTxTime);
11517 }
11518
11519 long leftOverRxTimeMs = rxTimeMs;
11520 long leftOverTxTimeMs = txTimeMs;
11521
11522 for (int i = 0; i < uidCount; i++) {
11523 final Uid u = mUidStats.valueAt(i);
11524 if (u.mBluetoothScanTimer == null) {
11525 continue;
11526 }
11527
Bookatzaa4594a2017-03-24 12:39:56 -070011528 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011529 elapsedRealtimeMs * 1000) / 1000;
11530 if (scanTimeSinceMarkMs > 0) {
11531 // Set the new mark so that next time we get new data since this point.
11532 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11533
11534 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11535 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11536
11537 if (normalizeScanRxTime) {
11538 // Scan time is longer than the total rx time in the controller,
11539 // so distribute the scan time proportionately. This means regular traffic
11540 // will not blamed, but scans are more expensive anyways.
11541 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11542 }
11543
11544 if (normalizeScanTxTime) {
11545 // Scan time is longer than the total tx time in the controller,
11546 // so distribute the scan time proportionately. This means regular traffic
11547 // will not blamed, but scans are more expensive anyways.
11548 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11549 }
11550
11551 final ControllerActivityCounterImpl counter =
11552 u.getOrCreateBluetoothControllerActivityLocked();
11553 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11554 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11555
11556 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11557 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11558 }
11559 }
11560
11561 if (DEBUG_ENERGY) {
11562 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs
11563 + " TX=" + leftOverTxTimeMs);
11564 }
11565
11566 //
11567 // Now distribute blame to apps that did bluetooth traffic.
11568 //
11569
11570 long totalTxBytes = 0;
11571 long totalRxBytes = 0;
11572
11573 final UidTraffic[] uidTraffic = info.getUidTraffic();
Chenjie Yu89083392018-01-11 14:53:31 -080011574 final UidTraffic[] lastUidTraffic = mLastBluetoothActivityEnergyInfo.getUidTraffic();
11575 final ArrayList<UidTraffic> deltaTraffic = new ArrayList<>();
11576 int m = 0, n = 0;
11577 for (; m < uidTraffic.length && n < lastUidTraffic.length; m++) {
11578 final UidTraffic traffic = uidTraffic[m];
11579 final UidTraffic lastTraffic = lastUidTraffic[n];
11580 if (traffic.getUid() == lastTraffic.getUid()) {
11581 deltaTraffic.add(new UidTraffic(traffic.getUid(),
11582 traffic.getRxBytes() - lastTraffic.getRxBytes(),
11583 traffic.getTxBytes() - lastTraffic.getTxBytes()));
11584 n++;
11585 }
11586 }
11587 for (; m < uidTraffic.length; m ++) {
11588 deltaTraffic.add(uidTraffic[m]);
11589 }
11590
11591 for (int i = 0, j = 0; i < deltaTraffic.size(); i++) {
11592 final UidTraffic traffic = deltaTraffic.get(i);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011593
11594 // Add to the global counters.
11595 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(
11596 traffic.getRxBytes());
11597 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(
11598 traffic.getTxBytes());
11599
11600 // Add to the UID counters.
11601 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
11602 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, traffic.getRxBytes(), 0);
11603 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, traffic.getTxBytes(), 0);
11604
11605 // Calculate the total traffic.
11606 totalTxBytes += traffic.getTxBytes();
11607 totalRxBytes += traffic.getRxBytes();
11608 }
11609
11610 if ((totalTxBytes != 0 || totalRxBytes != 0) &&
11611 (leftOverRxTimeMs != 0 || leftOverTxTimeMs != 0)) {
Chenjie Yu89083392018-01-11 14:53:31 -080011612 for (int i = 0; i < deltaTraffic.size(); i++) {
11613 final UidTraffic traffic = deltaTraffic.get(i);
Adam Lesinski50e47602015-12-04 17:04:54 -080011614
Adam Lesinski50e47602015-12-04 17:04:54 -080011615 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011616 final ControllerActivityCounterImpl counter =
11617 u.getOrCreateBluetoothControllerActivityLocked();
11618
11619 if (totalRxBytes > 0 && traffic.getRxBytes() > 0) {
11620 final long timeRxMs = (leftOverRxTimeMs * traffic.getRxBytes()) / totalRxBytes;
11621
11622 if (DEBUG_ENERGY) {
11623 Slog.d(TAG, "UID=" + traffic.getUid() + " rx_bytes=" + traffic.getRxBytes()
11624 + " rx_time=" + timeRxMs);
11625 }
11626 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11627 leftOverRxTimeMs -= timeRxMs;
11628 }
11629
11630 if (totalTxBytes > 0 && traffic.getTxBytes() > 0) {
11631 final long timeTxMs = (leftOverTxTimeMs * traffic.getTxBytes()) / totalTxBytes;
11632
11633 if (DEBUG_ENERGY) {
11634 Slog.d(TAG, "UID=" + traffic.getUid() + " tx_bytes=" + traffic.getTxBytes()
11635 + " tx_time=" + timeTxMs);
11636 }
11637
11638 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11639 leftOverTxTimeMs -= timeTxMs;
11640 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011641 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011642 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011643
Chenjie Yu89083392018-01-11 14:53:31 -080011644 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11645 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11646 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011647
11648 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11649 final double opVolt = mPowerProfile.getAveragePower(
11650 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11651 if (opVolt != 0) {
11652 // We store the power drain as mAms.
11653 mBluetoothActivity.getPowerCounter().addCountLocked(
Chenjie Yu89083392018-01-11 14:53:31 -080011654 (long) ((info.getControllerEnergyUsed() -
11655 mLastBluetoothActivityEnergyInfo.getControllerEnergyUsed() )/ opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011656 }
Chenjie Yu89083392018-01-11 14:53:31 -080011657 mLastBluetoothActivityEnergyInfo = info;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011658 }
11659
11660 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011661 * Read and record Resource Power Manager (RPM) state and voter times.
11662 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11663 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011664 */
11665 public void updateRpmStatsLocked() {
11666 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011667 long now = SystemClock.elapsedRealtime();
11668 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11669 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11670 mLastRpmStatsUpdateTimeMs = now;
11671 }
Bookatz50df7112017-08-04 14:53:26 -070011672
11673 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11674 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11675
11676 // Update values for this platform state.
11677 final String pName = pstate.getKey();
11678 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11679 final int pCount = pstate.getValue().mCount;
11680 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011681 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11682 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11683 }
Bookatz50df7112017-08-04 14:53:26 -070011684
11685 // Update values for each voter of this platform state.
11686 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11687 : pstate.getValue().mVoters.entrySet()) {
11688 final String vName = pName + "." + voter.getKey();
11689 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11690 final int vCount = voter.getValue().mCount;
11691 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011692 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11693 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11694 }
Bookatz50df7112017-08-04 14:53:26 -070011695 }
11696 }
11697
11698 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11699 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11700
11701 final String subsysName = subsys.getKey();
11702 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11703 : subsys.getValue().mStates.entrySet()) {
11704 final String name = subsysName + "." + sstate.getKey();
11705 final long timeUs = sstate.getValue().mTimeMs * 1000;
11706 final int count = sstate.getValue().mCount;
11707 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011708 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11709 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11710 }
Bookatz50df7112017-08-04 14:53:26 -070011711 }
11712 }
11713 }
11714
11715 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011716 * Read and distribute kernel wake lock use across apps.
11717 */
11718 public void updateKernelWakelocksLocked() {
11719 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11720 mTmpWakelockStats);
11721 if (wakelockStats == null) {
11722 // Not crashing might make board bringup easier.
11723 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11724 return;
11725 }
11726
11727 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11728 String name = ent.getKey();
11729 KernelWakelockStats.Entry kws = ent.getValue();
11730
11731 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11732 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011733 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011734 mKernelWakelockStats.put(name, kwlt);
11735 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011736
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011737 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011738 kwlt.setUpdateVersion(kws.mVersion);
11739 }
11740
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011741 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011742 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11743 // this time.
11744 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11745 SamplingTimer st = ent.getValue();
11746 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11747 st.endSample();
11748 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011749 }
11750 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011751
Adam Lesinskid84ad302016-05-17 18:31:02 -070011752 // Record whether we've seen a non-zero time (for debugging b/22716723).
11753 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011754 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11755 }
11756
11757 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11758 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11759 wakelockStats.kernelWakelockVersion);
11760 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011761 }
11762
Adam Lesinski72478f02015-06-17 15:39:43 -070011763 // We use an anonymous class to access these variables,
11764 // so they can't live on the stack or they'd have to be
11765 // final MutableLong objects (more allocations).
11766 // Used in updateCpuTimeLocked().
11767 long mTempTotalCpuUserTimeUs;
11768 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011769 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011770
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011771 /**
James Carr3a226052016-07-01 14:49:52 -070011772 * Reads the newest memory stats from the kernel.
11773 */
11774 public void updateKernelMemoryBandwidthLocked() {
11775 mKernelMemoryBandwidthStats.updateStats();
11776 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11777 final int bandwidthEntryCount = bandwidthEntries.size();
11778 int index;
11779 for (int i = 0; i < bandwidthEntryCount; i++) {
11780 SamplingTimer timer;
11781 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11782 timer = mKernelMemoryStats.valueAt(index);
11783 } else {
11784 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11785 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11786 }
11787 timer.update(bandwidthEntries.valueAt(i), 1);
11788 if (DEBUG_MEMORY) {
11789 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11790 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11791 mKernelMemoryStats.get(
11792 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11793 mKernelMemoryStats.size()));
11794 }
11795 }
11796 }
11797
11798 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011799 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11800 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11801 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011802 */
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011803 public void updateCpuTimeLocked() {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011804 if (mPowerProfile == null) {
11805 return;
11806 }
11807
Adam Lesinski72478f02015-06-17 15:39:43 -070011808 if (DEBUG_ENERGY_CPU) {
11809 Slog.d(TAG, "!Cpu updating!");
11810 }
11811
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011812 if (mCpuFreqs == null) {
11813 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11814 }
11815
Sudheer Shanka38383232017-07-25 09:55:03 -070011816 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11817 // usually holding the wakelock on behalf of an app.
11818 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11819 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Adam Lesinski72478f02015-06-17 15:39:43 -070011820 if (mOnBatteryScreenOffTimeBase.isRunning()) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011821 partialTimersToConsider = new ArrayList<>();
11822 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011823 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011824 // Since the collection and blaming of wakelocks can be scheduled to run after
11825 // some delay, the mPartialTimers list may have new entries. We can't blame
11826 // the newly added timer for past cpu time, so we only consider timers that
11827 // were present for one round of collection. Once a timer has gone through
11828 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011829 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011830 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011831 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011832 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011833 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011834 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011835
Sudheer Shanka38383232017-07-25 09:55:03 -070011836 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11837 // need to take the snapshots.
11838 if (!mOnBatteryInternal) {
11839 mKernelUidCpuTimeReader.readDelta(null);
11840 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Mafae87da2018-01-19 20:07:20 -080011841 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11842 mKernelUidCpuActiveTimeReader.readDelta(null);
11843 mKernelUidCpuClusterTimeReader.readDelta(null);
11844 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011845 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
11846 mKernelCpuSpeedReaders[cluster].readDelta();
11847 }
11848 return;
11849 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011850
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011851 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011852 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
11853 ? null : new SparseLongArray();
Sudheer Shanka38383232017-07-25 09:55:03 -070011854 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011855 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
11856 // freqs, so no need to approximate these values.
11857 if (updatedUids != null) {
11858 updateClusterSpeedTimes(updatedUids);
Sudheer Shanka671985f2017-05-19 11:33:42 -070011859 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011860 readKernelUidCpuFreqTimesLocked(partialTimersToConsider);
Mike Mafae87da2018-01-19 20:07:20 -080011861 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11862 readKernelUidCpuActiveTimesLocked();
11863 readKernelUidCpuClusterTimesLocked();
11864 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011865 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011866
Sudheer Shanka38383232017-07-25 09:55:03 -070011867 /**
11868 * Mark the current partial timers as gone through a collection so that they will be
11869 * considered in the next cpu times distribution to wakelock holders.
11870 */
11871 @VisibleForTesting
11872 public void markPartialTimersAsEligible() {
11873 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
11874 // No difference, so each timer is now considered for the next collection.
11875 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
11876 mPartialTimers.get(i).mInList = true;
11877 }
11878 } else {
11879 // The lists are different, meaning we added (or removed a timer) since the last
11880 // collection.
11881 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
11882 mLastPartialTimers.get(i).mInList = false;
11883 }
11884 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070011885
Sudheer Shanka38383232017-07-25 09:55:03 -070011886 // Mark the current timers as gone through a collection.
11887 final int numPartialTimers = mPartialTimers.size();
11888 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011889 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011890 timer.mInList = true;
11891 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070011892 }
11893 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011894 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011895
Sudheer Shanka38383232017-07-25 09:55:03 -070011896 /**
11897 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
11898 * calculate cpu times spent by each uid at different frequencies.
11899 *
11900 * @param updatedUids The uids for which times spent at different frequencies are calculated.
11901 */
11902 @VisibleForTesting
11903 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011904 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011905 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070011906 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011907 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011908 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
11909 if (clusterSpeedTimesMs[cluster] != null) {
11910 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
11911 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011912 }
11913 }
11914 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011915 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011916 // We have cpu times per freq aggregated over all uids but we need the times per uid.
11917 // So, we distribute total time spent by an uid to different cpu freqs based on the
11918 // amount of time cpu was running at that freq.
11919 final int updatedUidsCount = updatedUids.size();
11920 for (int i = 0; i < updatedUidsCount; ++i) {
11921 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070011922 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011923 // Add the cpu speeds to this UID.
11924 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070011925 if (u.mCpuClusterSpeedTimesUs == null ||
11926 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011927 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011928 }
11929
Sudheer Shankaaf857412017-07-21 00:14:24 -070011930 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
11931 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
11932 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
11933 u.mCpuClusterSpeedTimesUs[cluster].length) {
11934 u.mCpuClusterSpeedTimesUs[cluster]
11935 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011936 }
11937
Sudheer Shankaaf857412017-07-21 00:14:24 -070011938 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011939 for (int speed = 0; speed < speedsInCluster; speed++) {
11940 if (cpuSpeeds[speed] == null) {
11941 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11942 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011943 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
11944 * clusterSpeedTimesMs[cluster][speed]
11945 / totalCpuClustersTimeMs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011946 }
11947 }
11948 }
11949 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011950 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011951
Sudheer Shanka38383232017-07-25 09:55:03 -070011952 /**
11953 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
11954 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
11955 * wakelock holders.
11956 *
11957 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
11958 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
11959 */
11960 @VisibleForTesting
11961 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
11962 @Nullable SparseLongArray updatedUids) {
11963 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
11964 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11965 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070011966
Sudheer Shanka38383232017-07-25 09:55:03 -070011967 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
11968 uid = mapUid(uid);
11969 if (Process.isIsolated(uid)) {
11970 // This could happen if the isolated uid mapping was removed before that process
11971 // was actually killed.
11972 mKernelUidCpuTimeReader.removeUid(uid);
11973 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
11974 return;
11975 }
11976 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11977 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
11978 mKernelUidCpuTimeReader.removeUid(uid);
11979 return;
11980 }
11981 final Uid u = getUidStatsLocked(uid);
11982
11983 // Accumulate the total system and user time.
11984 mTempTotalCpuUserTimeUs += userTimeUs;
11985 mTempTotalCpuSystemTimeUs += systemTimeUs;
11986
11987 StringBuilder sb = null;
11988 if (DEBUG_ENERGY_CPU) {
11989 sb = new StringBuilder();
11990 sb.append(" got time for uid=").append(u.mUid).append(": u=");
11991 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11992 sb.append(" s=");
11993 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11994 sb.append("\n");
11995 }
11996
11997 if (numWakelocks > 0) {
11998 // We have wakelocks being held, so only give a portion of the
11999 // time to the process. The rest will be distributed among wakelock
12000 // holders.
12001 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
12002 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
12003 }
12004
12005 if (sb != null) {
12006 sb.append(" adding to uid=").append(u.mUid).append(": u=");
12007 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12008 sb.append(" s=");
12009 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12010 Slog.d(TAG, sb.toString());
12011 }
12012
12013 u.mUserCpuTime.addCountLocked(userTimeUs);
12014 u.mSystemCpuTime.addCountLocked(systemTimeUs);
12015 if (updatedUids != null) {
12016 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
12017 }
12018 });
12019
12020 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12021 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12022 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
12023 }
12024
12025 if (numWakelocks > 0) {
12026 // Distribute a portion of the total cpu time to wakelock holders.
12027 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12028 mTempTotalCpuSystemTimeUs =
12029 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12030
12031 for (int i = 0; i < numWakelocks; ++i) {
12032 final StopwatchTimer timer = partialTimers.get(i);
12033 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
12034 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
12035
12036 if (DEBUG_ENERGY_CPU) {
12037 final StringBuilder sb = new StringBuilder();
12038 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
12039 .append(": u=");
12040 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12041 sb.append(" s=");
12042 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12043 Slog.d(TAG, sb.toString());
12044 }
12045
12046 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs);
12047 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs);
12048 if (updatedUids != null) {
12049 final int uid = timer.mUid.getUid();
12050 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
12051 }
12052
12053 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
12054 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000);
12055
12056 mTempTotalCpuUserTimeUs -= userTimeUs;
12057 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070012058 }
12059 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012060 }
12061
Sudheer Shanka38383232017-07-25 09:55:03 -070012062 /**
12063 * Take a snapshot of the cpu times spent by each uid in each freq and update the
12064 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012065 *
12066 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070012067 */
12068 @VisibleForTesting
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012069 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers) {
12070 final boolean perClusterTimesAvailable =
12071 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
12072 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12073 final int numClusters = mPowerProfile.getNumCpuClusters();
12074 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012075 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012076 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
12077 uid = mapUid(uid);
12078 if (Process.isIsolated(uid)) {
12079 mKernelUidCpuFreqTimeReader.removeUid(uid);
12080 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
12081 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070012082 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012083 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12084 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
12085 mKernelUidCpuFreqTimeReader.removeUid(uid);
12086 return;
12087 }
12088 final Uid u = getUidStatsLocked(uid);
12089 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12090 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
12091 }
12092 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
12093 if (u.mScreenOffCpuFreqTimeMs == null ||
12094 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12095 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
12096 mOnBatteryScreenOffTimeBase);
12097 }
12098 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012099
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012100 if (perClusterTimesAvailable) {
12101 if (u.mCpuClusterSpeedTimesUs == null ||
12102 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12103 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012104 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012105 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
12106 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012107 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012108
12109 int freqIndex = 0;
12110 for (int cluster = 0; cluster < numClusters; ++cluster) {
12111 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12112 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12113 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12114 u.mCpuClusterSpeedTimesUs[cluster]
12115 = new LongSamplingCounter[speedsInCluster];
12116 }
12117 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
12118 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
12119 }
12120 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
12121 for (int speed = 0; speed < speedsInCluster; ++speed) {
12122 if (cpuTimesUs[speed] == null) {
12123 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12124 }
12125 final long appAllocationUs;
12126 if (mWakeLockAllocationsUs != null) {
12127 appAllocationUs =
12128 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
12129 mWakeLockAllocationsUs[cluster][speed] +=
12130 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
12131 } else {
12132 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
12133 }
12134 cpuTimesUs[speed].addCountLocked(appAllocationUs);
12135 freqIndex++;
12136 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012137 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012138 }
12139 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012140
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012141 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12142 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12143 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
12144 }
12145
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012146 if (mWakeLockAllocationsUs != null) {
12147 for (int i = 0; i < numWakelocks; ++i) {
12148 final Uid u = partialTimers.get(i).mUid;
12149 if (u.mCpuClusterSpeedTimesUs == null ||
12150 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12151 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
12152 }
12153
12154 for (int cluster = 0; cluster < numClusters; ++cluster) {
12155 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12156 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12157 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12158 u.mCpuClusterSpeedTimesUs[cluster]
12159 = new LongSamplingCounter[speedsInCluster];
12160 }
12161 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
12162 for (int speed = 0; speed < speedsInCluster; ++speed) {
12163 if (cpuTimeUs[speed] == null) {
12164 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12165 }
12166 final long allocationUs =
12167 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
12168 cpuTimeUs[speed].addCountLocked(allocationUs);
12169 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
12170 }
12171 }
12172 }
12173 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012174 }
12175
Mike Ma3d422c32017-10-25 11:08:57 -070012176 /**
12177 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
12178 * counters.
12179 */
12180 @VisibleForTesting
12181 public void readKernelUidCpuActiveTimesLocked() {
12182 final long startTimeMs = mClocks.uptimeMillis();
12183 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesUs) -> {
12184 uid = mapUid(uid);
12185 if (Process.isIsolated(uid)) {
12186 mKernelUidCpuActiveTimeReader.removeUid(uid);
12187 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
12188 return;
12189 }
12190 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12191 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
12192 mKernelUidCpuActiveTimeReader.removeUid(uid);
12193 return;
12194 }
12195 final Uid u = getUidStatsLocked(uid);
12196 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesUs);
12197 });
12198
12199 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12200 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12201 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12202 }
12203 }
12204
12205 /**
12206 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12207 * counters.
12208 */
12209 @VisibleForTesting
12210 public void readKernelUidCpuClusterTimesLocked() {
12211 final long startTimeMs = mClocks.uptimeMillis();
12212 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesUs) -> {
12213 uid = mapUid(uid);
12214 if (Process.isIsolated(uid)) {
12215 mKernelUidCpuClusterTimeReader.removeUid(uid);
12216 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12217 return;
12218 }
12219 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12220 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12221 mKernelUidCpuClusterTimeReader.removeUid(uid);
12222 return;
12223 }
12224 final Uid u = getUidStatsLocked(uid);
12225 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesUs);
12226 });
12227
12228 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12229 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12230 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12231 }
12232 }
12233
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012234 boolean setChargingLocked(boolean charging) {
12235 if (mCharging != charging) {
12236 mCharging = charging;
12237 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012238 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012239 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012240 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012241 }
12242 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12243 return true;
12244 }
12245 return false;
12246 }
12247
Mike Mac2f518a2017-09-19 16:06:03 -070012248 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12249 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012250 boolean doWrite = false;
12251 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12252 m.arg1 = onBattery ? 1 : 0;
12253 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012254
Dianne Hackborn40c87252014-03-19 16:55:40 -070012255 final long uptime = mSecUptime * 1000;
12256 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012257 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012258 if (onBattery) {
12259 // We will reset our status if we are unplugging after the
12260 // battery was last full, or the level is at 100, or
12261 // we have gone through a significant charge (from a very low
12262 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012263 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012264 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012265 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012266 || (mDischargeCurrentLevel < 20 && level >= 80)
12267 || (getHighDischargeAmountSinceCharge() >= 200
12268 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012269 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012270 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012271 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12272 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012273 // Before we write, collect a snapshot of the final aggregated
12274 // stats to be reported in the next checkin. Only do this if we have
12275 // a sufficient amount of data to make it interesting.
12276 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012277 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012278 final Parcel parcel = Parcel.obtain();
12279 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012280 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012281 BackgroundThread.getHandler().post(new Runnable() {
12282 @Override public void run() {
12283 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012284 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012285 FileOutputStream stream = null;
12286 try {
12287 stream = mCheckinFile.startWrite();
12288 stream.write(parcel.marshall());
12289 stream.flush();
12290 FileUtils.sync(stream);
12291 stream.close();
12292 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012293 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12294 "batterystats-checkin",
12295 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012296 } catch (IOException e) {
12297 Slog.w("BatteryStats",
12298 "Error writing checkin battery statistics", e);
12299 mCheckinFile.failWrite(stream);
12300 } finally {
12301 parcel.recycle();
12302 }
12303 }
12304 }
12305 });
12306 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012307 doWrite = true;
12308 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012309 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012310 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012311 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012312 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012313 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012314 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012315 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012316 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012317 if (mCharging) {
12318 setChargingLocked(false);
12319 }
12320 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012321 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012322 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012323 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012324 mDischargeStepTracker.clearTime();
12325 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012326 mInitStepMode = mCurStepMode;
12327 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012328 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012329 mHistoryCur.batteryLevel = (byte)level;
12330 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12331 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12332 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012333 if (reset) {
12334 mRecordingHistory = true;
12335 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12336 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012337 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012338 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012339 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012340 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012341 mDischargeScreenDozeUnplugLevel = 0;
12342 mDischargeScreenOffUnplugLevel = 0;
12343 } else if (isScreenDoze(screenState)) {
12344 mDischargeScreenOnUnplugLevel = 0;
12345 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012346 mDischargeScreenOffUnplugLevel = 0;
12347 } else {
12348 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012349 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012350 mDischargeScreenOffUnplugLevel = level;
12351 }
12352 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012353 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012354 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012355 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012356 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012357 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012358 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012359 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012360 mHistoryCur.batteryLevel = (byte)level;
12361 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12362 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12363 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012364 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012365 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012366 if (level < mDischargeUnplugLevel) {
12367 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12368 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12369 }
Mike Mac2f518a2017-09-19 16:06:03 -070012370 updateDischargeScreenLevelsLocked(screenState, screenState);
12371 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012372 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012373 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012374 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012375 mInitStepMode = mCurStepMode;
12376 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012377 }
12378 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12379 if (mFile != null) {
12380 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012381 }
12382 }
12383 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012384
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012385 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12386 boolean reset) {
12387 mRecordingHistory = true;
12388 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn37de0982014-05-09 09:32:18 -070012389 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs,
12390 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012391 mHistoryCur);
12392 mHistoryCur.currentTime = 0;
12393 if (reset) {
12394 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12395 }
12396 }
12397
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012398 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12399 final long uptimeMs) {
12400 if (mRecordingHistory) {
12401 mHistoryCur.currentTime = currentTime;
12402 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_CURRENT_TIME,
12403 mHistoryCur);
12404 mHistoryCur.currentTime = 0;
12405 }
12406 }
12407
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012408 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12409 if (mRecordingHistory) {
12410 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012411 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_SHUTDOWN,
12412 mHistoryCur);
12413 mHistoryCur.currentTime = 0;
12414 }
12415 }
12416
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012417 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012418 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012419 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012420 }
12421 }
12422
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012423 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012424 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012425
Bookatz8c6571b2017-10-24 15:04:41 -070012426 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12427 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12428 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012429 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12430 temp = Math.max(0, temp);
12431
Bookatz8c6571b2017-10-24 15:04:41 -070012432 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
12433 status, plugType, level, temp);
12434
Todd Poynor1acf06a2017-12-07 19:19:35 -080012435 final boolean onBattery =
12436 plugType == BATTERY_PLUGGED_NONE &&
12437 status != BatteryManager.BATTERY_STATUS_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080012438 final long uptime = mClocks.uptimeMillis();
12439 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012440 if (!mHaveBatteryLevel) {
12441 mHaveBatteryLevel = true;
12442 // We start out assuming that the device is plugged in (not
12443 // on battery). If our first report is now that we are indeed
12444 // plugged in, then twiddle our state to correctly reflect that
12445 // since we won't be going through the full setOnBattery().
12446 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012447 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012448 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012449 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012450 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012451 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012452 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012453 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012454 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012455 mHistoryCur.batteryStatus = (byte)status;
12456 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012457 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012458 mMaxChargeStepLevel = mMinDischargeStepLevel =
12459 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012460 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012461 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12462 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12463 }
12464 int oldStatus = mHistoryCur.batteryStatus;
12465 if (onBattery) {
12466 mDischargeCurrentLevel = level;
12467 if (!mRecordingHistory) {
12468 mRecordingHistory = true;
12469 startRecordingHistory(elapsedRealtime, uptime, true);
12470 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012471 } else if (level < 96 &&
12472 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012473 if (!mRecordingHistory) {
12474 mRecordingHistory = true;
12475 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012476 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012477 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012478 mCurrentBatteryLevel = level;
12479 if (mDischargePlugLevel < 0) {
12480 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012481 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012482
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012483 if (onBattery != mOnBattery) {
12484 mHistoryCur.batteryLevel = (byte)level;
12485 mHistoryCur.batteryStatus = (byte)status;
12486 mHistoryCur.batteryHealth = (byte)health;
12487 mHistoryCur.batteryPlugType = (byte)plugType;
12488 mHistoryCur.batteryTemperature = (short)temp;
12489 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012490 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12491 // Only record discharges
12492 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12493 mDischargeCounter.addCountLocked(chargeDiff);
12494 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012495 if (isScreenDoze(mScreenState)) {
12496 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12497 }
Mike Ma15313c92017-11-15 17:58:21 -080012498 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12499 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12500 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12501 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12502 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012503 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012504 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012505 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012506 } else {
12507 boolean changed = false;
12508 if (mHistoryCur.batteryLevel != level) {
12509 mHistoryCur.batteryLevel = (byte)level;
12510 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012511
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012512 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12513 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012514 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070012515 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012516 if (mHistoryCur.batteryStatus != status) {
12517 mHistoryCur.batteryStatus = (byte)status;
12518 changed = true;
12519 }
12520 if (mHistoryCur.batteryHealth != health) {
12521 mHistoryCur.batteryHealth = (byte)health;
12522 changed = true;
12523 }
12524 if (mHistoryCur.batteryPlugType != plugType) {
12525 mHistoryCur.batteryPlugType = (byte)plugType;
12526 changed = true;
12527 }
12528 if (temp >= (mHistoryCur.batteryTemperature+10)
12529 || temp <= (mHistoryCur.batteryTemperature-10)) {
12530 mHistoryCur.batteryTemperature = (short)temp;
12531 changed = true;
12532 }
12533 if (volt > (mHistoryCur.batteryVoltage+20)
12534 || volt < (mHistoryCur.batteryVoltage-20)) {
12535 mHistoryCur.batteryVoltage = (char)volt;
12536 changed = true;
12537 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012538 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12539 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012540 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12541 // Only record discharges
12542 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12543 mDischargeCounter.addCountLocked(chargeDiff);
12544 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012545 if (isScreenDoze(mScreenState)) {
12546 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12547 }
Mike Ma15313c92017-11-15 17:58:21 -080012548 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12549 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12550 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12551 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12552 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012553 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012554 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012555 changed = true;
12556 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012557 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12558 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12559 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12560 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012561 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012562 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12563 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12564 modeBits, elapsedRealtime);
12565 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12566 modeBits, elapsedRealtime);
12567 mLastDischargeStepLevel = level;
12568 mMinDischargeStepLevel = level;
12569 mInitStepMode = mCurStepMode;
12570 mModStepMode = 0;
12571 }
12572 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012573 if (level >= 90) {
12574 // If the battery level is at least 90%, always consider the device to be
12575 // charging even if it happens to go down a level.
12576 changed |= setChargingLocked(true);
12577 mLastChargeStepLevel = level;
12578 } if (!mCharging) {
12579 if (mLastChargeStepLevel < level) {
12580 // We have not reporting that we are charging, but the level has now
12581 // gone up, so consider the state to be charging.
12582 changed |= setChargingLocked(true);
12583 mLastChargeStepLevel = level;
12584 }
12585 } else {
12586 if (mLastChargeStepLevel > level) {
12587 // We had reported that the device was charging, but here we are with
12588 // power connected and the level going down. Looks like the current
12589 // power supplied isn't enough, so consider the device to now be
12590 // discharging.
12591 changed |= setChargingLocked(false);
12592 mLastChargeStepLevel = level;
12593 }
12594 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012595 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12596 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12597 modeBits, elapsedRealtime);
12598 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12599 modeBits, elapsedRealtime);
12600 mLastChargeStepLevel = level;
12601 mMaxChargeStepLevel = level;
12602 mInitStepMode = mCurStepMode;
12603 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012604 }
12605 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012606 if (changed) {
12607 addHistoryRecordLocked(elapsedRealtime, uptime);
12608 }
Evan Millarc64edde2009-04-18 12:26:32 -070012609 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012610 if (!onBattery &&
12611 (status == BatteryManager.BATTERY_STATUS_FULL ||
12612 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12613 // We don't record history while we are plugged in and fully charged
12614 // (or when battery is not present). The next time we are
12615 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012616 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012617 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012618
Jocelyn Dangc627d102017-04-14 13:15:14 -070012619 if (mMinLearnedBatteryCapacity == -1) {
12620 mMinLearnedBatteryCapacity = chargeFullUAh;
12621 } else {
12622 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012623 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012624 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012625 }
12626
Bookatz8c6571b2017-10-24 15:04:41 -070012627 // Inform StatsLog of setBatteryState changes.
12628 // If this is the first reporting, pass in recentPast == null.
12629 private void reportChangesToStatsLog(HistoryItem recentPast,
12630 final int status, final int plugType, final int level, final int temp) {
12631
12632 if (recentPast == null || recentPast.batteryStatus != status) {
12633 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12634 }
12635 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12636 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12637 }
12638 if (recentPast == null || recentPast.batteryLevel != level) {
12639 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12640 }
12641 // Let's just always print the temperature, regardless of whether it changed.
12642 StatsLog.write(StatsLog.DEVICE_TEMPERATURE_REPORTED, temp);
12643 }
12644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012645 public long getAwakeTimeBattery() {
12646 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12647 }
12648
12649 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012650 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012651 }
12652
12653 @Override
12654 public long computeUptime(long curTime, int which) {
12655 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012656 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012657 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012658 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012659 }
12660 return 0;
12661 }
12662
12663 @Override
12664 public long computeRealtime(long curTime, int which) {
12665 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012666 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012667 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012668 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012669 }
12670 return 0;
12671 }
12672
12673 @Override
12674 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012675 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012676 }
12677
12678 @Override
12679 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012680 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012681 }
12682
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012683 @Override
12684 public long computeBatteryScreenOffUptime(long curTime, int which) {
12685 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12686 }
12687
12688 @Override
12689 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12690 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012691 }
12692
Dianne Hackborn260c5022014-04-29 11:23:16 -070012693 private long computeTimePerLevel(long[] steps, int numSteps) {
12694 // For now we'll do a simple average across all steps.
12695 if (numSteps <= 0) {
12696 return -1;
12697 }
12698 long total = 0;
12699 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012700 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012701 }
12702 return total / numSteps;
12703 /*
12704 long[] buckets = new long[numSteps];
12705 int numBuckets = 0;
12706 int numToAverage = 4;
12707 int i = 0;
12708 while (i < numSteps) {
12709 long totalTime = 0;
12710 int num = 0;
12711 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012712 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012713 num++;
12714 }
12715 buckets[numBuckets] = totalTime / num;
12716 numBuckets++;
12717 numToAverage *= 2;
12718 i += num;
12719 }
12720 if (numBuckets < 1) {
12721 return -1;
12722 }
12723 long averageTime = buckets[numBuckets-1];
12724 for (i=numBuckets-2; i>=0; i--) {
12725 averageTime = (averageTime + buckets[i]) / 2;
12726 }
12727 return averageTime;
12728 */
12729 }
12730
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012731 @Override
12732 public long computeBatteryTimeRemaining(long curTime) {
12733 if (!mOnBattery) {
12734 return -1;
12735 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012736 /* Simple implementation just looks at the average discharge per level across the
12737 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012738 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12739 if (discharge < 2) {
12740 return -1;
12741 }
12742 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12743 if (duration < 1000*1000) {
12744 return -1;
12745 }
12746 long usPerLevel = duration/discharge;
12747 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012748 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012749 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012750 return -1;
12751 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012752 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012753 if (msPerLevel <= 0) {
12754 return -1;
12755 }
12756 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012757 }
12758
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012759 @Override
12760 public LevelStepTracker getDischargeLevelStepTracker() {
12761 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012762 }
12763
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012764 @Override
12765 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12766 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012767 }
12768
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012769 @Override
12770 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012771 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012772 // Not yet working.
12773 return -1;
12774 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012775 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012776 int curLevel = mCurrentBatteryLevel;
12777 int plugLevel = mDischargePlugLevel;
12778 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12779 return -1;
12780 }
12781 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12782 if (duration < 1000*1000) {
12783 return -1;
12784 }
12785 long usPerLevel = duration/(curLevel-plugLevel);
12786 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012787 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012788 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012789 return -1;
12790 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012791 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012792 if (msPerLevel <= 0) {
12793 return -1;
12794 }
12795 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012796 }
12797
Siddharth Raya1fd0572017-11-13 14:20:47 -080012798 /*@hide */
12799 public CellularBatteryStats getCellularBatteryStats() {
12800 CellularBatteryStats s = new CellularBatteryStats();
12801 final int which = STATS_SINCE_CHARGED;
12802 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12803 final ControllerActivityCounter counter = getModemControllerActivity();
Siddharth Rayed754702018-02-15 12:44:37 -080012804 final long sleepTimeMs = counter.getSleepTimeCounter().getCountLocked(which);
Siddharth Raya1fd0572017-11-13 14:20:47 -080012805 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12806 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12807 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12808 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12809 for (int i = 0; i < timeInRatMs.length; i++) {
12810 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12811 }
12812 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12813 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12814 timeInRxSignalStrengthLevelMs[i]
12815 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12816 }
12817 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12818 counter.getTxTimeCounters().length)];
12819 long totalTxTimeMs = 0;
12820 for (int i = 0; i < txTimeMs.length; i++) {
12821 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12822 totalTxTimeMs += txTimeMs[i];
12823 }
Siddharth Raya1fd0572017-11-13 14:20:47 -080012824 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12825 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12826 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12827 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12828 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12829 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
12830 s.setSleepTimeMs(sleepTimeMs);
12831 s.setIdleTimeMs(idleTimeMs);
12832 s.setRxTimeMs(rxTimeMs);
12833 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12834 s.setTimeInRatMs(timeInRatMs);
12835 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
12836 s.setTxTimeMs(txTimeMs);
12837 return s;
12838 }
12839
Siddharth Rayb50a6842017-12-14 15:15:28 -080012840 /*@hide */
12841 public WifiBatteryStats getWifiBatteryStats() {
12842 WifiBatteryStats s = new WifiBatteryStats();
12843 final int which = STATS_SINCE_CHARGED;
12844 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12845 final ControllerActivityCounter counter = getWifiControllerActivity();
12846 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12847 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
12848 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12849 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
12850 final long totalControllerActivityTimeMs
12851 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12852 final long sleepTimeMs
12853 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
12854 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12855 long numAppScanRequest = 0;
12856 for (int i = 0; i < mUidStats.size(); i++) {
12857 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
12858 }
12859 long[] timeInStateMs = new long[NUM_WIFI_STATES];
12860 for (int i=0; i<NUM_WIFI_STATES; i++) {
12861 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
12862 }
12863 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
12864 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12865 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
12866 }
12867 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
12868 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12869 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
12870 }
12871 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12872 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
12873 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
12874 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
12875 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
12876 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
12877 s.setSleepTimeMs(sleepTimeMs);
12878 s.setIdleTimeMs(idleTimeMs);
12879 s.setRxTimeMs(rxTimeMs);
12880 s.setTxTimeMs(txTimeMs);
12881 s.setScanTimeMs(scanTimeMs);
12882 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12883 s.setNumAppScanRequest(numAppScanRequest);
12884 s.setTimeInStateMs(timeInStateMs);
12885 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
12886 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
12887 return s;
12888 }
12889
Siddharth Ray78ccaf52017-12-23 16:16:21 -080012890 /*@hide */
12891 public GpsBatteryStats getGpsBatteryStats() {
12892 GpsBatteryStats s = new GpsBatteryStats();
12893 final int which = STATS_SINCE_CHARGED;
12894 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12895 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12896 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
12897 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
12898 for (int i=0; i<time.length; i++) {
12899 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
12900 }
12901 s.setTimeInGpsSignalQualityLevel(time);
12902 return s;
12903 }
12904
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012905 @Override
12906 public LevelStepTracker getChargeLevelStepTracker() {
12907 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012908 }
12909
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012910 @Override
12911 public LevelStepTracker getDailyChargeLevelStepTracker() {
12912 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012913 }
12914
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012915 @Override
12916 public ArrayList<PackageChange> getDailyPackageChanges() {
12917 return mDailyPackageChanges;
12918 }
12919
Joe Onoratoe1acd632016-02-23 13:25:10 -080012920 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012921 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012922 }
12923
12924 @Override
12925 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012926 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012927 }
12928
12929 @Override
12930 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012931 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012932 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070012933
The Android Open Source Project10592532009-03-18 17:39:46 -070012934 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012935 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012936 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012937 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012938 }
12939 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012940
Evan Millar633a1742009-04-02 16:36:33 -070012941 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012942 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012943 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012944
The Android Open Source Project10592532009-03-18 17:39:46 -070012945 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012946 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012947 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012948 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012949 }
12950 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012951
Evan Millar633a1742009-04-02 16:36:33 -070012952 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012953 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012955
Amith Yamasanie43530a2009-08-21 13:11:37 -070012956 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012957 public int getLowDischargeAmountSinceCharge() {
12958 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012959 int val = mLowDischargeAmountSinceCharge;
12960 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12961 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
12962 }
12963 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012964 }
12965 }
12966
12967 @Override
12968 public int getHighDischargeAmountSinceCharge() {
12969 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012970 int val = mHighDischargeAmountSinceCharge;
12971 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12972 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
12973 }
12974 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012975 }
12976 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012977
12978 @Override
12979 public int getDischargeAmount(int which) {
12980 int dischargeAmount = which == STATS_SINCE_CHARGED
12981 ? getHighDischargeAmountSinceCharge()
12982 : (getDischargeStartLevel() - getDischargeCurrentLevel());
12983 if (dischargeAmount < 0) {
12984 dischargeAmount = 0;
12985 }
12986 return dischargeAmount;
12987 }
12988
Mike Mac2f518a2017-09-19 16:06:03 -070012989 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012990 public int getDischargeAmountScreenOn() {
12991 synchronized(this) {
12992 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070012993 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012994 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12995 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12996 }
12997 return val;
12998 }
12999 }
13000
Mike Mac2f518a2017-09-19 16:06:03 -070013001 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013002 public int getDischargeAmountScreenOnSinceCharge() {
13003 synchronized(this) {
13004 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070013005 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013006 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13007 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13008 }
13009 return val;
13010 }
13011 }
13012
Mike Mac2f518a2017-09-19 16:06:03 -070013013 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013014 public int getDischargeAmountScreenOff() {
13015 synchronized(this) {
13016 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070013017 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013018 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13019 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13020 }
Mike Mac2f518a2017-09-19 16:06:03 -070013021 // For backward compatibility, doze discharge is counted into screen off.
13022 return val + getDischargeAmountScreenDoze();
13023 }
13024 }
13025
13026 @Override
13027 public int getDischargeAmountScreenOffSinceCharge() {
13028 synchronized(this) {
13029 int val = mDischargeAmountScreenOffSinceCharge;
13030 if (mOnBattery && isScreenOff(mScreenState)
13031 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13032 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13033 }
13034 // For backward compatibility, doze discharge is counted into screen off.
13035 return val + getDischargeAmountScreenDozeSinceCharge();
13036 }
13037 }
13038
13039 @Override
13040 public int getDischargeAmountScreenDoze() {
13041 synchronized(this) {
13042 int val = mDischargeAmountScreenDoze;
13043 if (mOnBattery && isScreenDoze(mScreenState)
13044 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13045 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
13046 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013047 return val;
13048 }
13049 }
13050
Mike Mac2f518a2017-09-19 16:06:03 -070013051 @Override
13052 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013053 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070013054 int val = mDischargeAmountScreenDozeSinceCharge;
13055 if (mOnBattery && isScreenDoze(mScreenState)
13056 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13057 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013058 }
13059 return val;
13060 }
13061 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063 /**
13064 * Retrieve the statistics object for a particular uid, creating if needed.
13065 */
13066 public Uid getUidStatsLocked(int uid) {
13067 Uid u = mUidStats.get(uid);
13068 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080013069 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013070 mUidStats.put(uid, u);
13071 }
13072 return u;
13073 }
13074
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013075 /**
13076 * Retrieve the statistics object for a particular uid. Returns null if the object is not
13077 * available.
13078 */
13079 public Uid getAvailableUidStatsLocked(int uid) {
13080 Uid u = mUidStats.get(uid);
13081 return u;
13082 }
13083
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013084 public void onCleanupUserLocked(int userId) {
13085 final int firstUidForUser = UserHandle.getUid(userId, 0);
13086 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13087 mKernelUidCpuFreqTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
13088 mKernelUidCpuTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013089 if (mKernelSingleUidTimeReader != null) {
13090 mKernelSingleUidTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
13091 }
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013092 }
13093
13094 public void onUserRemovedLocked(int userId) {
13095 final int firstUidForUser = UserHandle.getUid(userId, 0);
13096 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13097 mUidStats.put(firstUidForUser, null);
13098 mUidStats.put(lastUidForUser, null);
13099 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
13100 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
13101 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
13102 }
13103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013104 /**
13105 * Remove the statistics object for a particular uid.
13106 */
13107 public void removeUidStatsLocked(int uid) {
Adam Lesinskib83ffee2015-05-12 14:43:47 -070013108 mKernelUidCpuTimeReader.removeUid(uid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -070013109 mKernelUidCpuFreqTimeReader.removeUid(uid);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013110 if (mKernelSingleUidTimeReader != null) {
13111 mKernelSingleUidTimeReader.removeUid(uid);
13112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013113 mUidStats.remove(uid);
13114 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070013115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013116 /**
13117 * Retrieve the statistics object for a particular process, creating
13118 * if needed.
13119 */
13120 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013121 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013122 Uid u = getUidStatsLocked(uid);
13123 return u.getProcessStatsLocked(name);
13124 }
13125
13126 /**
13127 * Retrieve the statistics object for a particular process, creating
13128 * if needed.
13129 */
13130 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013131 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013132 Uid u = getUidStatsLocked(uid);
13133 return u.getPackageStatsLocked(pkg);
13134 }
13135
13136 /**
13137 * Retrieve the statistics object for a particular service, creating
13138 * if needed.
13139 */
13140 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013141 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013142 Uid u = getUidStatsLocked(uid);
13143 return u.getServiceStatsLocked(pkg, name);
13144 }
13145
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013146 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013147 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013148 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013149 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013150 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013151
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013152 public boolean trackPerProcStateCpuTimes() {
13153 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
13154 }
13155
13156 public void systemServicesReady(Context context) {
13157 mConstants.startObserving(context.getContentResolver());
13158 }
13159
13160 @VisibleForTesting
13161 public final class Constants extends ContentObserver {
13162 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
13163 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080013164 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
13165 = "track_cpu_active_cluster_time";
13166 public static final String KEY_READ_BINARY_CPU_TIME
13167 = "read_binary_cpu_time";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013168
13169 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080013170 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
13171 private static final boolean DEFAULT_READ_BINARY_CPU_TIME = false;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013172
13173 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013174 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
13175 // Not used right now.
13176 public boolean READ_BINARY_CPU_TIME = DEFAULT_READ_BINARY_CPU_TIME;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013177
13178 private ContentResolver mResolver;
13179 private final KeyValueListParser mParser = new KeyValueListParser(',');
13180
13181 public Constants(Handler handler) {
13182 super(handler);
13183 }
13184
13185 public void startObserving(ContentResolver resolver) {
13186 mResolver = resolver;
13187 mResolver.registerContentObserver(
13188 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13189 false /* notifyForDescendants */, this);
13190 updateConstants();
13191 }
13192
13193 @Override
13194 public void onChange(boolean selfChange, Uri uri) {
13195 updateConstants();
13196 }
13197
13198 private void updateConstants() {
13199 synchronized (BatteryStatsImpl.this) {
13200 try {
13201 mParser.setString(Settings.Global.getString(mResolver,
13202 Settings.Global.BATTERY_STATS_CONSTANTS));
13203 } catch (IllegalArgumentException e) {
13204 // Failed to parse the settings string, log this and move on
13205 // with defaults.
13206 Slog.e(TAG, "Bad batterystats settings", e);
13207 }
13208
13209 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13210 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13211 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013212 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13213 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
13214 READ_BINARY_CPU_TIME = mParser.getBoolean(
13215 KEY_READ_BINARY_CPU_TIME, DEFAULT_READ_BINARY_CPU_TIME);
13216
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013217 }
13218 }
13219
13220 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13221 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13222 if (isEnabled && !wasEnabled) {
13223 mKernelSingleUidTimeReader.markDataAsStale(true);
13224 mExternalSync.scheduleCpuSyncDueToSettingChange();
13225 }
13226 }
13227
13228 public void dumpLocked(PrintWriter pw) {
13229 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13230 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013231 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13232 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
13233 pw.print(KEY_READ_BINARY_CPU_TIME); pw.print("=");
13234 pw.println(READ_BINARY_CPU_TIME);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013235 }
13236 }
13237
13238 public void dumpConstantsLocked(PrintWriter pw) {
13239 mConstants.dumpLocked(pw);
13240 }
13241
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013242 Parcel mPendingWrite = null;
13243 final ReentrantLock mWriteLock = new ReentrantLock();
13244
13245 public void writeAsyncLocked() {
13246 writeLocked(false);
13247 }
13248
13249 public void writeSyncLocked() {
13250 writeLocked(true);
13251 }
13252
13253 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013254 if (mFile == null) {
13255 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013256 return;
13257 }
13258
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013259 if (mShuttingDown) {
13260 return;
13261 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013262
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013263 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013264 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013265 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013266
13267 if (mPendingWrite != null) {
13268 mPendingWrite.recycle();
13269 }
13270 mPendingWrite = out;
13271
13272 if (sync) {
13273 commitPendingDataToDisk();
13274 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013275 BackgroundThread.getHandler().post(new Runnable() {
13276 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013277 commitPendingDataToDisk();
13278 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013279 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013280 }
13281 }
13282
13283 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013284 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013285 synchronized (this) {
13286 next = mPendingWrite;
13287 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013288 if (next == null) {
13289 return;
13290 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013291 }
13292
Amith Yamasanid2450862017-02-07 15:58:24 -080013293 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013294 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013295 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013296 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013297 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013298 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013299 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013300 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013301 mFile.commit();
Dianne Hackborne17b4452018-01-10 13:15:40 -080013302 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13303 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013304 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013305 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013306 mFile.rollback();
13307 } finally {
13308 next.recycle();
13309 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013311 }
13312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013313 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013314 if (mDailyFile != null) {
13315 readDailyStatsLocked();
13316 }
13317
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013318 if (mFile == null) {
13319 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013320 return;
13321 }
13322
13323 mUidStats.clear();
13324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013325 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013326 File file = mFile.chooseForRead();
13327 if (!file.exists()) {
13328 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013329 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013330 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013331
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013332 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013333 Parcel in = Parcel.obtain();
13334 in.unmarshall(raw, 0, raw.length);
13335 in.setDataPosition(0);
13336 stream.close();
13337
13338 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013339 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013340 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013341 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013342 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013343
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013344 mEndPlatformVersion = Build.ID;
13345
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013346 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013347 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013348 final long elapsedRealtime = mClocks.elapsedRealtime();
13349 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013350 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013351 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013352 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013353 addHistoryBufferLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
13354 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013355 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013356
13357 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013358 }
13359
13360 public int describeContents() {
13361 return 0;
13362 }
13363
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013364 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013365 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013366
13367 mHistoryBuffer.setDataSize(0);
13368 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013369 mHistoryTagPool.clear();
13370 mNextHistoryTagIdx = 0;
13371 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013372
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013373 int numTags = in.readInt();
13374 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013375 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013376 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013377 if (str == null) {
13378 throw new ParcelFormatException("null history tag string");
13379 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013380 int uid = in.readInt();
13381 HistoryTag tag = new HistoryTag();
13382 tag.string = str;
13383 tag.uid = uid;
13384 tag.poolIdx = idx;
13385 mHistoryTagPool.put(tag, idx);
13386 if (idx >= mNextHistoryTagIdx) {
13387 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013388 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013389 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013390 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013391
13392 int bufSize = in.readInt();
13393 int curPos = in.dataPosition();
13394 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013395 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13396 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013397 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013398 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13399 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013400 } else {
13401 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13402 + " bytes at " + curPos);
13403 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13404 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013405 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013406
Dianne Hackbornae384452011-06-28 12:33:48 -070013407 if (andOldHistory) {
13408 readOldHistory(in);
13409 }
13410
13411 if (DEBUG_HISTORY) {
13412 StringBuilder sb = new StringBuilder(128);
13413 sb.append("****************** OLD mHistoryBaseTime: ");
13414 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13415 Slog.i(TAG, sb.toString());
13416 }
13417 mHistoryBaseTime = historyBaseTime;
13418 if (DEBUG_HISTORY) {
13419 StringBuilder sb = new StringBuilder(128);
13420 sb.append("****************** NEW mHistoryBaseTime: ");
13421 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13422 Slog.i(TAG, sb.toString());
13423 }
13424
13425 // We are just arbitrarily going to insert 1 minute from the sample of
13426 // the last run until samples in this run.
13427 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013428 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013429 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013430 if (DEBUG_HISTORY) {
13431 StringBuilder sb = new StringBuilder(128);
13432 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13433 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13434 Slog.i(TAG, sb.toString());
13435 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013436 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013437 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013438
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013439 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013440 if (!USE_OLD_HISTORY) {
13441 return;
13442 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013443 mHistory = mHistoryEnd = mHistoryCache = null;
13444 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013445 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013446 HistoryItem rec = new HistoryItem(time, in);
13447 addHistoryRecordLocked(rec);
13448 }
13449 }
13450
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013451 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013452 if (DEBUG_HISTORY) {
13453 StringBuilder sb = new StringBuilder(128);
13454 sb.append("****************** WRITING mHistoryBaseTime: ");
13455 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013456 sb.append(" mLastHistoryElapsedRealtime: ");
13457 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013458 Slog.i(TAG, sb.toString());
13459 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013460 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013461 if (!inclData) {
13462 out.writeInt(0);
13463 out.writeInt(0);
13464 return;
13465 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013466 out.writeInt(mHistoryTagPool.size());
13467 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13468 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013469 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013470 out.writeString(tag.string);
13471 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013472 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013473 out.writeInt(mHistoryBuffer.dataSize());
13474 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13475 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13476 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013477
13478 if (andOldHistory) {
13479 writeOldHistory(out);
13480 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013481 }
13482
13483 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013484 if (!USE_OLD_HISTORY) {
13485 return;
13486 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013487 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013488 while (rec != null) {
13489 if (rec.time >= 0) rec.writeToParcel(out, 0);
13490 rec = rec.next;
13491 }
13492 out.writeLong(-1);
13493 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013494
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013495 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013496 final int version = in.readInt();
13497 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013498 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013499 + ", expected " + VERSION + "; erasing old stats");
13500 return;
13501 }
13502
Dianne Hackbornae384452011-06-28 12:33:48 -070013503 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013505 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013506 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013507 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013508 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013509 mStartPlatformVersion = in.readString();
13510 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013511 mOnBatteryTimeBase.readSummaryFromParcel(in);
13512 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013513 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013514 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013515 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013516 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013517 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013518 mMinLearnedBatteryCapacity = in.readInt();
13519 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013520 mLowDischargeAmountSinceCharge = in.readInt();
13521 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013522 mDischargeAmountScreenOnSinceCharge = in.readInt();
13523 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013524 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013525 mDischargeStepTracker.readFromParcel(in);
13526 mChargeStepTracker.readFromParcel(in);
13527 mDailyDischargeStepTracker.readFromParcel(in);
13528 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013529 mDischargeCounter.readSummaryFromParcelLocked(in);
13530 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013531 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013532 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13533 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013534 int NPKG = in.readInt();
13535 if (NPKG > 0) {
13536 mDailyPackageChanges = new ArrayList<>(NPKG);
13537 while (NPKG > 0) {
13538 NPKG--;
13539 PackageChange pc = new PackageChange();
13540 pc.mPackageName = in.readString();
13541 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013542 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013543 mDailyPackageChanges.add(pc);
13544 }
13545 } else {
13546 mDailyPackageChanges = null;
13547 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013548 mDailyStartTime = in.readLong();
13549 mNextMinDailyDeadline = in.readLong();
13550 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013552 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013553
Jeff Browne95c3cd2014-05-02 16:59:26 -070013554 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013555 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013556 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013557 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13558 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13559 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013560 mInteractive = false;
13561 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013562 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013563 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013564 mLongestLightIdleTime = in.readLong();
13565 mLongestFullIdleTime = in.readLong();
13566 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13567 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13568 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013569 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013570 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013571 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013572 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13573 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013574 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013575 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13576 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13577 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013578 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013579 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13580 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013581 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013582 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013583 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013584 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013585 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013586 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13587 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013588 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013589 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013590 mWifiOn = false;
13591 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013592 mGlobalWifiRunning = false;
13593 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013594 for (int i=0; i<NUM_WIFI_STATES; i++) {
13595 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13596 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013597 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13598 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13599 }
13600 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13601 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13602 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013603 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13604 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013605 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13606 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13607 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013608 mBluetoothActivity.readSummaryFromParcel(in);
13609 mModemActivity.readSummaryFromParcel(in);
13610 mHasWifiReporting = in.readInt() != 0;
13611 mHasBluetoothReporting = in.readInt() != 0;
13612 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013613
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013614 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013615 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013616 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013617 mCameraOnNesting = 0;
13618 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013619 mBluetoothScanNesting = 0;
13620 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080013621 mIsCellularTxPowerHigh = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013622
Bookatz50df7112017-08-04 14:53:26 -070013623 int NRPMS = in.readInt();
13624 if (NRPMS > 10000) {
13625 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13626 }
13627 for (int irpm = 0; irpm < NRPMS; irpm++) {
13628 if (in.readInt() != 0) {
13629 String rpmName = in.readString();
13630 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13631 }
13632 }
13633 int NSORPMS = in.readInt();
13634 if (NSORPMS > 10000) {
13635 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13636 }
13637 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13638 if (in.readInt() != 0) {
13639 String rpmName = in.readString();
13640 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13641 }
13642 }
13643
Evan Millarc64edde2009-04-18 12:26:32 -070013644 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013645 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013646 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013647 }
Evan Millarc64edde2009-04-18 12:26:32 -070013648 for (int ikw = 0; ikw < NKW; ikw++) {
13649 if (in.readInt() != 0) {
13650 String kwltName = in.readString();
13651 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13652 }
13653 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013654
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013655 int NWR = in.readInt();
13656 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013657 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013658 }
13659 for (int iwr = 0; iwr < NWR; iwr++) {
13660 if (in.readInt() != 0) {
13661 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013662 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013663 }
13664 }
13665
James Carr3a226052016-07-01 14:49:52 -070013666 int NMS = in.readInt();
13667 for (int ims = 0; ims < NMS; ims++) {
13668 if (in.readInt() != 0) {
13669 long kmstName = in.readLong();
13670 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13671 }
13672 }
13673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013674 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013675 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013676 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013678 for (int iu = 0; iu < NU; iu++) {
13679 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013680 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013681 mUidStats.put(uid, u);
13682
Bookatz867c0d72017-03-07 18:23:42 -080013683 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013684 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013685
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013686 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013687 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013688 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013689 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013690 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013691 if (in.readInt() != 0) {
13692 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13693 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013694 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013695 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013696 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013697 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013698 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13699 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13700 if (in.readInt() != 0) {
13701 u.makeWifiBatchedScanBin(i, null);
13702 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13703 }
13704 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013705 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013706 if (in.readInt() != 0) {
13707 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13708 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013709 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013710 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013711 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013712 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013713 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13714 }
13715 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013716 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13717 }
13718 if (in.readInt() != 0) {
13719 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13720 }
13721 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013722 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13723 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013724 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013725 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13726 }
13727 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013728 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13729 }
13730 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013731 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13732 }
Bookatz956f36bf2017-04-28 09:48:17 -070013733 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013734 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13735 }
13736 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013737 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13738 }
Bookatzb1f04f32017-05-19 13:57:32 -070013739 if (in.readInt() != 0) {
13740 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13741 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013742 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013743 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13744 if (in.readInt() != 0) {
13745 u.makeProcessState(i, null);
13746 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13747 }
13748 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013749 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013750 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013751 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013752
Dianne Hackborn617f8772009-03-31 15:04:46 -070013753 if (in.readInt() != 0) {
13754 if (u.mUserActivityCounters == null) {
13755 u.initUserActivityLocked();
13756 }
13757 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13758 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13759 }
13760 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013761
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013762 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013763 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013764 u.initNetworkActivityLocked();
13765 }
13766 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013767 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13768 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013769 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013770 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13771 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013772 }
13773
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013774 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13775 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13776
Adam Lesinski6832f392015-09-05 18:05:40 -070013777 if (in.readInt() != 0) {
13778 final int numClusters = in.readInt();
13779 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13780 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013781 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013782
Sudheer Shankaaf857412017-07-21 00:14:24 -070013783 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013784 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013785 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013786 final int NSB = in.readInt();
13787 if (mPowerProfile != null &&
13788 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13789 throw new ParcelFormatException("File corrupt: too many speed bins " +
13790 NSB);
13791 }
13792
Sudheer Shankaaf857412017-07-21 00:14:24 -070013793 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070013794 for (int speed = 0; speed < NSB; speed++) {
13795 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013796 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070013797 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013798 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070013799 }
13800 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070013801 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013802 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070013803 }
13804 }
13805 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013806 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013807 }
13808
Sudheer Shanka59f5c002017-05-15 10:57:15 -070013809 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13810 in, mOnBatteryTimeBase);
13811 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13812 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070013813
13814 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
13815 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
13816
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013817 int length = in.readInt();
13818 if (length == Uid.NUM_PROCESS_STATE) {
13819 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
13820 for (int procState = 0; procState < length; ++procState) {
13821 u.mProcStateTimeMs[procState]
13822 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13823 in, mOnBatteryTimeBase);
13824 }
13825 } else {
13826 u.mProcStateTimeMs = null;
13827 }
13828 length = in.readInt();
13829 if (length == Uid.NUM_PROCESS_STATE) {
13830 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
13831 for (int procState = 0; procState < length; ++procState) {
13832 u.mProcStateScreenOffTimeMs[procState]
13833 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13834 in, mOnBatteryScreenOffTimeBase);
13835 }
13836 } else {
13837 u.mProcStateScreenOffTimeMs = null;
13838 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070013839
13840 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070013841 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13842 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
13843 } else {
13844 u.mMobileRadioApWakeupCount = null;
13845 }
13846
13847 if (in.readInt() != 0) {
13848 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13849 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
13850 } else {
13851 u.mWifiRadioApWakeupCount = null;
13852 }
13853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013854 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013855 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013856 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013858 for (int iw = 0; iw < NW; iw++) {
13859 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013860 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013861 }
13862
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013863 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013864 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013865 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013866 }
13867 for (int is = 0; is < NS; is++) {
13868 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013869 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013870 }
13871
13872 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013873 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013874 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013875 }
13876 for (int ij = 0; ij < NJ; ij++) {
13877 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013878 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013879 }
13880
Dianne Hackborn94326cb2017-06-28 16:17:20 -070013881 u.readJobCompletionsFromParcelLocked(in);
13882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013883 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013884 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013885 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013887 for (int is = 0; is < NP; is++) {
13888 int seNumber = in.readInt();
13889 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080013890 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013891 }
13892 }
13893
13894 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013895 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013896 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013898 for (int ip = 0; ip < NP; ip++) {
13899 String procName = in.readString();
13900 Uid.Proc p = u.getProcessStatsLocked(procName);
13901 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013902 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013903 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013904 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013905 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
13906 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013907 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013908 }
13909
13910 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013911 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013912 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013914 for (int ip = 0; ip < NP; ip++) {
13915 String pkgName = in.readString();
13916 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013917 final int NWA = in.readInt();
13918 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013919 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013920 }
13921 p.mWakeupAlarms.clear();
13922 for (int iwa=0; iwa<NWA; iwa++) {
13923 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070013924 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013925 c.readSummaryFromParcelLocked(in);
13926 p.mWakeupAlarms.put(tag, c);
13927 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013928 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013929 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013930 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013932 for (int is = 0; is < NS; is++) {
13933 String servName = in.readString();
13934 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
13935 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013936 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013937 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013938 }
13939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013940 }
13941 }
13942
13943 /**
13944 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
13945 * disk. This format does not allow a lossless round-trip.
13946 *
13947 * @param out the Parcel to be written to.
13948 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013949 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013950 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013951
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013952 // Pull the clock time. This may update the time and make a new history entry
13953 // if we had originally pulled a time before the RTC was set.
13954 long startClockTime = getStartClockTime();
13955
Joe Onoratoabded112016-02-08 16:49:39 -080013956 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
13957 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013958
13959 out.writeInt(VERSION);
13960
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013961 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013963 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013964 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013965 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013966 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013967 out.writeString(mStartPlatformVersion);
13968 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013969 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
13970 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013971 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013972 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070013973 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013974 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013975 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070013976 out.writeInt(mMinLearnedBatteryCapacity);
13977 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080013978 out.writeInt(getLowDischargeAmountSinceCharge());
13979 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013980 out.writeInt(getDischargeAmountScreenOnSinceCharge());
13981 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070013982 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013983 mDischargeStepTracker.writeToParcel(out);
13984 mChargeStepTracker.writeToParcel(out);
13985 mDailyDischargeStepTracker.writeToParcel(out);
13986 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070013987 mDischargeCounter.writeSummaryFromParcelLocked(out);
13988 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070013989 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080013990 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
13991 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013992 if (mDailyPackageChanges != null) {
13993 final int NPKG = mDailyPackageChanges.size();
13994 out.writeInt(NPKG);
13995 for (int i=0; i<NPKG; i++) {
13996 PackageChange pc = mDailyPackageChanges.get(i);
13997 out.writeString(pc.mPackageName);
13998 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070013999 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014000 }
14001 } else {
14002 out.writeInt(0);
14003 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014004 out.writeLong(mDailyStartTime);
14005 out.writeLong(mNextMinDailyDeadline);
14006 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014007
14008 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070014009 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014010 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014011 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014012 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014013 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014014 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014015 out.writeLong(mLongestLightIdleTime);
14016 out.writeLong(mLongestFullIdleTime);
14017 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14018 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14019 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014020 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014021 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080014022 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014023 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014024 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014025 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014026 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014027 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014028 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014029 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014030 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14031 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014032 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014033 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14034 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014035 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014036 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
14037 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014038 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014039 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14040 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014041 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014042 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014043 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014044 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14045 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14046 }
14047 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14048 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14049 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014050 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14051 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014052 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14053 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14054 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014055 mBluetoothActivity.writeSummaryToParcel(out);
14056 mModemActivity.writeSummaryToParcel(out);
14057 out.writeInt(mHasWifiReporting ? 1 : 0);
14058 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14059 out.writeInt(mHasModemReporting ? 1 : 0);
14060
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014061 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014062 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014063 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014064 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014065
Bookatz50df7112017-08-04 14:53:26 -070014066 out.writeInt(mRpmStats.size());
14067 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14068 Timer rpmt = ent.getValue();
14069 if (rpmt != null) {
14070 out.writeInt(1);
14071 out.writeString(ent.getKey());
14072 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14073 } else {
14074 out.writeInt(0);
14075 }
14076 }
14077 out.writeInt(mScreenOffRpmStats.size());
14078 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14079 Timer rpmt = ent.getValue();
14080 if (rpmt != null) {
14081 out.writeInt(1);
14082 out.writeString(ent.getKey());
14083 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14084 } else {
14085 out.writeInt(0);
14086 }
14087 }
14088
Evan Millarc64edde2009-04-18 12:26:32 -070014089 out.writeInt(mKernelWakelockStats.size());
14090 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14091 Timer kwlt = ent.getValue();
14092 if (kwlt != null) {
14093 out.writeInt(1);
14094 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014095 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14096 } else {
14097 out.writeInt(0);
14098 }
14099 }
14100
14101 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014102 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14103 SamplingTimer timer = ent.getValue();
14104 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014105 out.writeInt(1);
14106 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014107 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014108 } else {
14109 out.writeInt(0);
14110 }
14111 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014112
James Carr3a226052016-07-01 14:49:52 -070014113 out.writeInt(mKernelMemoryStats.size());
14114 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14115 Timer kmt = mKernelMemoryStats.valueAt(i);
14116 if (kmt != null) {
14117 out.writeInt(1);
14118 out.writeLong(mKernelMemoryStats.keyAt(i));
14119 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14120 } else {
14121 out.writeInt(0);
14122 }
14123 }
14124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014125 final int NU = mUidStats.size();
14126 out.writeInt(NU);
14127 for (int iu = 0; iu < NU; iu++) {
14128 out.writeInt(mUidStats.keyAt(iu));
14129 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014130
Bookatz867c0d72017-03-07 18:23:42 -080014131 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014132 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014133
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014134 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014135 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014136 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014137 } else {
14138 out.writeInt(0);
14139 }
14140 if (u.mFullWifiLockTimer != null) {
14141 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014142 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014143 } else {
14144 out.writeInt(0);
14145 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014146 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014147 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014148 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014149 } else {
14150 out.writeInt(0);
14151 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014152 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14153 if (u.mWifiBatchedScanTimer[i] != null) {
14154 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014155 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014156 } else {
14157 out.writeInt(0);
14158 }
14159 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014160 if (u.mWifiMulticastTimer != null) {
14161 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014162 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014163 } else {
14164 out.writeInt(0);
14165 }
14166 if (u.mAudioTurnedOnTimer != null) {
14167 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014168 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014169 } else {
14170 out.writeInt(0);
14171 }
14172 if (u.mVideoTurnedOnTimer != null) {
14173 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014174 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014175 } else {
14176 out.writeInt(0);
14177 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014178 if (u.mFlashlightTurnedOnTimer != null) {
14179 out.writeInt(1);
14180 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14181 } else {
14182 out.writeInt(0);
14183 }
14184 if (u.mCameraTurnedOnTimer != null) {
14185 out.writeInt(1);
14186 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14187 } else {
14188 out.writeInt(0);
14189 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014190 if (u.mForegroundActivityTimer != null) {
14191 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014192 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014193 } else {
14194 out.writeInt(0);
14195 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014196 if (u.mForegroundServiceTimer != null) {
14197 out.writeInt(1);
14198 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14199 } else {
14200 out.writeInt(0);
14201 }
Bookatzc8c44962017-05-11 12:12:54 -070014202 if (u.mAggregatedPartialWakelockTimer != null) {
14203 out.writeInt(1);
14204 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14205 } else {
14206 out.writeInt(0);
14207 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014208 if (u.mBluetoothScanTimer != null) {
14209 out.writeInt(1);
14210 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14211 } else {
14212 out.writeInt(0);
14213 }
Bookatzb1f04f32017-05-19 13:57:32 -070014214 if (u.mBluetoothUnoptimizedScanTimer != null) {
14215 out.writeInt(1);
14216 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14217 } else {
14218 out.writeInt(0);
14219 }
Bookatz956f36bf2017-04-28 09:48:17 -070014220 if (u.mBluetoothScanResultCounter != null) {
14221 out.writeInt(1);
14222 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14223 } else {
14224 out.writeInt(0);
14225 }
Bookatzb1f04f32017-05-19 13:57:32 -070014226 if (u.mBluetoothScanResultBgCounter != null) {
14227 out.writeInt(1);
14228 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14229 } else {
14230 out.writeInt(0);
14231 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014232 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14233 if (u.mProcessStateTimer[i] != null) {
14234 out.writeInt(1);
14235 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14236 } else {
14237 out.writeInt(0);
14238 }
14239 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014240 if (u.mVibratorOnTimer != null) {
14241 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014242 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014243 } else {
14244 out.writeInt(0);
14245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014246
Dianne Hackborn617f8772009-03-31 15:04:46 -070014247 if (u.mUserActivityCounters == null) {
14248 out.writeInt(0);
14249 } else {
14250 out.writeInt(1);
14251 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14252 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14253 }
14254 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014255
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014256 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014257 out.writeInt(0);
14258 } else {
14259 out.writeInt(1);
14260 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014261 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14262 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014263 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014264 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14265 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014266 }
14267
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014268 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14269 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14270
Sudheer Shankaaf857412017-07-21 00:14:24 -070014271 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014272 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014273 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14274 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014275 if (cpuSpeeds != null) {
14276 out.writeInt(1);
14277 out.writeInt(cpuSpeeds.length);
14278 for (LongSamplingCounter c : cpuSpeeds) {
14279 if (c != null) {
14280 out.writeInt(1);
14281 c.writeSummaryFromParcelLocked(out);
14282 } else {
14283 out.writeInt(0);
14284 }
14285 }
14286 } else {
14287 out.writeInt(0);
14288 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014289 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014290 } else {
14291 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014292 }
14293
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014294 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14295 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014296
Mike Ma3d422c32017-10-25 11:08:57 -070014297 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14298 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14299
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014300 if (u.mProcStateTimeMs != null) {
14301 out.writeInt(u.mProcStateTimeMs.length);
14302 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14303 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14304 }
14305 } else {
14306 out.writeInt(0);
14307 }
14308 if (u.mProcStateScreenOffTimeMs != null) {
14309 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14310 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14311 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14312 }
14313 } else {
14314 out.writeInt(0);
14315 }
14316
Adam Lesinski5f056f62016-07-14 16:56:08 -070014317 if (u.mMobileRadioApWakeupCount != null) {
14318 out.writeInt(1);
14319 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14320 } else {
14321 out.writeInt(0);
14322 }
14323
14324 if (u.mWifiRadioApWakeupCount != null) {
14325 out.writeInt(1);
14326 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14327 } else {
14328 out.writeInt(0);
14329 }
14330
Dianne Hackbornd953c532014-08-16 18:17:38 -070014331 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14332 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014333 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014334 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014335 out.writeString(wakeStats.keyAt(iw));
14336 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014337 if (wl.mTimerFull != null) {
14338 out.writeInt(1);
14339 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14340 } else {
14341 out.writeInt(0);
14342 }
14343 if (wl.mTimerPartial != null) {
14344 out.writeInt(1);
14345 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14346 } else {
14347 out.writeInt(0);
14348 }
14349 if (wl.mTimerWindow != null) {
14350 out.writeInt(1);
14351 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14352 } else {
14353 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014354 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014355 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014356 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014357 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014358 } else {
14359 out.writeInt(0);
14360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014361 }
14362
Bookatz2bffb5b2017-04-13 11:59:33 -070014363 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014364 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014365 out.writeInt(NS);
14366 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014367 out.writeString(syncStats.keyAt(is));
14368 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014369 }
14370
Bookatzaa4594a2017-03-24 12:39:56 -070014371 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014372 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014373 out.writeInt(NJ);
14374 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014375 out.writeString(jobStats.keyAt(ij));
14376 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014377 }
14378
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014379 u.writeJobCompletionsToParcelLocked(out);
14380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014381 int NSE = u.mSensorStats.size();
14382 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014383 for (int ise=0; ise<NSE; ise++) {
14384 out.writeInt(u.mSensorStats.keyAt(ise));
14385 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14386 if (se.mTimer != null) {
14387 out.writeInt(1);
14388 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14389 } else {
14390 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014391 }
14392 }
14393
14394 int NP = u.mProcessStats.size();
14395 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014396 for (int ip=0; ip<NP; ip++) {
14397 out.writeString(u.mProcessStats.keyAt(ip));
14398 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14399 out.writeLong(ps.mUserTime);
14400 out.writeLong(ps.mSystemTime);
14401 out.writeLong(ps.mForegroundTime);
14402 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014403 out.writeInt(ps.mNumCrashes);
14404 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014405 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014406 }
14407
14408 NP = u.mPackageStats.size();
14409 out.writeInt(NP);
14410 if (NP > 0) {
14411 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14412 : u.mPackageStats.entrySet()) {
14413 out.writeString(ent.getKey());
14414 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014415 final int NWA = ps.mWakeupAlarms.size();
14416 out.writeInt(NWA);
14417 for (int iwa=0; iwa<NWA; iwa++) {
14418 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14419 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14420 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014421 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014422 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014423 for (int is=0; is<NS; is++) {
14424 out.writeString(ps.mServiceStats.keyAt(is));
14425 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14426 long time = ss.getStartTimeToNowLocked(
14427 mOnBatteryTimeBase.getUptime(NOW_SYS));
14428 out.writeLong(time);
14429 out.writeInt(ss.mStarts);
14430 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014431 }
14432 }
14433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014434 }
14435 }
14436
14437 public void readFromParcel(Parcel in) {
14438 readFromParcelLocked(in);
14439 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014441 void readFromParcelLocked(Parcel in) {
14442 int magic = in.readInt();
14443 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014444 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014445 }
14446
Dianne Hackbornae384452011-06-28 12:33:48 -070014447 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014449 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014450 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014451 mStartPlatformVersion = in.readString();
14452 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014453 mUptime = in.readLong();
14454 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014455 mRealtime = in.readLong();
14456 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014457 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014458 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014459 mMinLearnedBatteryCapacity = in.readInt();
14460 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014461 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014462 mOnBatteryTimeBase.readFromParcel(in);
14463 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14464
Jeff Browne95c3cd2014-05-02 16:59:26 -070014465 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014466 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014467 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014468 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014469 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14470 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014471 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014472 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014473 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014474 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014475 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14476 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014477 mLongestLightIdleTime = in.readLong();
14478 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014479 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14480 mOnBatteryTimeBase, in);
14481 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14482 mOnBatteryTimeBase, in);
14483 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14484 mOnBatteryTimeBase, in);
14485 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14486 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014487 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014488 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014489 null, mOnBatteryTimeBase, in);
14490 }
Joe Onoratoabded112016-02-08 16:49:39 -080014491 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14492 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014493 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014494 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014495 null, mOnBatteryTimeBase, in);
14496 }
14497 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14498 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14499 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14500 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014501 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014502 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14503 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014504 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014505 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014506 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014507 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14508 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014509 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14510 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014511 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014512 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014513 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014514 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014515 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14516 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014517 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014518 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014519 null, mOnBatteryTimeBase, in);
14520 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014521 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014522 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014523 null, mOnBatteryTimeBase, in);
14524 }
14525 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014526 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014527 null, mOnBatteryTimeBase, in);
14528 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014529 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14530 mOnBatteryTimeBase, in);
14531 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14532 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014533 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14534 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14535 null, mOnBatteryTimeBase, in);
14536 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014537 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14538 NUM_BT_TX_LEVELS, in);
14539 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14540 ModemActivityInfo.TX_POWER_LEVELS, in);
14541 mHasWifiReporting = in.readInt() != 0;
14542 mHasBluetoothReporting = in.readInt() != 0;
14543 mHasModemReporting = in.readInt() != 0;
14544
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014545 mNumConnectivityChange = in.readInt();
14546 mLoadedNumConnectivityChange = in.readInt();
14547 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014548 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014549 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014550 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014551 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014552 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014553 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014554 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014555 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014556 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014557 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080014558 mIsCellularTxPowerHigh = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014559 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014560 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014561 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014562 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014563 mLowDischargeAmountSinceCharge = in.readInt();
14564 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014565 mDischargeAmountScreenOn = in.readInt();
14566 mDischargeAmountScreenOnSinceCharge = in.readInt();
14567 mDischargeAmountScreenOff = in.readInt();
14568 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014569 mDischargeAmountScreenDoze = in.readInt();
14570 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014571 mDischargeStepTracker.readFromParcel(in);
14572 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014573 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014574 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14575 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014576 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14577 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014578 mLastWriteTime = in.readLong();
14579
Bookatz50df7112017-08-04 14:53:26 -070014580 mRpmStats.clear();
14581 int NRPMS = in.readInt();
14582 for (int irpm = 0; irpm < NRPMS; irpm++) {
14583 if (in.readInt() != 0) {
14584 String rpmName = in.readString();
14585 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14586 mRpmStats.put(rpmName, rpmt);
14587 }
14588 }
14589 mScreenOffRpmStats.clear();
14590 int NSORPMS = in.readInt();
14591 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14592 if (in.readInt() != 0) {
14593 String rpmName = in.readString();
14594 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14595 mScreenOffRpmStats.put(rpmName, rpmt);
14596 }
14597 }
14598
Evan Millarc64edde2009-04-18 12:26:32 -070014599 mKernelWakelockStats.clear();
14600 int NKW = in.readInt();
14601 for (int ikw = 0; ikw < NKW; ikw++) {
14602 if (in.readInt() != 0) {
14603 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014604 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014605 mKernelWakelockStats.put(wakelockName, kwlt);
14606 }
14607 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014608
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014609 mWakeupReasonStats.clear();
14610 int NWR = in.readInt();
14611 for (int iwr = 0; iwr < NWR; iwr++) {
14612 if (in.readInt() != 0) {
14613 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014614 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014615 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014616 }
14617 }
14618
James Carr3a226052016-07-01 14:49:52 -070014619 mKernelMemoryStats.clear();
14620 int nmt = in.readInt();
14621 for (int imt = 0; imt < nmt; imt++) {
14622 if (in.readInt() != 0) {
14623 Long bucket = in.readLong();
14624 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14625 mKernelMemoryStats.put(bucket, kmt);
14626 }
14627 }
14628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014629 mPartialTimers.clear();
14630 mFullTimers.clear();
14631 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014632 mWifiRunningTimers.clear();
14633 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014634 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014635 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014636 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014637 mAudioTurnedOnTimers.clear();
14638 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014639 mFlashlightTurnedOnTimers.clear();
14640 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014641
14642 int numUids = in.readInt();
14643 mUidStats.clear();
14644 for (int i = 0; i < numUids; i++) {
14645 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014646 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014647 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014648 mUidStats.append(uid, u);
14649 }
14650 }
14651
14652 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014653 writeToParcelLocked(out, true, flags);
14654 }
14655
14656 public void writeToParcelWithoutUids(Parcel out, int flags) {
14657 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014658 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014659
14660 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014661 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014662 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014663 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014664
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014665 // Pull the clock time. This may update the time and make a new history entry
14666 // if we had originally pulled a time before the RTC was set.
14667 long startClockTime = getStartClockTime();
14668
Joe Onoratoabded112016-02-08 16:49:39 -080014669 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14670 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014671 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14672 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014674 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014675
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014676 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014678 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014679 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014680 out.writeString(mStartPlatformVersion);
14681 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014682 out.writeLong(mUptime);
14683 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014684 out.writeLong(mRealtime);
14685 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014686 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014687 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014688 out.writeInt(mMinLearnedBatteryCapacity);
14689 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014690 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14691 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14692
14693 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014694 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014695 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14696 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14697 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014698 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014699 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014700 out.writeLong(mLongestLightIdleTime);
14701 out.writeLong(mLongestFullIdleTime);
14702 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14703 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14704 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014705 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014706 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14707 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14708 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14709 }
14710 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14711 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14712 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14713 }
14714 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14715 mNetworkByteActivityCounters[i].writeToParcel(out);
14716 mNetworkPacketActivityCounters[i].writeToParcel(out);
14717 }
14718 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14719 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014720 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014721 mMobileRadioActiveUnknownTime.writeToParcel(out);
14722 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014723 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014724 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14725 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14726 for (int i=0; i<NUM_WIFI_STATES; i++) {
14727 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14728 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014729 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14730 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14731 }
14732 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14733 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14734 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014735 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
14736 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014737 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14738 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
14739 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014740 mBluetoothActivity.writeToParcel(out, 0);
14741 mModemActivity.writeToParcel(out, 0);
14742 out.writeInt(mHasWifiReporting ? 1 : 0);
14743 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14744 out.writeInt(mHasModemReporting ? 1 : 0);
14745
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014746 out.writeInt(mNumConnectivityChange);
14747 out.writeInt(mLoadedNumConnectivityChange);
14748 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014749 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014750 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014751 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014752 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014753 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014754 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014755 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014756 out.writeInt(mLowDischargeAmountSinceCharge);
14757 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014758 out.writeInt(mDischargeAmountScreenOn);
14759 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14760 out.writeInt(mDischargeAmountScreenOff);
14761 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014762 out.writeInt(mDischargeAmountScreenDoze);
14763 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014764 mDischargeStepTracker.writeToParcel(out);
14765 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014766 mDischargeCounter.writeToParcel(out);
14767 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014768 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080014769 mDischargeLightDozeCounter.writeToParcel(out);
14770 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014771 out.writeLong(mLastWriteTime);
14772
Bookatz50df7112017-08-04 14:53:26 -070014773 out.writeInt(mRpmStats.size());
14774 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14775 SamplingTimer rpmt = ent.getValue();
14776 if (rpmt != null) {
14777 out.writeInt(1);
14778 out.writeString(ent.getKey());
14779 rpmt.writeToParcel(out, uSecRealtime);
14780 } else {
14781 out.writeInt(0);
14782 }
14783 }
14784 out.writeInt(mScreenOffRpmStats.size());
14785 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14786 SamplingTimer rpmt = ent.getValue();
14787 if (rpmt != null) {
14788 out.writeInt(1);
14789 out.writeString(ent.getKey());
14790 rpmt.writeToParcel(out, uSecRealtime);
14791 } else {
14792 out.writeInt(0);
14793 }
14794 }
14795
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014796 if (inclUids) {
14797 out.writeInt(mKernelWakelockStats.size());
14798 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14799 SamplingTimer kwlt = ent.getValue();
14800 if (kwlt != null) {
14801 out.writeInt(1);
14802 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014803 kwlt.writeToParcel(out, uSecRealtime);
14804 } else {
14805 out.writeInt(0);
14806 }
14807 }
14808 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014809 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14810 SamplingTimer timer = ent.getValue();
14811 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014812 out.writeInt(1);
14813 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014814 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014815 } else {
14816 out.writeInt(0);
14817 }
Evan Millarc64edde2009-04-18 12:26:32 -070014818 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014819 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070014820 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014821 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070014822 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070014823
James Carr3a226052016-07-01 14:49:52 -070014824 out.writeInt(mKernelMemoryStats.size());
14825 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14826 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
14827 if (kmt != null) {
14828 out.writeInt(1);
14829 out.writeLong(mKernelMemoryStats.keyAt(i));
14830 kmt.writeToParcel(out, uSecRealtime);
14831 } else {
14832 out.writeInt(0);
14833 }
14834 }
14835
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014836 if (inclUids) {
14837 int size = mUidStats.size();
14838 out.writeInt(size);
14839 for (int i = 0; i < size; i++) {
14840 out.writeInt(mUidStats.keyAt(i));
14841 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014842
Bookatz867c0d72017-03-07 18:23:42 -080014843 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014844 }
14845 } else {
14846 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014847 }
14848 }
14849
14850 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
14851 new Parcelable.Creator<BatteryStatsImpl>() {
14852 public BatteryStatsImpl createFromParcel(Parcel in) {
14853 return new BatteryStatsImpl(in);
14854 }
14855
14856 public BatteryStatsImpl[] newArray(int size) {
14857 return new BatteryStatsImpl[size];
14858 }
14859 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014860
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014861 public void prepareForDumpLocked() {
14862 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014863 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014864
14865 // Pull the clock time. This may update the time and make a new history entry
14866 // if we had originally pulled a time before the RTC was set.
14867 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014868 }
14869
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014870 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014871 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014872 pw.println("mOnBatteryTimeBase:");
14873 mOnBatteryTimeBase.dump(pw, " ");
14874 pw.println("mOnBatteryScreenOffTimeBase:");
14875 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014876 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070014877 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014878 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070014879 pr.println("*** Screen doze timer:");
14880 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014881 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014882 pr.println("*** Screen brightness #" + i + ":");
14883 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014884 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014885 pr.println("*** Interactive timer:");
14886 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014887 pr.println("*** Power save mode timer:");
14888 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014889 pr.println("*** Device idle mode light timer:");
14890 mDeviceIdleModeLightTimer.logState(pr, " ");
14891 pr.println("*** Device idle mode full timer:");
14892 mDeviceIdleModeFullTimer.logState(pr, " ");
14893 pr.println("*** Device light idling timer:");
14894 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014895 pr.println("*** Device idling timer:");
14896 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014897 pr.println("*** Phone timer:");
14898 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080014899 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070014900 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014901 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014902 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070014903 pr.println("*** Signal scanning :");
14904 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014905 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014906 pr.println("*** Data connection type #" + i + ":");
14907 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014908 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014909 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080014910 pr.println("*** Mobile network active timer:");
14911 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014912 pr.println("*** Mobile network active adjusted timer:");
14913 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014914 pr.println("*** Wifi Multicast WakeLock Timer:");
14915 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014916 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014917 pr.println("*** Wifi timer:");
14918 mWifiOnTimer.logState(pr, " ");
14919 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014920 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014921 for (int i=0; i<NUM_WIFI_STATES; i++) {
14922 pr.println("*** Wifi state #" + i + ":");
14923 mWifiStateTimer[i].logState(pr, " ");
14924 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014925 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14926 pr.println("*** Wifi suppl state #" + i + ":");
14927 mWifiSupplStateTimer[i].logState(pr, " ");
14928 }
14929 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14930 pr.println("*** Wifi signal strength #" + i + ":");
14931 mWifiSignalStrengthsTimer[i].logState(pr, " ");
14932 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014933 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14934 pr.println("*** GPS signal quality #" + i + ":");
14935 mGpsSignalQualityTimer[i].logState(pr, " ");
14936 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014937 pr.println("*** Flashlight timer:");
14938 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014939 pr.println("*** Camera timer:");
14940 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014941 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014942 super.dumpLocked(context, pw, flags, reqUid, histStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014944}