blob: d837518a9755cc2426b6a72cb72549c3ed706bb8 [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;
Mike Ma2ab01442018-02-13 14:22:47 -0800113import java.util.concurrent.ExecutorService;
114import java.util.concurrent.Executors;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700115import java.util.concurrent.Future;
Mike Ma2ab01442018-02-13 14:22:47 -0800116import java.util.concurrent.ThreadFactory;
Christopher Tate4cee7252010-03-19 14:50:40 -0700117import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700118import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
120/**
121 * All information we are collecting about things that can happen that impact
122 * battery life. All times are represented in microseconds except where indicated
123 * otherwise.
124 */
Joe Onoratoabded112016-02-08 16:49:39 -0800125public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800127 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700128 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800129 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700130 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700131 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700132 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700133
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700134 // TODO: remove "tcp" from network methods, since we measure total stats.
135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700137 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
139 // Current on-disk Parcel version
Adam Lesinski14082082018-02-23 12:35:55 -0800140 private static final int VERSION = 176 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700141
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700142 // Maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100143 private static final int MAX_HISTORY_ITEMS;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700144
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700145 // No, really, THIS is the maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100146 private static final int MAX_MAX_HISTORY_ITEMS;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700147
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800148 // The maximum number of names wakelocks we will keep track of
149 // per uid; once the limit is reached, we batch the remaining wakelocks
150 // in to one common name.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100151 private static final int MAX_WAKELOCKS_PER_UID;
152
153 static final int MAX_HISTORY_BUFFER; // 256KB
154 static final int MAX_MAX_HISTORY_BUFFER; // 320KB
155
156 static {
157 if (ActivityManager.isLowRamDeviceStatic()) {
158 MAX_HISTORY_ITEMS = 800;
159 MAX_MAX_HISTORY_ITEMS = 1200;
160 MAX_WAKELOCKS_PER_UID = 40;
161 MAX_HISTORY_BUFFER = 96*1024; // 96KB
162 MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
163 } else {
Makoto Onuki44d64602018-01-18 08:44:28 -0800164 MAX_HISTORY_ITEMS = 4000;
165 MAX_MAX_HISTORY_ITEMS = 6000;
166 MAX_WAKELOCKS_PER_UID = 200;
167 MAX_HISTORY_BUFFER = 512*1024; // 512KB
168 MAX_MAX_HISTORY_BUFFER = 640*1024; // 640KB
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100169 }
170 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700171
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800172 // Number of transmit power states the Wifi controller can be in.
173 private static final int NUM_WIFI_TX_LEVELS = 1;
174
175 // Number of transmit power states the Bluetooth controller can be in.
176 private static final int NUM_BT_TX_LEVELS = 1;
177
Sudheer Shanka38383232017-07-25 09:55:03 -0700178 /**
179 * Holding a wakelock costs more than just using the cpu.
180 * Currently, we assign only half the cpu time to an app that is running but
181 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
182 * If no app is holding a wakelock, then the distribution is normal.
183 */
184 @VisibleForTesting
185 public static final int WAKE_LOCK_WEIGHT = 50;
186
Joe Onoratoabded112016-02-08 16:49:39 -0800187 protected Clocks mClocks;
188
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700189 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700190 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800191 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
Sudheer Shankac57729a2018-02-09 15:44:42 -0800193 static final int MSG_REPORT_CPU_UPDATE_NEEDED = 1;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700194 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700195 static final int MSG_REPORT_CHARGING = 3;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700196 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700197
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700198 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
199 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
200
Sudheer Shanka38383232017-07-25 09:55:03 -0700201 @VisibleForTesting
202 protected KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
203 @VisibleForTesting
204 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
205 @VisibleForTesting
206 protected KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700207 new KernelUidCpuFreqTimeReader();
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800208 @VisibleForTesting
Mike Ma3d422c32017-10-25 11:08:57 -0700209 protected KernelUidCpuActiveTimeReader mKernelUidCpuActiveTimeReader =
210 new KernelUidCpuActiveTimeReader();
211 @VisibleForTesting
212 protected KernelUidCpuClusterTimeReader mKernelUidCpuClusterTimeReader =
213 new KernelUidCpuClusterTimeReader();
214 @VisibleForTesting
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800215 protected KernelSingleUidTimeReader mKernelSingleUidTimeReader;
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700216
James Carr3a226052016-07-01 14:49:52 -0700217 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
218 = new KernelMemoryBandwidthStats();
219 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
220 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
221 return mKernelMemoryStats;
222 }
223
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800224 @GuardedBy("this")
225 public boolean mPerProcStateCpuTimesAvailable = true;
226
227 /**
228 * Uids for which per-procstate cpu times need to be updated.
229 *
230 * Contains uid -> procState mappings.
231 */
232 @GuardedBy("this")
233 @VisibleForTesting
234 protected final SparseIntArray mPendingUids = new SparseIntArray();
235
Sudheer Shankac20379e2018-02-15 00:06:21 -0800236 @GuardedBy("this")
237 private long mNumCpuTimeReads;
238 @GuardedBy("this")
239 private long mNumBatchedCpuTimeReads;
240 @GuardedBy("this")
241 private long mCpuTimeReadsTrackingStartTime = SystemClock.uptimeMillis();
242
Bookatz0b8a0502017-09-13 11:51:52 -0700243 /** Container for Resource Power Manager stats. Updated by updateRpmStatsLocked. */
Bookatz50df7112017-08-04 14:53:26 -0700244 private final RpmStats mTmpRpmStats = new RpmStats();
Bookatz0b8a0502017-09-13 11:51:52 -0700245 /** The soonest the RPM stats can be updated after it was last updated. */
246 private static final long RPM_STATS_UPDATE_FREQ_MS = 1000;
247 /** Last time that RPM stats were updated by updateRpmStatsLocked. */
248 private long mLastRpmStatsUpdateTimeMs = -RPM_STATS_UPDATE_FREQ_MS;
Bookatz50df7112017-08-04 14:53:26 -0700249
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700250 public interface BatteryCallback {
251 public void batteryNeedsCpuUpdate();
252 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700253 public void batterySendBroadcast(Intent intent);
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700254 }
255
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700256 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700257 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700258 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000259 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700260 }
261
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700262 public static abstract class UserInfoProvider {
263 private int[] userIds;
264 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700265 @VisibleForTesting
266 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700267 userIds = getUserIds();
268 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700269 @VisibleForTesting
270 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700271 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
272 }
273 }
274
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700275 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
276
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700277 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800278 public MyHandler(Looper looper) {
279 super(looper, null, true);
280 }
281
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700282 @Override
283 public void handleMessage(Message msg) {
284 BatteryCallback cb = mCallback;
285 switch (msg.what) {
Sudheer Shankac57729a2018-02-09 15:44:42 -0800286 case MSG_REPORT_CPU_UPDATE_NEEDED:
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700287 if (cb != null) {
288 cb.batteryNeedsCpuUpdate();
289 }
290 break;
291 case MSG_REPORT_POWER_CHANGE:
292 if (cb != null) {
293 cb.batteryPowerChanged(msg.arg1 != 0);
294 }
295 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700296 case MSG_REPORT_CHARGING:
297 if (cb != null) {
298 final String action;
299 synchronized (BatteryStatsImpl.this) {
300 action = mCharging ? BatteryManager.ACTION_CHARGING
301 : BatteryManager.ACTION_DISCHARGING;
302 }
303 Intent intent = new Intent(action);
304 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
305 cb.batterySendBroadcast(intent);
306 }
307 break;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700308 }
309 }
310 }
311
Sudheer Shankac57729a2018-02-09 15:44:42 -0800312 public void postBatteryNeedsCpuUpdateMsg() {
313 mHandler.sendEmptyMessage(MSG_REPORT_CPU_UPDATE_NEEDED);
314 }
315
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800316 /**
317 * Update per-freq cpu times for all the uids in {@link #mPendingUids}.
318 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800319 public void updateProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800320 final SparseIntArray uidStates;
321 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800322 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
323 return;
324 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800325 if(!initKernelSingleUidTimeReaderLocked()) {
326 return;
327 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800328 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
329 // compute deltas since it might result in mis-attributing cpu times to wrong states.
330 if (mKernelSingleUidTimeReader.hasStaleData()) {
331 mPendingUids.clear();
332 return;
333 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800334
335 if (mPendingUids.size() == 0) {
336 return;
337 }
338 uidStates = mPendingUids.clone();
339 mPendingUids.clear();
340 }
341 for (int i = uidStates.size() - 1; i >= 0; --i) {
342 final int uid = uidStates.keyAt(i);
343 final int procState = uidStates.valueAt(i);
344 final int[] isolatedUids;
345 final Uid u;
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800346 synchronized (BatteryStatsImpl.this) {
347 // It's possible that uid no longer exists and any internal references have
348 // already been deleted, so using {@link #getAvailableUidStatsLocked} to avoid
349 // creating an UidStats object if it doesn't already exist.
350 u = getAvailableUidStatsLocked(uid);
351 if (u == null) {
352 continue;
353 }
354 if (u.mChildUids == null) {
355 isolatedUids = null;
356 } else {
357 isolatedUids = u.mChildUids.toArray();
358 for (int j = isolatedUids.length - 1; j >= 0; --j) {
359 isolatedUids[j] = u.mChildUids.get(j);
360 }
361 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800362 }
363 long[] cpuTimesMs = mKernelSingleUidTimeReader.readDeltaMs(uid);
364 if (isolatedUids != null) {
365 for (int j = isolatedUids.length - 1; j >= 0; --j) {
366 cpuTimesMs = addCpuTimes(cpuTimesMs,
367 mKernelSingleUidTimeReader.readDeltaMs(isolatedUids[j]));
368 }
369 }
370 if (onBattery && cpuTimesMs != null) {
371 synchronized (BatteryStatsImpl.this) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800372 u.addProcStateTimesMs(procState, cpuTimesMs, onBattery);
373 u.addProcStateScreenOffTimesMs(procState, cpuTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800374 }
375 }
376 }
377 }
378
Sudheer Shankae544d162017-12-28 17:06:20 -0800379 public void copyFromAllUidsCpuTimes() {
380 synchronized (BatteryStatsImpl.this) {
381 copyFromAllUidsCpuTimes(
382 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
383 }
384 }
385
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800386 /**
387 * When the battery/screen state changes, we don't attribute the cpu times to any process
388 * but we still need to snapshots of all uids to get correct deltas later on. Since we
389 * already read this data for updating per-freq cpu times, we can use the same data for
390 * per-procstate cpu times.
391 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800392 public void copyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800393 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800394 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
395 return;
396 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800397 if(!initKernelSingleUidTimeReaderLocked()) {
398 return;
399 }
400
401 final SparseArray<long[]> allUidCpuFreqTimesMs =
402 mKernelUidCpuFreqTimeReader.getAllUidCpuFreqTimeMs();
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800403 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
404 // compute deltas since it might result in mis-attributing cpu times to wrong states.
405 if (mKernelSingleUidTimeReader.hasStaleData()) {
406 mKernelSingleUidTimeReader.setAllUidsCpuTimesMs(allUidCpuFreqTimesMs);
407 mKernelSingleUidTimeReader.markDataAsStale(false);
408 mPendingUids.clear();
409 return;
410 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800411 for (int i = allUidCpuFreqTimesMs.size() - 1; i >= 0; --i) {
412 final int uid = allUidCpuFreqTimesMs.keyAt(i);
413 final Uid u = getAvailableUidStatsLocked(mapUid(uid));
414 if (u == null) {
415 continue;
416 }
417 final long[] cpuTimesMs = allUidCpuFreqTimesMs.valueAt(i);
418 if (cpuTimesMs == null) {
419 continue;
420 }
421 final long[] deltaTimesMs = mKernelSingleUidTimeReader.computeDelta(
422 uid, cpuTimesMs.clone());
Sudheer Shankae544d162017-12-28 17:06:20 -0800423 if (onBattery && deltaTimesMs != null) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800424 final int procState;
425 final int idx = mPendingUids.indexOfKey(uid);
426 if (idx >= 0) {
427 procState = mPendingUids.valueAt(idx);
428 mPendingUids.removeAt(idx);
429 } else {
430 procState = u.mProcessState;
431 }
432 if (procState >= 0 && procState < Uid.NUM_PROCESS_STATE) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800433 u.addProcStateTimesMs(procState, deltaTimesMs, onBattery);
434 u.addProcStateScreenOffTimesMs(procState, deltaTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800435 }
436 }
437 }
438 }
439 }
440
441 @VisibleForTesting
442 public long[] addCpuTimes(long[] timesA, long[] timesB) {
443 if (timesA != null && timesB != null) {
444 for (int i = timesA.length - 1; i >= 0; --i) {
445 timesA[i] += timesB[i];
446 }
447 return timesA;
448 }
449 return timesA == null ? (timesB == null ? null : timesB) : timesA;
450 }
451
452 @GuardedBy("this")
453 private boolean initKernelSingleUidTimeReaderLocked() {
454 if (mKernelSingleUidTimeReader == null) {
455 if (mPowerProfile == null) {
456 return false;
457 }
458 if (mCpuFreqs == null) {
459 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
460 }
461 if (mCpuFreqs != null) {
462 mKernelSingleUidTimeReader = new KernelSingleUidTimeReader(mCpuFreqs.length);
463 } else {
464 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable();
465 return false;
466 }
467 }
468 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable()
469 && mKernelSingleUidTimeReader.singleUidCpuTimesAvailable();
470 return true;
471 }
472
Joe Onoratoabded112016-02-08 16:49:39 -0800473 public interface Clocks {
474 public long elapsedRealtime();
475 public long uptimeMillis();
476 }
477
478 public static class SystemClocks implements Clocks {
479 public long elapsedRealtime() {
480 return SystemClock.elapsedRealtime();
481 }
482
483 public long uptimeMillis() {
484 return SystemClock.uptimeMillis();
485 }
486 }
487
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700488 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700489 int UPDATE_CPU = 0x01;
490 int UPDATE_WIFI = 0x02;
491 int UPDATE_RADIO = 0x04;
492 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700493 int UPDATE_RPM = 0x10; // 16
494 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800495
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700496 Future<?> scheduleSync(String reason, int flags);
497 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Sudheer Shankac20379e2018-02-15 00:06:21 -0800498 Future<?> scheduleReadProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff,
499 long delayMillis);
Sudheer Shankae544d162017-12-28 17:06:20 -0800500 Future<?> scheduleCopyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800501 Future<?> scheduleCpuSyncDueToSettingChange();
Sudheer Shankac57729a2018-02-09 15:44:42 -0800502 Future<?> scheduleCpuSyncDueToScreenStateChange(boolean onBattery,
503 boolean onBatteryScreenOff);
504 Future<?> scheduleCpuSyncDueToWakelockChange(long delayMillis);
505 void cancelCpuSyncDueToWakelockChange();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700506 }
507
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800508 public Handler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700509 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700510 @VisibleForTesting
511 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700512
513 private BatteryCallback mCallback;
514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800516 * Mapping isolated uids to the actual owning app uid.
517 */
518 final SparseIntArray mIsolatedUids = new SparseIntArray();
519
520 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 * The statistics we have collected organized by uids.
522 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800523 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524
525 // A set of pools of currently active timers. When a timer is queried, we will divide the
526 // elapsed time by the number of active timers to arrive at that timer's share of the time.
527 // In order to do this, we must refresh each timer whenever the number of active timers
528 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700529 @VisibleForTesting
530 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700531 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
532 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700533 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700534 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
535 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
536 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
537 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
538 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
539 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
540 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
541 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700542 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
543 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800544 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700546 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700547 @VisibleForTesting
548 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 // These are the objects that will want to do something when the device
551 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800552 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800553
554 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700555 // is unplugged from power *and* the screen is off or doze.
556 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800557
558 // Set to true when we want to distribute CPU across wakelocks for the next
559 // CPU update, even if we aren't currently running wake locks.
560 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700561
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700562 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700563
Dianne Hackborn37de0982014-05-09 09:32:18 -0700564 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800565
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700566 long mHistoryBaseTime;
Narayan Kamath695cf722017-12-21 18:32:47 +0000567 protected boolean mHaveBatteryLevel = false;
568 protected boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700569 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700570
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700571 final Parcel mHistoryBuffer = Parcel.obtain();
572 final HistoryItem mHistoryLastWritten = new HistoryItem();
573 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700574 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700575 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700576 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800577 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800578 int[] mReadHistoryUids;
579 int mReadHistoryChars;
580 int mNextHistoryTagIdx = 0;
581 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700582 int mHistoryBufferLastPos = -1;
583 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700584 int mActiveHistoryStates = 0xffffffff;
585 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700586 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700587 long mTrackRunningHistoryElapsedRealtime = 0;
588 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700589
590 final HistoryItem mHistoryCur = new HistoryItem();
591
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700592 HistoryItem mHistory;
593 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700594 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700595 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700596
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800597 // Used by computeHistoryStepDetails
598 HistoryStepDetails mLastHistoryStepDetails = null;
599 byte mLastHistoryStepLevel = 0;
600 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
601 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
602 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700603
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800604 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700605 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800606 */
607 long mLastStepCpuUserTime;
608 long mCurStepCpuUserTime;
609 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700610 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800611 */
612 long mLastStepCpuSystemTime;
613 long mCurStepCpuSystemTime;
614 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700615 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800616 */
617 long mLastStepStatUserTime;
618 long mLastStepStatSystemTime;
619 long mLastStepStatIOWaitTime;
620 long mLastStepStatIrqTime;
621 long mLastStepStatSoftIrqTime;
622 long mLastStepStatIdleTime;
623 long mCurStepStatUserTime;
624 long mCurStepStatSystemTime;
625 long mCurStepStatIOWaitTime;
626 long mCurStepStatIrqTime;
627 long mCurStepStatSoftIrqTime;
628 long mCurStepStatIdleTime;
629
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700630 private HistoryItem mHistoryIterator;
631 private boolean mReadOverflow;
632 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 int mStartCount;
635
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800636 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700637 String mStartPlatformVersion;
638 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 long mUptime;
641 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 long mRealtime;
643 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700644
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800645 int mWakeLockNesting;
646 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700647 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700648 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800649
Mike Mac2f518a2017-09-19 16:06:03 -0700650 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
651 protected int mScreenState = Display.STATE_UNKNOWN;
652 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
653 protected StopwatchTimer mScreenOnTimer;
654 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
655 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700656
Dianne Hackborn617f8772009-03-31 15:04:46 -0700657 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700658 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700659
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800660 boolean mPretendScreenOff;
661
Jeff Browne95c3cd2014-05-02 16:59:26 -0700662 boolean mInteractive;
663 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700664
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700665 boolean mPowerSaveModeEnabled;
666 StopwatchTimer mPowerSaveModeEnabledTimer;
667
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700668 boolean mDeviceIdling;
669 StopwatchTimer mDeviceIdlingTimer;
670
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700671 boolean mDeviceLightIdling;
672 StopwatchTimer mDeviceLightIdlingTimer;
673
674 int mDeviceIdleMode;
675 long mLastIdleTimeStart;
676 long mLongestLightIdleTime;
677 long mLongestFullIdleTime;
678 StopwatchTimer mDeviceIdleModeLightTimer;
679 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700682 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700683
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700684 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700685 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700686
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700687 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700688 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700689
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700690 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700691 StopwatchTimer mFlashlightOnTimer;
692
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700693 int mCameraOnNesting;
694 StopwatchTimer mCameraOnTimer;
695
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800696 int mGpsSignalQualityBin = -1;
Narayan Kamathefa0fe62018-02-05 16:04:43 +0000697 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
698 protected final StopwatchTimer[] mGpsSignalQualityTimer =
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800699 new StopwatchTimer[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
700
Dianne Hackborn627bba72009-03-24 22:32:56 -0700701 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800702 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700703 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800704 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700705
706 StopwatchTimer mPhoneSignalScanningTimer;
707
Dianne Hackborn627bba72009-03-24 22:32:56 -0700708 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700709 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700710 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700711
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800712 final LongSamplingCounter[] mNetworkByteActivityCounters =
713 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
714 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700715 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
716
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800717 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800718 * The WiFi Overall wakelock timer
719 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
720 * since addition of per UID timers would not result in an accurate value due to overlapp of
721 * per uid wakelock timers
722 */
723 StopwatchTimer mWifiMulticastWakelockTimer;
724
725 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800726 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
727 */
728 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700729
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800730 /**
731 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
732 */
733 ControllerActivityCounterImpl mBluetoothActivity;
734
735 /**
736 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
737 */
738 ControllerActivityCounterImpl mModemActivity;
739
740 /**
741 * Whether the device supports WiFi controller energy reporting. This is set to true on
742 * the first WiFi energy report. See {@link #mWifiActivity}.
743 */
744 boolean mHasWifiReporting = false;
745
746 /**
747 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
748 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
749 */
750 boolean mHasBluetoothReporting = false;
751
752 /**
753 * Whether the device supports Modem controller energy reporting. This is set to true on
754 * the first Modem energy report. See {@link #mModemActivity}.
755 */
756 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700757
The Android Open Source Project10592532009-03-18 17:39:46 -0700758 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700759 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700760
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700761 boolean mGlobalWifiRunning;
762 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700763
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800764 int mWifiState = -1;
765 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
766
Dianne Hackborn3251b902014-06-20 14:40:53 -0700767 int mWifiSupplState = -1;
768 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
769
770 int mWifiSignalStrengthBin = -1;
771 final StopwatchTimer[] mWifiSignalStrengthsTimer =
772 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
773
Siddharth Rayb50a6842017-12-14 15:15:28 -0800774 StopwatchTimer mWifiActiveTimer;
775
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800776 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800777 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
778 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800779
Siddharth Rayf5e796a2018-01-22 18:18:17 -0800780 boolean mIsCellularTxPowerHigh = false;
781
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700782 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700783 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800784 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800785 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700786 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800787 LongSamplingCounter mMobileRadioActiveUnknownTime;
788 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800789
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700790 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 /**
793 * These provide time bases that discount the time the device is plugged
794 * in to power.
795 */
796 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700797 @VisibleForTesting
798 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700799
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700800 /**
801 * External reporting of whether the device is actually charging.
802 */
803 boolean mCharging = true;
804 int mLastChargingStateLevel;
805
The Android Open Source Project10592532009-03-18 17:39:46 -0700806 /*
807 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
808 */
Evan Millar633a1742009-04-02 16:36:33 -0700809 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700810 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700811 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700812 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700813 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700814 int mLowDischargeAmountSinceCharge;
815 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800816 int mDischargeScreenOnUnplugLevel;
817 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700818 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800819 int mDischargeAmountScreenOn;
820 int mDischargeAmountScreenOnSinceCharge;
821 int mDischargeAmountScreenOff;
822 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700823 int mDischargeAmountScreenDoze;
824 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700825
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700826 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700827 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700828 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800829 private LongSamplingCounter mDischargeLightDozeCounter;
830 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700831
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700832 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700833
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700834 int mInitStepMode = 0;
835 int mCurStepMode = 0;
836 int mModStepMode = 0;
837
Dianne Hackborn260c5022014-04-29 11:23:16 -0700838 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700839 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800840 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
841 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700842 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700843
844 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700845 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800846 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
847 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
848
849 static final int MAX_DAILY_ITEMS = 10;
850
851 long mDailyStartTime = 0;
852 long mNextMinDailyDeadline = 0;
853 long mNextMaxDailyDeadline = 0;
854
855 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700858
Amith Yamasanif37447b2009-10-08 18:28:01 -0700859 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800860 private int mPhoneServiceStateRaw = -1;
861 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700862
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800863 private int mNumConnectivityChange;
864 private int mLoadedNumConnectivityChange;
865 private int mUnpluggedNumConnectivityChange;
866
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700867 private int mEstimatedBatteryCapacity = -1;
868
Jocelyn Dangc627d102017-04-14 13:15:14 -0700869 private int mMinLearnedBatteryCapacity = -1;
870 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800871
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700872 private long[] mCpuFreqs;
873
Sudheer Shanka38383232017-07-25 09:55:03 -0700874 @VisibleForTesting
875 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700876
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800877 @GuardedBy("this")
878 private final Constants mConstants;
879
Evan Millarc64edde2009-04-18 12:26:32 -0700880 /*
Bookatz50df7112017-08-04 14:53:26 -0700881 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
882 * recording their times when on-battery (regardless of screen state).
883 */
884 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
885 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
886 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
887
888 @Override
889 public Map<String, ? extends Timer> getRpmStats() {
890 return mRpmStats;
891 }
892
Bookatz82b341172017-09-07 19:06:08 -0700893 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700894 @Override
895 public Map<String, ? extends Timer> getScreenOffRpmStats() {
896 return mScreenOffRpmStats;
897 }
898
899 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700900 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
901 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700902 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700903
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700904 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700905 return mKernelWakelockStats;
906 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700907
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700908 String mLastWakeupReason = null;
909 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700910 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700911
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700912 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700913 return mWakeupReasonStats;
914 }
915
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700916 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700917 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700918 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700919 }
920
921 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700922 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700923 return mDischargeScreenOffCounter.getCountLocked(which);
924 }
925
926 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700927 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700928 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700929 }
930
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700931 @Override
Mike Ma15313c92017-11-15 17:58:21 -0800932 public long getUahDischargeLightDoze(int which) {
933 return mDischargeLightDozeCounter.getCountLocked(which);
934 }
935
936 @Override
937 public long getUahDischargeDeepDoze(int which) {
938 return mDischargeDeepDozeCounter.getCountLocked(which);
939 }
940
941 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700942 public int getEstimatedBatteryCapacity() {
943 return mEstimatedBatteryCapacity;
944 }
945
Jocelyn Dangc627d102017-04-14 13:15:14 -0700946 @Override
947 public int getMinLearnedBatteryCapacity() {
948 return mMinLearnedBatteryCapacity;
949 }
950
951 @Override
952 public int getMaxLearnedBatteryCapacity() {
953 return mMaxLearnedBatteryCapacity;
954 }
955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -0800957 this(new SystemClocks());
958 }
959
960 public BatteryStatsImpl(Clocks clocks) {
961 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700962 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700963 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800964 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700965 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700966 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700967 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800968 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700969 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 }
971
Joe Onoratoabded112016-02-08 16:49:39 -0800972 private void init(Clocks clocks) {
973 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -0800974 }
975
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700976 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800977 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
978 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
979 }
980
Joe Onoratoabded112016-02-08 16:49:39 -0800981 // methods are protected not private to be VisibleForTesting
982 public static class TimeBase {
983 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800984
Joe Onoratoabded112016-02-08 16:49:39 -0800985 protected long mUptime;
986 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800987
Joe Onoratoabded112016-02-08 16:49:39 -0800988 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800989
Joe Onoratoabded112016-02-08 16:49:39 -0800990 protected long mPastUptime;
991 protected long mUptimeStart;
992 protected long mPastRealtime;
993 protected long mRealtimeStart;
994 protected long mUnpluggedUptime;
995 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800996
997 public void dump(PrintWriter pw, String prefix) {
998 StringBuilder sb = new StringBuilder(128);
999 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
1000 sb.setLength(0);
1001 sb.append(prefix);
1002 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001003 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001004 pw.println(sb.toString());
1005 sb.setLength(0);
1006 sb.append(prefix);
1007 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -07001008 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001009 pw.println(sb.toString());
1010 sb.setLength(0);
1011 sb.append(prefix);
1012 sb.append("mPastUptime=");
1013 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
1014 formatTimeMs(sb, mUptimeStart / 1000);
1015 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
1016 pw.println(sb.toString());
1017 sb.setLength(0);
1018 sb.append(prefix);
1019 sb.append("mPastRealtime=");
1020 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
1021 formatTimeMs(sb, mRealtimeStart / 1000);
1022 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
1023 pw.println(sb.toString());
1024 }
1025
1026 public void add(TimeBaseObs observer) {
1027 mObservers.add(observer);
1028 }
1029
1030 public void remove(TimeBaseObs observer) {
1031 if (!mObservers.remove(observer)) {
1032 Slog.wtf(TAG, "Removed unknown observer: " + observer);
1033 }
1034 }
1035
Joe Onoratoabded112016-02-08 16:49:39 -08001036 public boolean hasObserver(TimeBaseObs observer) {
1037 return mObservers.contains(observer);
1038 }
1039
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001040 public void init(long uptime, long realtime) {
1041 mRealtime = 0;
1042 mUptime = 0;
1043 mPastUptime = 0;
1044 mPastRealtime = 0;
1045 mUptimeStart = uptime;
1046 mRealtimeStart = realtime;
1047 mUnpluggedUptime = getUptime(mUptimeStart);
1048 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1049 }
1050
1051 public void reset(long uptime, long realtime) {
1052 if (!mRunning) {
1053 mPastUptime = 0;
1054 mPastRealtime = 0;
1055 } else {
1056 mUptimeStart = uptime;
1057 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001058 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1059 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001060 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001061 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001062 mUnpluggedRealtime = getRealtime(realtime);
1063 }
1064 }
1065
1066 public long computeUptime(long curTime, int which) {
1067 switch (which) {
1068 case STATS_SINCE_CHARGED:
1069 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001070 case STATS_CURRENT:
1071 return getUptime(curTime);
1072 case STATS_SINCE_UNPLUGGED:
1073 return getUptime(curTime) - mUnpluggedUptime;
1074 }
1075 return 0;
1076 }
1077
1078 public long computeRealtime(long curTime, int which) {
1079 switch (which) {
1080 case STATS_SINCE_CHARGED:
1081 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001082 case STATS_CURRENT:
1083 return getRealtime(curTime);
1084 case STATS_SINCE_UNPLUGGED:
1085 return getRealtime(curTime) - mUnpluggedRealtime;
1086 }
1087 return 0;
1088 }
1089
1090 public long getUptime(long curTime) {
1091 long time = mPastUptime;
1092 if (mRunning) {
1093 time += curTime - mUptimeStart;
1094 }
1095 return time;
1096 }
1097
1098 public long getRealtime(long curTime) {
1099 long time = mPastRealtime;
1100 if (mRunning) {
1101 time += curTime - mRealtimeStart;
1102 }
1103 return time;
1104 }
1105
1106 public long getUptimeStart() {
1107 return mUptimeStart;
1108 }
1109
1110 public long getRealtimeStart() {
1111 return mRealtimeStart;
1112 }
1113
1114 public boolean isRunning() {
1115 return mRunning;
1116 }
1117
1118 public boolean setRunning(boolean running, long uptime, long realtime) {
1119 if (mRunning != running) {
1120 mRunning = running;
1121 if (running) {
1122 mUptimeStart = uptime;
1123 mRealtimeStart = realtime;
1124 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1125 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
1126
1127 for (int i = mObservers.size() - 1; i >= 0; i--) {
1128 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
1129 }
1130 } else {
1131 mPastUptime += uptime - mUptimeStart;
1132 mPastRealtime += realtime - mRealtimeStart;
1133
1134 long batteryUptime = getUptime(uptime);
1135 long batteryRealtime = getRealtime(realtime);
1136
1137 for (int i = mObservers.size() - 1; i >= 0; i--) {
1138 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
1139 }
1140 }
1141 return true;
1142 }
1143 return false;
1144 }
1145
1146 public void readSummaryFromParcel(Parcel in) {
1147 mUptime = in.readLong();
1148 mRealtime = in.readLong();
1149 }
1150
1151 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1152 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1153 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1154 }
1155
1156 public void readFromParcel(Parcel in) {
1157 mRunning = false;
1158 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001159 mPastUptime = in.readLong();
1160 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001161 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001162 mPastRealtime = in.readLong();
1163 mRealtimeStart = in.readLong();
1164 mUnpluggedUptime = in.readLong();
1165 mUnpluggedRealtime = in.readLong();
1166 }
1167
1168 public void writeToParcel(Parcel out, long uptime, long realtime) {
1169 final long runningUptime = getUptime(uptime);
1170 final long runningRealtime = getRealtime(realtime);
1171 out.writeLong(mUptime);
1172 out.writeLong(runningUptime);
1173 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001174 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001175 out.writeLong(runningRealtime);
1176 out.writeLong(mRealtimeStart);
1177 out.writeLong(mUnpluggedUptime);
1178 out.writeLong(mUnpluggedRealtime);
1179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001183 * State for keeping track of counting information.
1184 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001185 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -07001186 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001187 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001188 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001189 int mUnpluggedCount;
1190 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001191
Bookatz8c6f3c52017-05-24 12:00:17 -07001192 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001193 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -07001194 mPluggedCount = in.readInt();
1195 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001196 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001197 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001198 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001199 }
1200
Bookatz8c6f3c52017-05-24 12:00:17 -07001201 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001202 mTimeBase = timeBase;
1203 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001204 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001205
Dianne Hackborn617f8772009-03-31 15:04:46 -07001206 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001207 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001208 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001209 out.writeInt(mUnpluggedCount);
1210 }
1211
Bookatz8c6f3c52017-05-24 12:00:17 -07001212 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001213 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001214 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001215 }
1216
Bookatz8c6f3c52017-05-24 12:00:17 -07001217 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001218 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001219 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001220 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001221
Dianne Hackborn617f8772009-03-31 15:04:46 -07001222 /**
1223 * Writes a possibly null Counter to a Parcel.
1224 *
1225 * @param out the Parcel to be written to.
1226 * @param counter a Counter, or null.
1227 */
Amith Yamasani977e11f2018-02-16 11:29:54 -08001228 public static void writeCounterToParcel(Parcel out, @Nullable Counter counter) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07001229 if (counter == null) {
1230 out.writeInt(0); // indicates null
1231 return;
1232 }
1233 out.writeInt(1); // indicates non-null
1234
1235 counter.writeToParcel(out);
1236 }
1237
Amith Yamasani977e11f2018-02-16 11:29:54 -08001238 /**
1239 * Reads a Counter that was written using {@link #writeCounterToParcel(Parcel, Counter)}.
1240 * @param timeBase the timebase to assign to the Counter
1241 * @param in the parcel to read from
1242 * @return the Counter or null.
1243 */
1244 public static @Nullable Counter readCounterFromParcel(TimeBase timeBase, Parcel in) {
1245 if (in.readInt() == 0) {
1246 return null;
1247 }
1248 return new Counter(timeBase, in);
1249 }
1250
Dianne Hackborn617f8772009-03-31 15:04:46 -07001251 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001252 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001253 int val = mCount.get();
1254 if (which == STATS_SINCE_UNPLUGGED) {
1255 val -= mUnpluggedCount;
1256 } else if (which != STATS_SINCE_CHARGED) {
1257 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001258 }
1259
1260 return val;
1261 }
1262
1263 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001264 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001265 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001266 + " mUnpluggedCount=" + mUnpluggedCount
1267 + " mPluggedCount=" + mPluggedCount);
1268 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001269
Bookatz8c6f3c52017-05-24 12:00:17 -07001270 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1271 public void stepAtomic() {
1272 if (mTimeBase.isRunning()) {
1273 mCount.incrementAndGet();
1274 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001275 }
1276
Bookatz4ebc0642017-05-11 12:21:19 -07001277 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001278 if (mTimeBase.isRunning()) {
1279 mCount.addAndGet(delta);
1280 }
Bookatz4ebc0642017-05-11 12:21:19 -07001281 }
1282
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001283 /**
1284 * Clear state of this counter.
1285 */
1286 void reset(boolean detachIfReset) {
1287 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001288 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001289 if (detachIfReset) {
1290 detach();
1291 }
1292 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001293
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001294 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001295 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001296 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001297
Bookatz8c6f3c52017-05-24 12:00:17 -07001298 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1299 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001300 int count = mCount.get();
1301 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001302 }
1303
Bookatz8c6f3c52017-05-24 12:00:17 -07001304 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1305 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001306 mLoadedCount = in.readInt();
1307 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001308 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001309 }
1310 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001311
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001312 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001313 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1314 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001315 public long[] mCounts;
1316 public long[] mLoadedCounts;
1317 public long[] mUnpluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001318
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001319 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001320 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001321 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001322 mLoadedCounts = in.createLongArray();
1323 mUnpluggedCounts = in.createLongArray();
1324 timeBase.add(this);
1325 }
1326
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001327 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001328 mTimeBase = timeBase;
1329 timeBase.add(this);
1330 }
1331
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001332 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001333 out.writeLongArray(mCounts);
1334 out.writeLongArray(mLoadedCounts);
1335 out.writeLongArray(mUnpluggedCounts);
1336 }
1337
1338 @Override
1339 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001340 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001341 }
1342
1343 @Override
1344 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001345 }
1346
1347 @Override
1348 public long[] getCountsLocked(int which) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001349 long[] val = copyArray(mCounts, null);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001350 if (which == STATS_SINCE_UNPLUGGED) {
1351 subtract(val, mUnpluggedCounts);
1352 } else if (which != STATS_SINCE_CHARGED) {
1353 subtract(val, mLoadedCounts);
1354 }
1355 return val;
1356 }
1357
1358 @Override
1359 public void logState(Printer pw, String prefix) {
1360 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1361 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
Sudheer Shankae544d162017-12-28 17:06:20 -08001362 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001363 }
1364
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001365 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001366 addCountLocked(counts, mTimeBase.isRunning());
1367 }
1368
1369 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001370 if (counts == null) {
1371 return;
1372 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001373 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001374 if (mCounts == null) {
1375 mCounts = new long[counts.length];
1376 }
1377 for (int i = 0; i < counts.length; ++i) {
1378 mCounts[i] += counts[i];
1379 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001380 }
1381 }
1382
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001383 public int getSize() {
1384 return mCounts == null ? 0 : mCounts.length;
1385 }
1386
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001387 /**
1388 * Clear state of this counter.
1389 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001390 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001391 fillArray(mCounts, 0);
1392 fillArray(mLoadedCounts, 0);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001393 fillArray(mUnpluggedCounts, 0);
1394 if (detachIfReset) {
1395 detach();
1396 }
1397 }
1398
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001399 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001400 mTimeBase.remove(this);
1401 }
1402
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001403 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001404 out.writeLongArray(mCounts);
1405 }
1406
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001407 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001408 mCounts = in.createLongArray();
1409 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1410 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001411 }
1412
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001413 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1414 if (counterArray != null) {
1415 out.writeInt(1);
1416 counterArray.writeToParcel(out);
1417 } else {
1418 out.writeInt(0);
1419 }
1420 }
1421
1422 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1423 if (in.readInt() != 0) {
1424 return new LongSamplingCounterArray(timeBase, in);
1425 } else {
1426 return null;
1427 }
1428 }
1429
1430 public static void writeSummaryToParcelLocked(Parcel out,
1431 LongSamplingCounterArray counterArray) {
1432 if (counterArray != null) {
1433 out.writeInt(1);
1434 counterArray.writeSummaryToParcelLocked(out);
1435 } else {
1436 out.writeInt(0);
1437 }
1438 }
1439
1440 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1441 TimeBase timeBase) {
1442 if (in.readInt() != 0) {
1443 final LongSamplingCounterArray counterArray
1444 = new LongSamplingCounterArray(timeBase);
1445 counterArray.readSummaryFromParcelLocked(in);
1446 return counterArray;
1447 } else {
1448 return null;
1449 }
1450 }
1451
Bookatz8c6f3c52017-05-24 12:00:17 -07001452 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001453 if (a != null) {
1454 Arrays.fill(a, val);
1455 }
1456 }
1457
Bookatz8c6f3c52017-05-24 12:00:17 -07001458 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001459 if (toSubtract == null) {
1460 return;
1461 }
1462 for (int i = 0; i < val.length; i++) {
1463 val[i] -= toSubtract[i];
1464 }
1465 }
1466
Bookatz8c6f3c52017-05-24 12:00:17 -07001467 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001468 if (src == null) {
1469 return null;
1470 } else {
1471 if (dest == null) {
1472 dest = new long[src.length];
1473 }
1474 System.arraycopy(src, 0, dest, 0, src.length);
1475 return dest;
1476 }
1477 }
1478 }
1479
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001480 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001481 final TimeBase mTimeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001482 long mCount;
1483 long mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001484 long mUnpluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001485
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001486 LongSamplingCounter(TimeBase timeBase, Parcel in) {
1487 mTimeBase = timeBase;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001488 mCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001489 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001490 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001491 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001492 }
1493
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001494 LongSamplingCounter(TimeBase timeBase) {
1495 mTimeBase = timeBase;
1496 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001497 }
1498
1499 public void writeToParcel(Parcel out) {
1500 out.writeLong(mCount);
1501 out.writeLong(mLoadedCount);
1502 out.writeLong(mUnpluggedCount);
1503 }
1504
1505 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001506 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001507 mUnpluggedCount = mCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001508 }
1509
1510 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001511 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001512 }
1513
1514 public long getCountLocked(int which) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001515 long val = mCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001516 if (which == STATS_SINCE_UNPLUGGED) {
1517 val -= mUnpluggedCount;
1518 } else if (which != STATS_SINCE_CHARGED) {
1519 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001520 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001521 return val;
1522 }
1523
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001524 @Override
1525 public void logState(Printer pw, String prefix) {
1526 pw.println(prefix + "mCount=" + mCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001527 + " mLoadedCount=" + mLoadedCount
Sudheer Shankac57729a2018-02-09 15:44:42 -08001528 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001529 }
1530
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001531 void addCountLocked(long count) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08001532 addCountLocked(count, mTimeBase.isRunning());
1533 }
1534
1535 void addCountLocked(long count, boolean isRunning) {
1536 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001537 mCount += count;
1538 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001539 }
1540
1541 /**
1542 * Clear state of this counter.
1543 */
1544 void reset(boolean detachIfReset) {
1545 mCount = 0;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001546 mLoadedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001547 if (detachIfReset) {
1548 detach();
1549 }
1550 }
1551
1552 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001553 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001554 }
1555
1556 void writeSummaryFromParcelLocked(Parcel out) {
1557 out.writeLong(mCount);
1558 }
1559
1560 void readSummaryFromParcelLocked(Parcel in) {
1561 mLoadedCount = in.readLong();
1562 mCount = mLoadedCount;
Sudheer Shankac57729a2018-02-09 15:44:42 -08001563 mUnpluggedCount = mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001564 }
1565 }
1566
Dianne Hackborn617f8772009-03-31 15:04:46 -07001567 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 * State for keeping track of timing information.
1569 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001570 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001571 protected final Clocks mClocks;
1572 protected final int mType;
1573 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001574
Joe Onoratoabded112016-02-08 16:49:39 -08001575 protected int mCount;
1576 protected int mLoadedCount;
1577 protected int mLastCount;
1578 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 // Times are in microseconds for better accuracy when dividing by the
1581 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 /**
1584 * The total time we have accumulated since the start of the original
1585 * boot, to the last time something interesting happened in the
1586 * current run.
1587 */
Joe Onoratoabded112016-02-08 16:49:39 -08001588 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 /**
1591 * The total time we loaded for the previous runs. Subtract this from
1592 * mTotalTime to find the time for the current run of the system.
1593 */
Joe Onoratoabded112016-02-08 16:49:39 -08001594 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 /**
1597 * The run time of the last run of the system, as loaded from the
1598 * saved data.
1599 */
Joe Onoratoabded112016-02-08 16:49:39 -08001600 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 /**
1603 * The value of mTotalTime when unplug() was last called. Subtract
1604 * this from mTotalTime to find the time since the last unplug from
1605 * power.
1606 */
Joe Onoratoabded112016-02-08 16:49:39 -08001607 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001608
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001609 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001610 * The total time this timer has been running until the latest mark has been set.
1611 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1612 */
Joe Onoratoabded112016-02-08 16:49:39 -08001613 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001614
1615 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001616 * Constructs from a parcel.
1617 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001618 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001619 * @param in
1620 */
Joe Onoratoabded112016-02-08 16:49:39 -08001621 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1622 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001624 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 mCount = in.readInt();
1627 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001628 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 mUnpluggedCount = in.readInt();
1630 mTotalTime = in.readLong();
1631 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001632 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001634 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001635 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001636 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638
Joe Onoratoabded112016-02-08 16:49:39 -08001639 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1640 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001642 mTimeBase = timeBase;
1643 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
Evan Millarc64edde2009-04-18 12:26:32 -07001645
1646 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001647
Evan Millarc64edde2009-04-18 12:26:32 -07001648 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001649
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001650 /**
1651 * Clear state of this timer. Returns true if the timer is inactive
1652 * so can be completely dropped.
1653 */
Joe Onoratoabded112016-02-08 16:49:39 -08001654 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001655 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001656 mCount = mLoadedCount = mLastCount = 0;
1657 if (detachIfReset) {
1658 detach();
1659 }
1660 return true;
1661 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001662
Joe Onoratoabded112016-02-08 16:49:39 -08001663 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001664 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001665 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001666
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001667 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001668 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1669 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001670 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001673 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001676 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
1678
Adam Lesinskie08af192015-03-25 16:42:59 -07001679 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001680 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001682 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 + " old mUnpluggedTime=" + mUnpluggedTime
1684 + " old mUnpluggedCount=" + mUnpluggedCount);
1685 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001686 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001687 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 if (DEBUG && mType < 0) {
1689 Log.v(TAG, "unplug #" + mType
1690 + ": new mUnpluggedTime=" + mUnpluggedTime
1691 + " new mUnpluggedCount=" + mUnpluggedCount);
1692 }
1693 }
1694
Adam Lesinskie08af192015-03-25 16:42:59 -07001695 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001696 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001697 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001698 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001699 + " old mTotalTime=" + mTotalTime);
1700 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001701 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001702 mCount = computeCurrentCountLocked();
1703 if (DEBUG && mType < 0) {
1704 Log.v(TAG, "plug #" + mType
1705 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 }
1707 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 /**
1710 * Writes a possibly null Timer to a Parcel.
1711 *
1712 * @param out the Parcel to be written to.
1713 * @param timer a Timer, or null.
1714 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001715 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 if (timer == null) {
1717 out.writeInt(0); // indicates null
1718 return;
1719 }
1720 out.writeInt(1); // indicates non-null
1721
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001722 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 }
1724
1725 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001726 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001727 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1728 if (which == STATS_SINCE_UNPLUGGED) {
1729 val -= mUnpluggedTime;
1730 } else if (which != STATS_SINCE_CHARGED) {
1731 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 }
1733
1734 return val;
1735 }
1736
1737 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001738 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001739 int val = computeCurrentCountLocked();
1740 if (which == STATS_SINCE_UNPLUGGED) {
1741 val -= mUnpluggedCount;
1742 } else if (which != STATS_SINCE_CHARGED) {
1743 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 }
1745
1746 return val;
1747 }
1748
Adam Lesinskie08af192015-03-25 16:42:59 -07001749 @Override
1750 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1751 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1752 return val - mTimeBeforeMark;
1753 }
1754
1755 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001756 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001757 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1759 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001760 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001762 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001764 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001765
1766
Joe Onoratoabded112016-02-08 16:49:39 -08001767 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001768 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1769 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001770 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001771 }
1772
Joe Onoratoabded112016-02-08 16:49:39 -08001773 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001774 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001775 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001776 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001777 mUnpluggedTime = mTotalTime;
1778 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001779 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001780 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001781
1782 // When reading the summary, we set the mark to be the latest information.
1783 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001784 }
1785 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001786
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001787 /**
1788 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1789 * method. The state of the timer according to its {@link TimeBase} will determine how much
1790 * of the value is recorded.
1791 *
1792 * If the value being recorded resets, {@link #endSample()} can be called in order to
1793 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1794 * between calls, the {@link #endSample()} is automatically called and the new value is
1795 * expected to increase monotonically from that point on.
1796 */
Joe Onoratoabded112016-02-08 16:49:39 -08001797 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001798
Evan Millarc64edde2009-04-18 12:26:32 -07001799 /**
1800 * The most recent reported count from /proc/wakelocks.
1801 */
1802 int mCurrentReportedCount;
1803
1804 /**
1805 * The reported count from /proc/wakelocks when unplug() was last
1806 * called.
1807 */
1808 int mUnpluggedReportedCount;
1809
1810 /**
1811 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001812 */
Evan Millarc64edde2009-04-18 12:26:32 -07001813 long mCurrentReportedTotalTime;
1814
1815
1816 /**
1817 * The reported total_time from /proc/wakelocks when unplug() was last
1818 * called.
1819 */
1820 long mUnpluggedReportedTotalTime;
1821
1822 /**
1823 * Whether we are currently in a discharge cycle.
1824 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001825 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001826
1827 /**
1828 * Whether we are currently recording reported values.
1829 */
1830 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001831
Evan Millarc64edde2009-04-18 12:26:32 -07001832 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001833 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001834 */
1835 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001836
Adam Lesinski98f0d462016-04-19 16:46:20 -07001837 @VisibleForTesting
1838 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001839 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001840 mCurrentReportedCount = in.readInt();
1841 mUnpluggedReportedCount = in.readInt();
1842 mCurrentReportedTotalTime = in.readLong();
1843 mUnpluggedReportedTotalTime = in.readLong();
1844 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001845 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001846 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001847
Adam Lesinski98f0d462016-04-19 16:46:20 -07001848 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001849 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001850 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001851 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001852 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001853 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001854
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001855 /**
1856 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1857 * be less than the values used for a previous invocation.
1858 */
1859 public void endSample() {
1860 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1861 mCount = computeCurrentCountLocked();
1862 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1863 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001864 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001865
Evan Millarc64edde2009-04-18 12:26:32 -07001866 public void setUpdateVersion(int version) {
1867 mUpdateVersion = version;
1868 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001869
Evan Millarc64edde2009-04-18 12:26:32 -07001870 public int getUpdateVersion() {
1871 return mUpdateVersion;
1872 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001873
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001874 /**
1875 * Updates the current recorded values. These are meant to be monotonically increasing
1876 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1877 *
1878 * If the values being recorded have been reset, the monotonically increasing requirement
1879 * will be broken. In this case, {@link #endSample()} is automatically called and
1880 * the total value of totalTime and count are recorded, starting a new monotonically
1881 * increasing sample.
1882 *
1883 * @param totalTime total time of sample in microseconds.
1884 * @param count total number of times the event being sampled occurred.
1885 */
1886 public void update(long totalTime, int count) {
1887 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001888 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001889 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001890 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001891 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001892
1893 mTrackingReportedValues = true;
1894
1895 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1896 endSample();
1897 }
1898
1899 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001900 mCurrentReportedCount = count;
1901 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001902
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001903 /**
1904 * Adds deltaTime and deltaCount to the current sample.
1905 *
1906 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1907 * @param deltaCount additional number of times the event being sampled occurred.
1908 */
1909 public void add(long deltaTime, int deltaCount) {
1910 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001911 }
1912
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001913 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001914 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
1915 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001916 if (mTrackingReportedValues) {
1917 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
1918 mUnpluggedReportedCount = mCurrentReportedCount;
1919 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001920 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07001921 }
1922
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001923 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001924 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1925 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1926 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07001927 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001928
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001929 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001930 public void logState(Printer pw, String prefix) {
1931 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001932 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07001933 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
1934 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
1935 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
1936 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001937
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001938 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001939 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001940 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001941 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
1942 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001943
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001944 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001945 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001946 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001947 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
1948 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001949
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001950 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001951 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1952 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001953 out.writeInt(mCurrentReportedCount);
1954 out.writeInt(mUnpluggedReportedCount);
1955 out.writeLong(mCurrentReportedTotalTime);
1956 out.writeLong(mUnpluggedReportedTotalTime);
1957 out.writeInt(mTrackingReportedValues ? 1 : 0);
1958 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001959
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001960 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001961 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001962 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001963 mTrackingReportedValues = false;
1964 mUnpluggedReportedTotalTime = 0;
1965 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001966 return true;
1967 }
Evan Millarc64edde2009-04-18 12:26:32 -07001968 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001969
Evan Millarc64edde2009-04-18 12:26:32 -07001970 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001971 * A timer that increments in batches. It does not run for durations, but just jumps
1972 * for a pre-determined amount.
1973 */
Joe Onoratoabded112016-02-08 16:49:39 -08001974 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001975 final Uid mUid;
1976
1977 /**
1978 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
1979 */
1980 long mLastAddedTime;
1981
1982 /**
1983 * The last duration that we added to the timer. This is in microseconds.
1984 */
1985 long mLastAddedDuration;
1986
1987 /**
1988 * Whether we are currently in a discharge cycle.
1989 */
1990 boolean mInDischarge;
1991
Joe Onoratoabded112016-02-08 16:49:39 -08001992 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
1993 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001994 mUid = uid;
1995 mLastAddedTime = in.readLong();
1996 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001997 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001998 }
1999
Joe Onoratoabded112016-02-08 16:49:39 -08002000 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
2001 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002002 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002003 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002004 }
2005
2006 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002007 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2008 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002009 out.writeLong(mLastAddedTime);
2010 out.writeLong(mLastAddedDuration);
2011 }
2012
2013 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002014 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002015 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002016 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002017 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002018 }
2019
2020 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002021 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002022 recomputeLastDuration(elapsedRealtime, false);
2023 mInDischarge = true;
2024 // If we are still within the last added duration, then re-added whatever remains.
2025 if (mLastAddedTime == elapsedRealtime) {
2026 mTotalTime += mLastAddedDuration;
2027 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002028 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002029 }
2030
2031 @Override
2032 public void logState(Printer pw, String prefix) {
2033 super.logState(pw, prefix);
2034 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
2035 + " mLastAddedDuration=" + mLastAddedDuration);
2036 }
2037
2038 private long computeOverage(long curTime) {
2039 if (mLastAddedTime > 0) {
2040 return mLastTime + mLastAddedDuration - curTime;
2041 }
2042 return 0;
2043 }
2044
2045 private void recomputeLastDuration(long curTime, boolean abort) {
2046 final long overage = computeOverage(curTime);
2047 if (overage > 0) {
2048 // Aborting before the duration ran out -- roll back the remaining
2049 // duration. Only do this if currently discharging; otherwise we didn't
2050 // actually add the time.
2051 if (mInDischarge) {
2052 mTotalTime -= overage;
2053 }
2054 if (abort) {
2055 mLastAddedTime = 0;
2056 } else {
2057 mLastAddedTime = curTime;
2058 mLastAddedDuration -= overage;
2059 }
2060 }
2061 }
2062
2063 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08002064 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002065 recomputeLastDuration(now, true);
2066 mLastAddedTime = now;
2067 mLastAddedDuration = durationMillis * 1000;
2068 if (mInDischarge) {
2069 mTotalTime += mLastAddedDuration;
2070 mCount++;
2071 }
2072 }
2073
2074 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002075 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002076 recomputeLastDuration(now, true);
2077 }
2078
2079 @Override
2080 protected int computeCurrentCountLocked() {
2081 return mCount;
2082 }
2083
2084 @Override
2085 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002086 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002087 if (overage > 0) {
2088 return mTotalTime = overage;
2089 }
2090 return mTotalTime;
2091 }
2092
2093 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002094 public boolean reset(boolean detachIfReset) {
2095 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002096 recomputeLastDuration(now, true);
2097 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002098 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002099 return !stillActive;
2100 }
2101 }
2102
Joe Onorato92fd23f2016-07-25 11:18:42 -07002103
2104 /**
2105 * A StopwatchTimer that also tracks the total and max individual
2106 * time spent active according to the given timebase. Whereas
2107 * StopwatchTimer apportions the time amongst all in the pool,
2108 * the total and max durations are not apportioned.
2109 */
2110 public static class DurationTimer extends StopwatchTimer {
2111 /**
2112 * The time (in ms) that the timer was last acquired or the time base
2113 * last (re-)started. Increasing the nesting depth does not reset this time.
2114 *
2115 * -1 if the timer is currently not running or the time base is not running.
2116 *
2117 * If written to a parcel, the start time is reset, as is mNesting in the base class
2118 * StopwatchTimer.
2119 */
2120 long mStartTimeMs = -1;
2121
2122 /**
Bookatz867c0d72017-03-07 18:23:42 -08002123 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002124 */
2125 long mMaxDurationMs;
2126
2127 /**
Bookatz867c0d72017-03-07 18:23:42 -08002128 * The time (in ms) that that the timer has been active since most recent
2129 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002130 */
2131 long mCurrentDurationMs;
2132
Bookatz867c0d72017-03-07 18:23:42 -08002133 /**
2134 * The total time (in ms) that that the timer has been active since most recent reset()
2135 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2136 * (but not including the present currentDuration) since reset. Not pooled.
2137 */
2138 long mTotalDurationMs;
2139
Joe Onorato92fd23f2016-07-25 11:18:42 -07002140 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2141 TimeBase timeBase, Parcel in) {
2142 super(clocks, uid, type, timerPool, timeBase, in);
2143 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002144 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002145 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002146 }
2147
2148 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2149 TimeBase timeBase) {
2150 super(clocks, uid, type, timerPool, timeBase);
2151 }
2152
2153 @Override
2154 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2155 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002156 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002157 out.writeLong(mTotalDurationMs);
2158 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002159 }
2160
2161 /**
2162 * Write the summary to the parcel.
2163 *
2164 * Since the time base is probably meaningless after we come back, reading
2165 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002166 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002167 */
2168 @Override
2169 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2170 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002171 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002172 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002173 }
2174
2175 /**
2176 * Read the summary parcel.
2177 *
2178 * Has the side effect of stopping the timer.
2179 */
2180 @Override
2181 public void readSummaryFromParcelLocked(Parcel in) {
2182 super.readSummaryFromParcelLocked(in);
2183 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002184 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002185 mStartTimeMs = -1;
2186 mCurrentDurationMs = 0;
2187 }
2188
2189 /**
2190 * The TimeBase time started (again).
2191 *
2192 * If the timer is also running, store the start time.
2193 */
2194 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2195 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2196 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002197 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002198 }
2199 }
2200
2201 /**
2202 * The TimeBase stopped running.
2203 *
2204 * If the timer is running, add the duration into mCurrentDurationMs.
2205 */
2206 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002207 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2208 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002209 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002210 // baseRealtimeUs has already been converted to the timebase's realtime.
2211 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002212 }
2213 mStartTimeMs = -1;
2214 }
2215
2216 @Override
2217 public void logState(Printer pw, String prefix) {
2218 super.logState(pw, prefix);
2219 }
2220
2221 @Override
2222 public void startRunningLocked(long elapsedRealtimeMs) {
2223 super.startRunningLocked(elapsedRealtimeMs);
2224 if (mNesting == 1 && mTimeBase.isRunning()) {
2225 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002226 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002227 }
2228 }
2229
2230 /**
2231 * Decrements the mNesting ref-count on this timer.
2232 *
2233 * If it actually stopped (mNesting went to 0), then possibly update
2234 * mMaxDuration if the current duration was the longest ever.
2235 */
2236 @Override
2237 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002238 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002239 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002240 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002241 if (durationMs > mMaxDurationMs) {
2242 mMaxDurationMs = durationMs;
2243 }
2244 mStartTimeMs = -1;
2245 mCurrentDurationMs = 0;
2246 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002247 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2248 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2249 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002250 }
2251
2252 @Override
2253 public boolean reset(boolean detachIfReset) {
2254 boolean result = super.reset(detachIfReset);
2255 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002256 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002257 mCurrentDurationMs = 0;
2258 if (mNesting > 0) {
2259 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2260 } else {
2261 mStartTimeMs = -1;
2262 }
2263 return result;
2264 }
2265
2266 /**
2267 * Returns the max duration that this timer has ever seen.
2268 *
2269 * Note that this time is NOT split between the timers in the timer group that
2270 * this timer is attached to. It is the TOTAL time.
2271 */
2272 @Override
2273 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2274 if (mNesting > 0) {
2275 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2276 if (durationMs > mMaxDurationMs) {
2277 return durationMs;
2278 }
2279 }
2280 return mMaxDurationMs;
2281 }
2282
2283 /**
2284 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002285 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002286 *
2287 * Note that this time is NOT split between the timers in the timer group that
2288 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002289 *
2290 * Note that if running timer is parceled and unparceled, this method will return
2291 * current duration value at the time of parceling even though timer may not be
2292 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002293 */
2294 @Override
2295 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2296 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002297 if (mNesting > 0 && mTimeBase.isRunning()) {
2298 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2299 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002300 }
2301 return durationMs;
2302 }
Bookatz867c0d72017-03-07 18:23:42 -08002303
2304 /**
2305 * Returns the total cumulative duration that this timer has been on since reset().
2306 * If mTimerPool == null, this should be the same
2307 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2308 *
2309 * Note that this time is NOT split between the timers in the timer group that
2310 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2311 * the result will not be equivalent to getTotalTimeLocked.
2312 */
2313 @Override
2314 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2315 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2316 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002317 }
2318
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002319 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002320 * State for keeping track of timing information.
2321 */
Joe Onoratoabded112016-02-08 16:49:39 -08002322 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002323 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002324 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002325
Evan Millarc64edde2009-04-18 12:26:32 -07002326 int mNesting;
2327
Evan Millarc64edde2009-04-18 12:26:32 -07002328 /**
2329 * The last time at which we updated the timer. If mNesting is > 0,
2330 * subtract this from the current battery time to find the amount of
2331 * time we have been running since we last computed an update.
2332 */
2333 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002334
Evan Millarc64edde2009-04-18 12:26:32 -07002335 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002336 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002337 * was actually held for an interesting duration. If time base was not running when timer
2338 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002339 */
Bookatzceebafe2017-04-06 11:59:13 -07002340 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002341
Amith Yamasanif37447b2009-10-08 18:28:01 -07002342 long mTimeout;
2343
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002344 /**
2345 * For partial wake locks, keep track of whether we are in the list
2346 * to consume CPU cycles.
2347 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002348 @VisibleForTesting
2349 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002350
Joe Onoratoabded112016-02-08 16:49:39 -08002351 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002352 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002353 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002354 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002355 mTimerPool = timerPool;
2356 mUpdateTime = in.readLong();
2357 }
2358
Joe Onoratoabded112016-02-08 16:49:39 -08002359 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002360 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002361 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002362 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002363 mTimerPool = timerPool;
2364 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002365
Joe Onoratoabded112016-02-08 16:49:39 -08002366 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002367 mTimeout = timeout;
2368 }
2369
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002370 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2371 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002372 out.writeLong(mUpdateTime);
2373 }
2374
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002375 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002376 if (mNesting > 0) {
2377 if (DEBUG && mType < 0) {
2378 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2379 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002380 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2381 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002382 if (DEBUG && mType < 0) {
2383 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2384 }
2385 }
2386 }
2387
2388 public void logState(Printer pw, String prefix) {
2389 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002390 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 + " mAcquireTime=" + mAcquireTime);
2392 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002393
Joe Onoratoabded112016-02-08 16:49:39 -08002394 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002396 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002397 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 if (mTimerPool != null) {
2399 // Accumulate time to all currently active timers before adding
2400 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002401 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 // Add this timer to the active pool
2403 mTimerPool.add(this);
2404 }
Bookatzceebafe2017-04-06 11:59:13 -07002405 if (mTimeBase.isRunning()) {
2406 // Increment the count
2407 mCount++;
2408 mAcquireTime = mTotalTime;
2409 } else {
2410 mAcquireTime = -1;
2411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 if (DEBUG && mType < 0) {
2413 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2414 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2415 + " mAcquireTime=" + mAcquireTime);
2416 }
2417 }
2418 }
2419
Joe Onoratoabded112016-02-08 16:49:39 -08002420 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002421 return mNesting > 0;
2422 }
2423
Joe Onoratoabded112016-02-08 16:49:39 -08002424 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 // Ignore attempt to stop a timer that isn't running
2426 if (mNesting == 0) {
2427 return;
2428 }
2429 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002430 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 if (mTimerPool != null) {
2432 // Accumulate time to all active counters, scaled by the total
2433 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002434 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 // Remove this timer from the active pool
2436 mTimerPool.remove(this);
2437 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 mNesting = 1;
2439 mTotalTime = computeRunTimeLocked(batteryRealtime);
2440 mNesting = 0;
2441 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 if (DEBUG && mType < 0) {
2444 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2445 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2446 + " mAcquireTime=" + mAcquireTime);
2447 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002448
Bookatzceebafe2017-04-06 11:59:13 -07002449 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 // If there was no change in the time, then discard this
2451 // count. A somewhat cheezy strategy, but hey.
2452 mCount--;
2453 }
2454 }
2455 }
2456
Joe Onoratoabded112016-02-08 16:49:39 -08002457 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002458 if (mNesting > 0) {
2459 mNesting = 1;
2460 stopRunningLocked(elapsedRealtimeMs);
2461 }
2462 }
2463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 // Update the total time for all other running Timers with the same type as this Timer
2465 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002466 private static long refreshTimersLocked(long batteryRealtime,
2467 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002468 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002469 final int N = pool.size();
2470 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002471 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 long heldTime = batteryRealtime - t.mUpdateTime;
2473 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002474 final long myTime = heldTime / N;
2475 if (t == self) {
2476 selfTime = myTime;
2477 }
2478 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 }
2480 t.mUpdateTime = batteryRealtime;
2481 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002482 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 }
2484
Evan Millarc64edde2009-04-18 12:26:32 -07002485 @Override
2486 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002487 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2488 curBatteryRealtime = mUpdateTime + mTimeout;
2489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 return mTotalTime + (mNesting > 0
2491 ? (curBatteryRealtime - mUpdateTime)
2492 / (mTimerPool != null ? mTimerPool.size() : 1)
2493 : 0);
2494 }
2495
Evan Millarc64edde2009-04-18 12:26:32 -07002496 @Override
2497 protected int computeCurrentCountLocked() {
2498 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 }
2500
Adam Lesinskie08af192015-03-25 16:42:59 -07002501 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002502 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002503 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002504 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002505 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002506 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002507 }
Bookatzceebafe2017-04-06 11:59:13 -07002508 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002509 return canDetach;
2510 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002511
Adam Lesinskie08af192015-03-25 16:42:59 -07002512 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002513 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002514 super.detach();
2515 if (mTimerPool != null) {
2516 mTimerPool.remove(this);
2517 }
2518 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002519
Adam Lesinskie08af192015-03-25 16:42:59 -07002520 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002521 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002522 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 mNesting = 0;
2524 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002525
2526 /**
2527 * Set the mark so that we can query later for the total time the timer has
2528 * accumulated since this point. The timer can be running or not.
2529 *
2530 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2531 */
2532 public void setMark(long elapsedRealtimeMs) {
2533 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2534 if (mNesting > 0) {
2535 // We are running.
2536 if (mTimerPool != null) {
2537 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2538 } else {
2539 mTotalTime += batteryRealtime - mUpdateTime;
2540 mUpdateTime = batteryRealtime;
2541 }
2542 }
2543 mTimeBeforeMark = mTotalTime;
2544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002546
Bookatz867c0d72017-03-07 18:23:42 -08002547 /**
2548 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2549 * TimeBase is effectively a subset of the other.
2550 */
Bookatzaa4594a2017-03-24 12:39:56 -07002551 public static class DualTimer extends DurationTimer {
2552 // This class both is a DurationTimer and also holds a second DurationTimer.
2553 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2554 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2555 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002556 // mSubTimer typically tracks only part of the total time, such as background time, as
2557 // determined by a subTimeBase. It is NOT pooled.
2558 private final DurationTimer mSubTimer;
2559
2560 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002561 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2562 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002563 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002564 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002565 */
2566 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2567 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002568 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002569 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2570 }
2571
2572 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002573 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2574 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002575 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002576 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002577 */
2578 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2579 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002580 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002581 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2582 }
2583
Bookatz867c0d72017-03-07 18:23:42 -08002584 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002585 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002586 public DurationTimer getSubTimer() {
2587 return mSubTimer;
2588 }
2589
Bookatzaa4594a2017-03-24 12:39:56 -07002590 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002591 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002592 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002593 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2594 }
2595
Bookatzaa4594a2017-03-24 12:39:56 -07002596 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002597 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002598 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002599 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2600 }
2601
Bookatzaa4594a2017-03-24 12:39:56 -07002602 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002603 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002604 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002605 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2606 }
2607
Bookatzaa4594a2017-03-24 12:39:56 -07002608 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002609 public boolean reset(boolean detachIfReset) {
2610 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002611 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2612 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002613 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002614 return !active;
2615 }
2616
Bookatzaa4594a2017-03-24 12:39:56 -07002617 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002618 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002619 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002620 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002621 }
2622
Bookatzaa4594a2017-03-24 12:39:56 -07002623 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002624 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002625 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002626 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2627 }
2628
Bookatzaa4594a2017-03-24 12:39:56 -07002629 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002630 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002631 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002632 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2633 }
2634
Bookatzaa4594a2017-03-24 12:39:56 -07002635 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002636 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002637 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002638 mSubTimer.readSummaryFromParcelLocked(in);
2639 }
2640 }
2641
2642
Dianne Hackbornd953c532014-08-16 18:17:38 -07002643 public abstract class OverflowArrayMap<T> {
2644 private static final String OVERFLOW_NAME = "*overflow*";
2645
Dianne Hackborn657153b2016-07-29 14:54:14 -07002646 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002647 final ArrayMap<String, T> mMap = new ArrayMap<>();
2648 T mCurOverflow;
2649 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002650 long mLastOverflowTime;
2651 long mLastOverflowFinishTime;
2652 long mLastClearTime;
2653 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002654
Dianne Hackborn657153b2016-07-29 14:54:14 -07002655 public OverflowArrayMap(int uid) {
2656 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002657 }
2658
2659 public ArrayMap<String, T> getMap() {
2660 return mMap;
2661 }
2662
2663 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002664 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002665 mMap.clear();
2666 mCurOverflow = null;
2667 mActiveOverflow = null;
2668 }
2669
2670 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002671 if (name == null) {
2672 name = "";
2673 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002674 mMap.put(name, obj);
2675 if (OVERFLOW_NAME.equals(name)) {
2676 mCurOverflow = obj;
2677 }
2678 }
2679
2680 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002681 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002682 if (mActiveOverflow != null) {
2683 if (mActiveOverflow.size() == 0) {
2684 mActiveOverflow = null;
2685 }
2686 }
2687 if (mActiveOverflow == null) {
2688 // There is no currently active overflow, so we should no longer have
2689 // an overflow entry.
2690 if (mMap.containsKey(OVERFLOW_NAME)) {
2691 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2692 + mMap.get(OVERFLOW_NAME));
2693 mMap.remove(OVERFLOW_NAME);
2694 }
2695 mCurOverflow = null;
2696 } else {
2697 // There is currently active overflow, so we should still have an overflow entry.
2698 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2699 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2700 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2701 }
2702 }
2703 }
2704
2705 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002706 if (name == null) {
2707 name = "";
2708 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002709 T obj = mMap.get(name);
2710 if (obj != null) {
2711 return obj;
2712 }
2713
2714 // No object exists for the given name, but do we currently have it
2715 // running as part of the overflow?
2716 if (mActiveOverflow != null) {
2717 MutableInt over = mActiveOverflow.get(name);
2718 if (over != null) {
2719 // We are already actively counting this name in the overflow object.
2720 obj = mCurOverflow;
2721 if (obj == null) {
2722 // Shouldn't be here, but we'll try to recover.
2723 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2724 obj = mCurOverflow = instantiateObject();
2725 mMap.put(OVERFLOW_NAME, obj);
2726 }
2727 over.value++;
2728 return obj;
2729 }
2730 }
2731
2732 // No object exists for given name nor in the overflow; we need to make
2733 // a new one.
2734 final int N = mMap.size();
2735 if (N >= MAX_WAKELOCKS_PER_UID) {
2736 // Went over the limit on number of objects to track; this one goes
2737 // in to the overflow.
2738 obj = mCurOverflow;
2739 if (obj == null) {
2740 // Need to start overflow now...
2741 obj = mCurOverflow = instantiateObject();
2742 mMap.put(OVERFLOW_NAME, obj);
2743 }
2744 if (mActiveOverflow == null) {
2745 mActiveOverflow = new ArrayMap<>();
2746 }
2747 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002748 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002749 return obj;
2750 }
2751
2752 // Normal case where we just need to make a new object.
2753 obj = instantiateObject();
2754 mMap.put(name, obj);
2755 return obj;
2756 }
2757
2758 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002759 if (name == null) {
2760 name = "";
2761 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002762 T obj = mMap.get(name);
2763 if (obj != null) {
2764 return obj;
2765 }
2766
2767 // No object exists for the given name, but do we currently have it
2768 // running as part of the overflow?
2769 if (mActiveOverflow != null) {
2770 MutableInt over = mActiveOverflow.get(name);
2771 if (over != null) {
2772 // We are already actively counting this name in the overflow object.
2773 obj = mCurOverflow;
2774 if (obj != null) {
2775 over.value--;
2776 if (over.value <= 0) {
2777 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002778 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002779 }
2780 return obj;
2781 }
2782 }
2783 }
2784
2785 // Huh, they are stopping an active operation but we can't find one!
2786 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002787 StringBuilder sb = new StringBuilder();
2788 sb.append("Unable to find object for ");
2789 sb.append(name);
2790 sb.append(" in uid ");
2791 sb.append(mUid);
2792 sb.append(" mapsize=");
2793 sb.append(mMap.size());
2794 sb.append(" activeoverflow=");
2795 sb.append(mActiveOverflow);
2796 sb.append(" curoverflow=");
2797 sb.append(mCurOverflow);
2798 long now = SystemClock.elapsedRealtime();
2799 if (mLastOverflowTime != 0) {
2800 sb.append(" lastOverflowTime=");
2801 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2802 }
2803 if (mLastOverflowFinishTime != 0) {
2804 sb.append(" lastOverflowFinishTime=");
2805 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2806 }
2807 if (mLastClearTime != 0) {
2808 sb.append(" lastClearTime=");
2809 TimeUtils.formatDuration(mLastClearTime-now, sb);
2810 }
2811 if (mLastCleanupTime != 0) {
2812 sb.append(" lastCleanupTime=");
2813 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2814 }
2815 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002816 return null;
2817 }
2818
2819 public abstract T instantiateObject();
2820 }
2821
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002822 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2823 implements Parcelable {
2824 private final LongSamplingCounter mIdleTimeMillis;
Siddharth Rayb50a6842017-12-14 15:15:28 -08002825 private final LongSamplingCounter mScanTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002826 private final LongSamplingCounter mRxTimeMillis;
2827 private final LongSamplingCounter[] mTxTimeMillis;
2828 private final LongSamplingCounter mPowerDrainMaMs;
2829
2830 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2831 mIdleTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002832 mScanTimeMillis = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002833 mRxTimeMillis = new LongSamplingCounter(timeBase);
2834 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2835 for (int i = 0; i < numTxStates; i++) {
2836 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2837 }
2838 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2839 }
2840
2841 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2842 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002843 mScanTimeMillis = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002844 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2845 final int recordedTxStates = in.readInt();
2846 if (recordedTxStates != numTxStates) {
2847 throw new ParcelFormatException("inconsistent tx state lengths");
2848 }
2849
2850 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2851 for (int i = 0; i < numTxStates; i++) {
2852 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2853 }
2854 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2855 }
2856
2857 public void readSummaryFromParcel(Parcel in) {
2858 mIdleTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002859 mScanTimeMillis.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002860 mRxTimeMillis.readSummaryFromParcelLocked(in);
2861 final int recordedTxStates = in.readInt();
2862 if (recordedTxStates != mTxTimeMillis.length) {
2863 throw new ParcelFormatException("inconsistent tx state lengths");
2864 }
2865 for (LongSamplingCounter counter : mTxTimeMillis) {
2866 counter.readSummaryFromParcelLocked(in);
2867 }
2868 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2869 }
2870
2871 @Override
2872 public int describeContents() {
2873 return 0;
2874 }
2875
2876 public void writeSummaryToParcel(Parcel dest) {
2877 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002878 mScanTimeMillis.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002879 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2880 dest.writeInt(mTxTimeMillis.length);
2881 for (LongSamplingCounter counter : mTxTimeMillis) {
2882 counter.writeSummaryFromParcelLocked(dest);
2883 }
2884 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2885 }
2886
2887 @Override
2888 public void writeToParcel(Parcel dest, int flags) {
2889 mIdleTimeMillis.writeToParcel(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002890 mScanTimeMillis.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002891 mRxTimeMillis.writeToParcel(dest);
2892 dest.writeInt(mTxTimeMillis.length);
2893 for (LongSamplingCounter counter : mTxTimeMillis) {
2894 counter.writeToParcel(dest);
2895 }
2896 mPowerDrainMaMs.writeToParcel(dest);
2897 }
2898
2899 public void reset(boolean detachIfReset) {
2900 mIdleTimeMillis.reset(detachIfReset);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002901 mScanTimeMillis.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002902 mRxTimeMillis.reset(detachIfReset);
2903 for (LongSamplingCounter counter : mTxTimeMillis) {
2904 counter.reset(detachIfReset);
2905 }
2906 mPowerDrainMaMs.reset(detachIfReset);
2907 }
2908
2909 public void detach() {
2910 mIdleTimeMillis.detach();
Siddharth Rayb50a6842017-12-14 15:15:28 -08002911 mScanTimeMillis.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002912 mRxTimeMillis.detach();
2913 for (LongSamplingCounter counter : mTxTimeMillis) {
2914 counter.detach();
2915 }
2916 mPowerDrainMaMs.detach();
2917 }
2918
2919 /**
2920 * @return a LongSamplingCounter, measuring time spent in the idle state in
2921 * milliseconds.
2922 */
2923 @Override
2924 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07002925 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002926 }
2927
2928 /**
Siddharth Rayb50a6842017-12-14 15:15:28 -08002929 * @return a LongSamplingCounter, measuring time spent in the scan state in
2930 * milliseconds.
2931 */
2932 @Override
2933 public LongSamplingCounter getScanTimeCounter() {
2934 return mScanTimeMillis;
2935 }
2936
2937 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002938 * @return a LongSamplingCounter, measuring time spent in the receive state in
2939 * milliseconds.
2940 */
2941 @Override
2942 public LongSamplingCounter getRxTimeCounter() {
2943 return mRxTimeMillis;
2944 }
2945
2946 /**
2947 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
2948 * milliseconds.
2949 */
2950 @Override
2951 public LongSamplingCounter[] getTxTimeCounters() {
2952 return mTxTimeMillis;
2953 }
2954
2955 /**
2956 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
2957 */
2958 @Override
2959 public LongSamplingCounter getPowerCounter() {
2960 return mPowerDrainMaMs;
2961 }
2962 }
2963
Bookatz50df7112017-08-04 14:53:26 -07002964 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
2965 public SamplingTimer getRpmTimerLocked(String name) {
2966 SamplingTimer rpmt = mRpmStats.get(name);
2967 if (rpmt == null) {
2968 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2969 mRpmStats.put(name, rpmt);
2970 }
2971 return rpmt;
2972 }
2973
2974 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
2975 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
2976 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
2977 if (rpmt == null) {
2978 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
2979 mScreenOffRpmStats.put(name, rpmt);
2980 }
2981 return rpmt;
2982 }
2983
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002984 /*
2985 * Get the wakeup reason counter, and create a new one if one
2986 * doesn't already exist.
2987 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002988 public SamplingTimer getWakeupReasonTimerLocked(String name) {
2989 SamplingTimer timer = mWakeupReasonStats.get(name);
2990 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002991 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002992 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002993 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002994 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002995 }
2996
Evan Millarc64edde2009-04-18 12:26:32 -07002997 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002998 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07002999 * doesn't already exist.
3000 */
3001 public SamplingTimer getKernelWakelockTimerLocked(String name) {
3002 SamplingTimer kwlt = mKernelWakelockStats.get(name);
3003 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003004 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07003005 mKernelWakelockStats.put(name, kwlt);
3006 }
3007 return kwlt;
3008 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003009
James Carr3a226052016-07-01 14:49:52 -07003010 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
3011 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
3012 if (kmt == null) {
3013 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
3014 mKernelMemoryStats.put(bucket, kmt);
3015 }
3016 return kmt;
3017 }
3018
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003019 private int writeHistoryTag(HistoryTag tag) {
3020 Integer idxObj = mHistoryTagPool.get(tag);
3021 int idx;
3022 if (idxObj != null) {
3023 idx = idxObj;
3024 } else {
3025 idx = mNextHistoryTagIdx;
3026 HistoryTag key = new HistoryTag();
3027 key.setTo(tag);
3028 tag.poolIdx = idx;
3029 mHistoryTagPool.put(key, idx);
3030 mNextHistoryTagIdx++;
3031 mNumHistoryTagChars += key.string.length() + 1;
3032 }
3033 return idx;
3034 }
3035
3036 private void readHistoryTag(int index, HistoryTag tag) {
3037 tag.string = mReadHistoryStrings[index];
3038 tag.uid = mReadHistoryUids[index];
3039 tag.poolIdx = index;
3040 }
3041
Adam Lesinski926969b2016-04-28 17:31:12 -07003042 /*
3043 The history delta format uses flags to denote further data in subsequent ints in the parcel.
3044
3045 There is always the first token, which may contain the delta time, or an indicator of
3046 the length of the time (int or long) following this token.
3047
3048 First token: always present,
3049 31 23 15 7 0
3050 â–ˆ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â–ˆ
3051
3052 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
3053 follows containing the time, and 0x7ffff indicates a long immediately follows with the
3054 delta time.
3055 A: battery level changed and an int follows with battery data.
3056 B: state changed and an int follows with state change data.
3057 C: state2 has changed and an int follows with state2 change data.
3058 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
3059 E: event data has changed and an event struct follows.
3060 F: battery charge in coulombs has changed and an int with the charge follows.
3061 G: state flag denoting that the mobile radio was active.
3062 H: state flag denoting that the wifi radio was active.
3063 I: state flag denoting that a wifi scan occurred.
3064 J: state flag denoting that a wifi full lock was held.
3065 K: state flag denoting that the gps was on.
3066 L: state flag denoting that a wakelock was held.
3067 M: state flag denoting that the cpu was running.
3068
3069 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3070 with the time delta.
3071
3072 Battery level int: if A in the first token is set,
3073 31 23 15 7 0
3074 â–ˆ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â–ˆ
3075
3076 D: indicates that extra history details follow.
3077 V: the battery voltage.
3078 T: the battery temperature.
3079 L: the battery level (out of 100).
3080
3081 State change int: if B in the first token is set,
3082 31 23 15 7 0
3083 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3084
3085 A: wifi multicast was on.
3086 B: battery was plugged in.
3087 C: screen was on.
3088 D: phone was scanning for signal.
3089 E: audio was on.
3090 F: a sensor was active.
3091
3092 State2 change int: if C in the first token is set,
3093 31 23 15 7 0
3094 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3095
3096 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3097 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3098 C: a bluetooth scan was active.
3099 D: the camera was active.
3100 E: bluetooth was on.
3101 F: a phone call was active.
3102 G: the device was charging.
3103 H: 2 bits indicating the device-idle (doze) state: off, light, full
3104 I: the flashlight was on.
3105 J: wifi was on.
3106 K: wifi was running.
3107 L: video was playing.
3108 M: power save mode was on.
3109
3110 Wakelock/wakereason struct: if D in the first token is set,
3111 TODO(adamlesinski): describe wakelock/wakereason struct.
3112
3113 Event struct: if E in the first token is set,
3114 TODO(adamlesinski): describe the event struct.
3115
3116 History step details struct: if D in the battery level int is set,
3117 TODO(adamlesinski): describe the history step details struct.
3118
3119 Battery charge int: if F in the first token is set, an int representing the battery charge
3120 in coulombs follows.
3121 */
3122
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003123 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003124 static final int DELTA_TIME_MASK = 0x7ffff;
3125 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3126 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3127 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003128 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003129 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003130 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003131 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003132 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003133 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003134 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003135 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003136 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003137 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003138 // Flag in delta int: contains the battery charge count in uAh.
3139 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003140 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003141 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003142
3143 // These are the pieces of battery state that are packed in to the upper bits of
3144 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003145 // in STATE_BATTERY_MASK.
3146 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003147 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3148 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3149 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3150 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3151 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3152 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003153
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003154 // We use the low bit of the battery state int to indicate that we have full details
3155 // from a battery level change.
3156 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3157
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003158 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003159 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003160 dest.writeInt(DELTA_TIME_ABS);
3161 cur.writeToParcel(dest, 0);
3162 return;
3163 }
3164
3165 final long deltaTime = cur.time - last.time;
3166 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3167 final int lastStateInt = buildStateInt(last);
3168
3169 int deltaTimeToken;
3170 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3171 deltaTimeToken = DELTA_TIME_LONG;
3172 } else if (deltaTime >= DELTA_TIME_ABS) {
3173 deltaTimeToken = DELTA_TIME_INT;
3174 } else {
3175 deltaTimeToken = (int)deltaTime;
3176 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003177 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003178 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3179 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3180 final boolean computeStepDetails = includeStepDetails != 0
3181 || mLastHistoryStepDetails == null;
3182 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003183 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3184 if (batteryLevelIntChanged) {
3185 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3186 }
3187 final int stateInt = buildStateInt(cur);
3188 final boolean stateIntChanged = stateInt != lastStateInt;
3189 if (stateIntChanged) {
3190 firstToken |= DELTA_STATE_FLAG;
3191 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003192 final boolean state2IntChanged = cur.states2 != last.states2;
3193 if (state2IntChanged) {
3194 firstToken |= DELTA_STATE2_FLAG;
3195 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003196 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003197 firstToken |= DELTA_WAKELOCK_FLAG;
3198 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003199 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3200 firstToken |= DELTA_EVENT_FLAG;
3201 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003202
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003203 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3204 if (batteryChargeChanged) {
3205 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003206 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003207 dest.writeInt(firstToken);
3208 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3209 + " deltaTime=" + deltaTime);
3210
3211 if (deltaTimeToken >= DELTA_TIME_INT) {
3212 if (deltaTimeToken == DELTA_TIME_INT) {
3213 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3214 dest.writeInt((int)deltaTime);
3215 } else {
3216 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3217 dest.writeLong(deltaTime);
3218 }
3219 }
3220 if (batteryLevelIntChanged) {
3221 dest.writeInt(batteryLevelInt);
3222 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3223 + Integer.toHexString(batteryLevelInt)
3224 + " batteryLevel=" + cur.batteryLevel
3225 + " batteryTemp=" + cur.batteryTemperature
3226 + " batteryVolt=" + (int)cur.batteryVoltage);
3227 }
3228 if (stateIntChanged) {
3229 dest.writeInt(stateInt);
3230 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3231 + Integer.toHexString(stateInt)
3232 + " batteryStatus=" + cur.batteryStatus
3233 + " batteryHealth=" + cur.batteryHealth
3234 + " batteryPlugType=" + cur.batteryPlugType
3235 + " states=0x" + Integer.toHexString(cur.states));
3236 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003237 if (state2IntChanged) {
3238 dest.writeInt(cur.states2);
3239 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3240 + Integer.toHexString(cur.states2));
3241 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003242 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3243 int wakeLockIndex;
3244 int wakeReasonIndex;
3245 if (cur.wakelockTag != null) {
3246 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3247 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3248 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3249 } else {
3250 wakeLockIndex = 0xffff;
3251 }
3252 if (cur.wakeReasonTag != null) {
3253 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3254 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3255 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3256 } else {
3257 wakeReasonIndex = 0xffff;
3258 }
3259 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003260 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003261 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003262 int index = writeHistoryTag(cur.eventTag);
3263 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003264 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003265 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3266 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3267 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003268 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003269 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003270 if (mPlatformIdleStateCallback != null) {
3271 mCurHistoryStepDetails.statPlatformIdleState =
3272 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3273 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3274 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003275
3276 mCurHistoryStepDetails.statSubsystemPowerState =
3277 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3278 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3279 mCurHistoryStepDetails.statSubsystemPowerState);
3280
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003281 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003282 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3283 if (includeStepDetails != 0) {
3284 mCurHistoryStepDetails.writeToParcel(dest);
3285 }
3286 cur.stepDetails = mCurHistoryStepDetails;
3287 mLastHistoryStepDetails = mCurHistoryStepDetails;
3288 } else {
3289 cur.stepDetails = null;
3290 }
3291 if (mLastHistoryStepLevel < cur.batteryLevel) {
3292 mLastHistoryStepDetails = null;
3293 }
3294 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003295
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003296 if (batteryChargeChanged) {
3297 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3298 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003299 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003300 }
3301
3302 private int buildBatteryLevelInt(HistoryItem h) {
3303 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003304 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3305 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3306 }
3307
3308 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3309 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3310 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3311 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003312 }
3313
3314 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003315 int plugType = 0;
3316 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3317 plugType = 1;
3318 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3319 plugType = 2;
3320 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3321 plugType = 3;
3322 }
3323 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3324 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3325 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003326 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003327 }
3328
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003329 private void computeHistoryStepDetails(final HistoryStepDetails out,
3330 final HistoryStepDetails last) {
3331 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3332
3333 // Perform a CPU update right after we do this collection, so we have started
3334 // collecting good data for the next step.
3335 requestImmediateCpuUpdate();
3336
3337 if (last == null) {
3338 // We are not generating a delta, so all we need to do is reset the stats
3339 // we will later be doing a delta from.
3340 final int NU = mUidStats.size();
3341 for (int i=0; i<NU; i++) {
3342 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3343 uid.mLastStepUserTime = uid.mCurStepUserTime;
3344 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3345 }
3346 mLastStepCpuUserTime = mCurStepCpuUserTime;
3347 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3348 mLastStepStatUserTime = mCurStepStatUserTime;
3349 mLastStepStatSystemTime = mCurStepStatSystemTime;
3350 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3351 mLastStepStatIrqTime = mCurStepStatIrqTime;
3352 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3353 mLastStepStatIdleTime = mCurStepStatIdleTime;
3354 tmp.clear();
3355 return;
3356 }
3357 if (DEBUG) {
3358 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3359 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3360 + " irq=" + mLastStepStatIrqTime + " sirq="
3361 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3362 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3363 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3364 + " irq=" + mCurStepStatIrqTime + " sirq="
3365 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3366 }
3367 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3368 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3369 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3370 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3371 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3372 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3373 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3374 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3375 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3376 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3377 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3378 final int NU = mUidStats.size();
3379 for (int i=0; i<NU; i++) {
3380 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3381 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3382 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3383 final int totalTime = totalUTime + totalSTime;
3384 uid.mLastStepUserTime = uid.mCurStepUserTime;
3385 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3386 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3387 continue;
3388 }
3389 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3390 out.appCpuUid3 = uid.mUid;
3391 out.appCpuUTime3 = totalUTime;
3392 out.appCpuSTime3 = totalSTime;
3393 } else {
3394 out.appCpuUid3 = out.appCpuUid2;
3395 out.appCpuUTime3 = out.appCpuUTime2;
3396 out.appCpuSTime3 = out.appCpuSTime2;
3397 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3398 out.appCpuUid2 = uid.mUid;
3399 out.appCpuUTime2 = totalUTime;
3400 out.appCpuSTime2 = totalSTime;
3401 } else {
3402 out.appCpuUid2 = out.appCpuUid1;
3403 out.appCpuUTime2 = out.appCpuUTime1;
3404 out.appCpuSTime2 = out.appCpuSTime1;
3405 out.appCpuUid1 = uid.mUid;
3406 out.appCpuUTime1 = totalUTime;
3407 out.appCpuSTime1 = totalSTime;
3408 }
3409 }
3410 }
3411 mLastStepCpuUserTime = mCurStepCpuUserTime;
3412 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3413 mLastStepStatUserTime = mCurStepStatUserTime;
3414 mLastStepStatSystemTime = mCurStepStatSystemTime;
3415 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3416 mLastStepStatIrqTime = mCurStepStatIrqTime;
3417 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3418 mLastStepStatIdleTime = mCurStepStatIdleTime;
3419 }
3420
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003421 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3422 int firstToken = src.readInt();
3423 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003424 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003425 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003426 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3427 + " deltaTimeToken=" + deltaTimeToken);
3428
3429 if (deltaTimeToken < DELTA_TIME_ABS) {
3430 cur.time += deltaTimeToken;
3431 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3432 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003433 cur.numReadInts += 2;
3434 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003435 cur.readFromParcel(src);
3436 return;
3437 } else if (deltaTimeToken == DELTA_TIME_INT) {
3438 int delta = src.readInt();
3439 cur.time += delta;
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: time delta=" + delta + " new time=" + cur.time);
3442 } else {
3443 long delta = src.readLong();
3444 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3445 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003446 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003447 }
3448
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003449 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003450 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003451 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003452 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003453 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003454 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3455 + Integer.toHexString(batteryLevelInt)
3456 + " batteryLevel=" + cur.batteryLevel
3457 + " batteryTemp=" + cur.batteryTemperature
3458 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003459 } else {
3460 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003461 }
3462
3463 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3464 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003465 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003466 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3467 & STATE_BATTERY_STATUS_MASK);
3468 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3469 & STATE_BATTERY_HEALTH_MASK);
3470 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3471 & STATE_BATTERY_PLUG_MASK);
3472 switch (cur.batteryPlugType) {
3473 case 1:
3474 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3475 break;
3476 case 2:
3477 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3478 break;
3479 case 3:
3480 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3481 break;
3482 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003483 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003484 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3485 + Integer.toHexString(stateInt)
3486 + " batteryStatus=" + cur.batteryStatus
3487 + " batteryHealth=" + cur.batteryHealth
3488 + " batteryPlugType=" + cur.batteryPlugType
3489 + " states=0x" + Integer.toHexString(cur.states));
3490 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003491 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003492 }
3493
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003494 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3495 cur.states2 = src.readInt();
3496 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3497 + Integer.toHexString(cur.states2));
3498 }
3499
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003500 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003501 int indexes = src.readInt();
3502 int wakeLockIndex = indexes&0xffff;
3503 int wakeReasonIndex = (indexes>>16)&0xffff;
3504 if (wakeLockIndex != 0xffff) {
3505 cur.wakelockTag = cur.localWakelockTag;
3506 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3507 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3508 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3509 } else {
3510 cur.wakelockTag = null;
3511 }
3512 if (wakeReasonIndex != 0xffff) {
3513 cur.wakeReasonTag = cur.localWakeReasonTag;
3514 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3515 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3516 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3517 } else {
3518 cur.wakeReasonTag = null;
3519 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003520 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003521 } else {
3522 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003523 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003524 }
3525
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003526 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003527 cur.eventTag = cur.localEventTag;
3528 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003529 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003530 final int index = ((codeAndIndex>>16)&0xffff);
3531 readHistoryTag(index, cur.eventTag);
3532 cur.numReadInts += 1;
3533 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3534 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3535 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003536 } else {
3537 cur.eventCode = HistoryItem.EVENT_NONE;
3538 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003539
3540 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3541 cur.stepDetails = mReadHistoryStepDetails;
3542 cur.stepDetails.readFromParcel(src);
3543 } else {
3544 cur.stepDetails = null;
3545 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003546
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003547 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3548 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003549 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003550 }
3551
Dianne Hackbornfc064132014-06-02 12:42:12 -07003552 @Override
3553 public void commitCurrentHistoryBatchLocked() {
3554 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3555 }
3556
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003557 void addHistoryBufferLocked(long elapsedRealtimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003558 if (!mHaveBatteryLevel || !mRecordingHistory) {
3559 return;
3560 }
3561
Dianne Hackborn40c87252014-03-19 16:55:40 -07003562 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003563 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3564 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003565 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003566 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003567 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3568 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003569 + Integer.toHexString(lastDiffStates) + " diff2="
3570 + Integer.toHexString(diffStates2) + " lastDiff2="
3571 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003572 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003573 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003574 && (diffStates2&lastDiffStates2) == 0
3575 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3576 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003577 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003578 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003579 || cur.eventCode == HistoryItem.EVENT_NONE)
3580 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3581 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3582 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3583 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3584 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3585 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003586 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003587 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003588 // as long as no bit has changed both between now and the last entry, as
3589 // well as the last entry and the one before it (so we capture any toggles).
3590 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003591 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3592 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3593 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003594 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003595 // If the last written history had a wakelock tag, we need to retain it.
3596 // Note that the condition above made sure that we aren't in a case where
3597 // both it and the current history item have a wakelock tag.
3598 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003599 cur.wakelockTag = cur.localWakelockTag;
3600 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003601 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003602 // If the last written history had a wake reason tag, we need to retain it.
3603 // Note that the condition above made sure that we aren't in a case where
3604 // both it and the current history item have a wakelock tag.
3605 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003606 cur.wakeReasonTag = cur.localWakeReasonTag;
3607 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003608 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003609 // If the last written history had an event, we need to retain it.
3610 // Note that the condition above made sure that we aren't in a case where
3611 // both it and the current history item have an event.
3612 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003613 cur.eventCode = mHistoryLastWritten.eventCode;
3614 cur.eventTag = cur.localEventTag;
3615 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003616 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003617 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003618 }
3619
Adam Lesinski45489782016-12-15 23:45:17 -08003620 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003621 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003622 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3623 // Clients can't deal with history buffers this large. This only
3624 // really happens when the device is on charger and interacted with
3625 // for long periods of time, like in retail mode. Since the device is
3626 // most likely charged, when unplugged, stats would have reset anyways.
3627 // Reset the stats and mark that we overflowed.
3628 // b/32540341
3629 resetAllStatsLocked();
3630
3631 // Mark that we want to set *OVERFLOW* event and the RESET:START
3632 // events.
3633 recordResetDueToOverflow = true;
3634
3635 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003636 if (!mHistoryOverflow) {
3637 mHistoryOverflow = true;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003638 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
3639 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003640 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003641 }
3642
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003643 // After overflow, we allow various bit-wise states to settle to 0.
3644 boolean writeAnyway = false;
3645 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3646 & mActiveHistoryStates;
3647 if (mHistoryLastWritten.states != curStates) {
3648 // mActiveHistoryStates keeps track of which bits in .states are now being
3649 // forced to 0.
3650 int old = mActiveHistoryStates;
3651 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3652 writeAnyway |= old != mActiveHistoryStates;
3653 }
3654 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3655 & mActiveHistoryStates2;
3656 if (mHistoryLastWritten.states2 != curStates2) {
3657 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3658 // forced to 0.
3659 int old = mActiveHistoryStates2;
3660 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3661 writeAnyway |= old != mActiveHistoryStates2;
3662 }
3663
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003664 // Once we've reached the maximum number of items, we only
3665 // record changes to the battery level and the most interesting states.
3666 // Once we've reached the maximum maximum number of items, we only
3667 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003668 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003669 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003670 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003671 & HistoryItem.MOST_INTERESTING_STATES) == 0
3672 || ((mHistoryLastWritten.states2^cur.states2)
3673 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003674 return;
3675 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003676
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003677 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003678 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003679 }
3680
Adam Lesinski45489782016-12-15 23:45:17 -08003681 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003682 // The history is currently empty; we need it to start with a time stamp.
3683 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003684 if (recordResetDueToOverflow) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003685 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Adam Lesinski45489782016-12-15 23:45:17 -08003686 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003687 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_RESET, cur);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003688 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003689 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003690 }
3691
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003692 private void addHistoryBufferLocked(long elapsedRealtimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003693 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003694 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003695 }
3696 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3697 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003698 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003699 mHistoryLastWritten.states &= mActiveHistoryStates;
3700 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003701 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003702 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003703 cur.wakelockTag = null;
3704 cur.wakeReasonTag = null;
3705 cur.eventCode = HistoryItem.EVENT_NONE;
3706 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003707 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3708 + " now " + mHistoryBuffer.dataPosition()
3709 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003710 }
3711
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003712 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003713 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003714
Dianne Hackborn40c87252014-03-19 16:55:40 -07003715 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003716 if (mTrackRunningHistoryElapsedRealtime != 0) {
3717 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3718 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3719 if (diffUptime < (diffElapsed-20)) {
3720 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3721 mHistoryAddTmp.setTo(mHistoryLastWritten);
3722 mHistoryAddTmp.wakelockTag = null;
3723 mHistoryAddTmp.wakeReasonTag = null;
3724 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3725 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003726 addHistoryRecordInnerLocked(wakeElapsedTime, mHistoryAddTmp);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003727 }
3728 }
3729 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3730 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3731 mTrackRunningHistoryUptime = uptimeMs;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003732 addHistoryRecordInnerLocked(elapsedRealtimeMs, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003733 }
3734
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003735 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, HistoryItem cur) {
3736 addHistoryBufferLocked(elapsedRealtimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003737
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003738 if (!USE_OLD_HISTORY) {
3739 return;
3740 }
3741
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003742 if (!mHaveBatteryLevel || !mRecordingHistory) {
3743 return;
3744 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003745
3746 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003747 // and no states have since the last recorded entry changed and
3748 // are now resetting back to their original value, then just collapse
3749 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003750 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003751 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003752 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3753 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003754 // If the current is the same as the one before, then we no
3755 // longer need the entry.
3756 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003757 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003758 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003759 mHistoryLastEnd.next = null;
3760 mHistoryEnd.next = mHistoryCache;
3761 mHistoryCache = mHistoryEnd;
3762 mHistoryEnd = mHistoryLastEnd;
3763 mHistoryLastEnd = null;
3764 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003765 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3766 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003767 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003768 }
3769 return;
3770 }
3771
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003772 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003773 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003774
3775 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3776 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003777 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003778 }
3779
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003780 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3781 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003782 // record changes to the battery level and the most interesting states.
3783 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003784 // record changes to the battery level.
3785 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003786 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003787 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003788 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003789 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003790 return;
3791 }
3792 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003793
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +00003794 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003795 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003796
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003797 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003798 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003799 mHistoryCur.eventCode = code;
3800 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3801 mHistoryCur.eventTag.string = name;
3802 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003803 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003804 }
3805
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003806 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003807 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003808 if (rec != null) {
3809 mHistoryCache = rec.next;
3810 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003811 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003812 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003813 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003814
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003815 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003816 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003817
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003818 void addHistoryRecordLocked(HistoryItem rec) {
3819 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003820 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003821 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003822 if (mHistoryEnd != null) {
3823 mHistoryEnd.next = rec;
3824 mHistoryEnd = rec;
3825 } else {
3826 mHistory = mHistoryEnd = rec;
3827 }
3828 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003829
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003830 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003831 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003832 if (USE_OLD_HISTORY) {
3833 if (mHistory != null) {
3834 mHistoryEnd.next = mHistoryCache;
3835 mHistoryCache = mHistory;
3836 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3837 }
3838 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003839 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003840
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003841 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003842 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003843 mTrackRunningHistoryElapsedRealtime = 0;
3844 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003845
3846 mHistoryBuffer.setDataSize(0);
3847 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003848 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003849 mHistoryLastLastWritten.clear();
3850 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003851 mHistoryTagPool.clear();
3852 mNextHistoryTagIdx = 0;
3853 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003854 mHistoryBufferLastPos = -1;
3855 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003856 mActiveHistoryStates = 0xffffffff;
3857 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003858 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003859
Andreas Gampe3f24e692018-02-05 13:24:28 -08003860 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -07003861 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003862 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003863 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003864 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3865 final boolean updateOnBatteryScreenOffTimeBase =
3866 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003867
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003868 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3869 if (updateOnBatteryScreenOffTimeBase) {
3870 updateKernelWakelocksLocked();
3871 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003872 }
Bookatz82b341172017-09-07 19:06:08 -07003873 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3874 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3875 // improved, remove the surrounding if{}.
3876 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3877 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3878 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003879 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003880 Slog.d(TAG, "Updating cpu time because screen is now "
3881 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003882 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003883 }
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003884
3885 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07003886 if (updateOnBatteryTimeBase) {
3887 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3888 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003889 }
Mike Mac2f518a2017-09-19 16:06:03 -07003890 }
3891 if (updateOnBatteryScreenOffTimeBase) {
3892 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
3893 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3894 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003895 }
Bookatzc8c44962017-05-11 12:12:54 -07003896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 }
3898 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003899
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003900 private void updateBatteryPropertiesLocked() {
3901 try {
3902 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
3903 ServiceManager.getService("batteryproperties"));
3904 registrar.scheduleUpdate();
3905 } catch (RemoteException e) {
3906 // Ignore.
3907 }
3908 }
3909
Dianne Hackborn099bc622014-01-22 13:39:16 -08003910 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
3911 mIsolatedUids.put(isolatedUid, appUid);
Bookatz90867622018-01-31 15:05:57 -08003912 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid,
3913 StatsLog.ISOLATED_UID_CHANGED__EVENT__CREATED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003914 final Uid u = getUidStatsLocked(appUid);
3915 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003916 }
3917
Adam Lesinski61db88f2015-07-01 15:05:07 -07003918 /**
3919 * Schedules a read of the latest cpu times before removing the isolated UID.
3920 * @see #removeIsolatedUidLocked(int)
3921 */
3922 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003923 int curUid = mIsolatedUids.get(isolatedUid, -1);
3924 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07003925 if (mExternalSync != null) {
3926 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
3927 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08003928 }
3929 }
3930
Adam Lesinski61db88f2015-07-01 15:05:07 -07003931 /**
3932 * This should only be called after the cpu times have been read.
3933 * @see #scheduleRemoveIsolatedUidLocked(int, int)
3934 */
Andreas Gampe3f24e692018-02-05 13:24:28 -08003935 @GuardedBy("this")
Adam Lesinski61db88f2015-07-01 15:05:07 -07003936 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003937 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08003938 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1),
3939 isolatedUid, StatsLog.ISOLATED_UID_CHANGED__EVENT__REMOVED);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003940 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
3941 if (idx >= 0) {
3942 final int ownerUid = mIsolatedUids.valueAt(idx);
3943 final Uid u = getUidStatsLocked(ownerUid);
3944 u.removeIsolatedUid(isolatedUid);
3945 mIsolatedUids.removeAt(idx);
3946 }
3947 mKernelUidCpuTimeReader.removeUid(isolatedUid);
3948 mKernelUidCpuFreqTimeReader.removeUid(isolatedUid);
Mike Mafae87da2018-01-19 20:07:20 -08003949 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
3950 mKernelUidCpuActiveTimeReader.removeUid(isolatedUid);
3951 mKernelUidCpuClusterTimeReader.removeUid(isolatedUid);
3952 }
Adam Lesinski61db88f2015-07-01 15:05:07 -07003953 }
3954
Dianne Hackborn099bc622014-01-22 13:39:16 -08003955 public int mapUid(int uid) {
3956 int isolated = mIsolatedUids.get(uid, -1);
3957 return isolated > 0 ? isolated : uid;
3958 }
3959
3960 public void noteEventLocked(int code, String name, int uid) {
3961 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003962 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3963 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003964 }
Joe Onoratoabded112016-02-08 16:49:39 -08003965 final long elapsedRealtime = mClocks.elapsedRealtime();
3966 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003967 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003968 }
3969
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003970 boolean ensureStartClockTime(final long currentTime) {
3971 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
3972 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
3973 // If the start clock time has changed by more than a year, then presumably
3974 // the previous time was completely bogus. So we are going to figure out a
3975 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08003976 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003977 return true;
3978 }
3979 return false;
3980 }
3981
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003982 public void noteCurrentTimeChangedLocked() {
3983 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003984 final long elapsedRealtime = mClocks.elapsedRealtime();
3985 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003986 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003987 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003988 }
3989
Dianne Hackborn61659e52014-07-09 16:13:01 -07003990 public void noteProcessStartLocked(String name, int uid) {
3991 uid = mapUid(uid);
3992 if (isOnBattery()) {
3993 Uid u = getUidStatsLocked(uid);
3994 u.getProcessStatsLocked(name).incStartsLocked();
3995 }
3996 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3997 return;
3998 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003999 if (!mRecordAllHistory) {
4000 return;
4001 }
Joe Onoratoabded112016-02-08 16:49:39 -08004002 final long elapsedRealtime = mClocks.elapsedRealtime();
4003 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07004004 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
4005 }
4006
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004007 public void noteProcessCrashLocked(String name, int uid) {
4008 uid = mapUid(uid);
4009 if (isOnBattery()) {
4010 Uid u = getUidStatsLocked(uid);
4011 u.getProcessStatsLocked(name).incNumCrashesLocked();
4012 }
4013 }
4014
4015 public void noteProcessAnrLocked(String name, int uid) {
4016 uid = mapUid(uid);
4017 if (isOnBattery()) {
4018 Uid u = getUidStatsLocked(uid);
4019 u.getProcessStatsLocked(name).incNumAnrsLocked();
4020 }
4021 }
4022
Dianne Hackborna8d10942015-11-19 17:55:19 -08004023 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07004024 int parentUid = mapUid(uid);
4025 if (uid != parentUid) {
4026 // Isolated UIDs process state is already rolled up into parent, so no need to track
4027 // Otherwise the parent's process state will get downgraded incorrectly
4028 return;
4029 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08004030 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004031 }
4032
4033 public void noteProcessFinishLocked(String name, int uid) {
4034 uid = mapUid(uid);
4035 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4036 return;
4037 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004038 if (!mRecordAllHistory) {
4039 return;
4040 }
Joe Onoratoabded112016-02-08 16:49:39 -08004041 final long elapsedRealtime = mClocks.elapsedRealtime();
4042 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004043 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004044 }
4045
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004046 public void noteSyncStartLocked(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).noteStartSyncLocked(name, elapsedRealtime);
4051 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4052 return;
4053 }
4054 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4055 }
4056
4057 public void noteSyncFinishLocked(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).noteStopSyncLocked(name, elapsedRealtime);
4062 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4063 return;
4064 }
4065 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4066 }
4067
4068 public void noteJobStartLocked(String name, int uid) {
4069 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004070 final long elapsedRealtime = mClocks.elapsedRealtime();
4071 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004072 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4073 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4074 return;
4075 }
4076 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4077 }
4078
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004079 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004080 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004081 final long elapsedRealtime = mClocks.elapsedRealtime();
4082 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004083 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004084 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4085 return;
4086 }
4087 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4088 }
4089
Amith Yamasani977e11f2018-02-16 11:29:54 -08004090 public void noteJobsDeferredLocked(int uid, int numDeferred, long sinceLast) {
4091 uid = mapUid(uid);
4092 getUidStatsLocked(uid).noteJobsDeferredLocked(numDeferred, sinceLast);
4093 }
4094
Narayan Kamath695cf722017-12-21 18:32:47 +00004095 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4096 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004097 }
4098
Narayan Kamath695cf722017-12-21 18:32:47 +00004099 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4100 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4101 }
4102
4103 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4104 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004105 if (!mRecordAllHistory) {
4106 return;
4107 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004108
Joe Onoratoabded112016-02-08 16:49:39 -08004109 final long elapsedRealtime = mClocks.elapsedRealtime();
4110 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004111
4112 if (workSource != null) {
4113 for (int i = 0; i < workSource.size(); ++i) {
4114 uid = mapUid(workSource.get(i));
4115 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4116 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4117 }
4118 }
4119
4120 List<WorkChain> workChains = workSource.getWorkChains();
4121 if (workChains != null) {
4122 for (int i = 0; i < workChains.size(); ++i) {
4123 uid = mapUid(workChains.get(i).getAttributionUid());
4124 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4125 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4126 }
4127 }
4128 }
4129 } else {
4130 uid = mapUid(uid);
4131
4132 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4133 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4134 }
4135 }
4136 }
4137
4138 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4139 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004140 if (workSource != null) {
4141 for (int i = 0; i < workSource.size(); ++i) {
4142 uid = workSource.get(i);
4143 final String workSourceName = workSource.getName(i);
4144
Tej Singh6f724c42018-01-03 20:02:03 -08004145 if (isOnBattery()) {
4146 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4147 workSourceName != null ? workSourceName : packageName);
4148 pkg.noteWakeupAlarmLocked(tag);
4149 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004150 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4151 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004152 }
4153
4154 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4155 if (workChains != null) {
4156 for (int i = 0; i < workChains.size(); ++i) {
4157 final WorkChain wc = workChains.get(i);
4158 uid = wc.getAttributionUid();
4159
Tej Singh6f724c42018-01-03 20:02:03 -08004160 if (isOnBattery()) {
4161 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4162 pkg.noteWakeupAlarmLocked(tag);
4163 }
Yangster-macafad8c62018-01-05 22:30:49 -08004164 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004165 }
4166 }
4167 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004168 if (isOnBattery()) {
4169 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4170 pkg.noteWakeupAlarmLocked(tag);
4171 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004172 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004173 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004174 }
4175
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004176 private void requestWakelockCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004177 mExternalSync.scheduleCpuSyncDueToWakelockChange(DELAY_UPDATE_WAKELOCKS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004178 }
4179
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004180 private void requestImmediateCpuUpdate() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004181 mExternalSync.scheduleCpuSyncDueToWakelockChange(0 /* delayMillis */);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004182 }
4183
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004184 public void setRecordAllHistoryLocked(boolean enabled) {
4185 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004186 if (!enabled) {
4187 // Clear out any existing state.
4188 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004189 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004190 // Record the currently running processes as stopping, now that we are no
4191 // longer tracking them.
4192 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4193 HistoryItem.EVENT_PROC);
4194 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004195 long mSecRealtime = mClocks.elapsedRealtime();
4196 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004197 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4198 SparseIntArray uids = ent.getValue();
4199 for (int j=0; j<uids.size(); j++) {
4200 addHistoryEventLocked(mSecRealtime, mSecUptime,
4201 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4202 }
4203 }
4204 }
4205 } else {
4206 // Record the currently running processes as starting, now that we are tracking them.
4207 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4208 HistoryItem.EVENT_PROC);
4209 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004210 long mSecRealtime = mClocks.elapsedRealtime();
4211 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004212 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4213 SparseIntArray uids = ent.getValue();
4214 for (int j=0; j<uids.size(); j++) {
4215 addHistoryEventLocked(mSecRealtime, mSecUptime,
4216 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4217 }
4218 }
4219 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004220 }
4221 }
4222
Dianne Hackborn9a755432014-05-15 17:05:22 -07004223 public void setNoAutoReset(boolean enabled) {
4224 mNoAutoReset = enabled;
4225 }
4226
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004227 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004228 if (mPretendScreenOff != pretendScreenOff) {
4229 mPretendScreenOff = pretendScreenOff;
4230 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4231 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004232 }
4233
Dianne Hackborn9a755432014-05-15 17:05:22 -07004234 private String mInitialAcquireWakeName;
4235 private int mInitialAcquireWakeUid = -1;
4236
Narayan Kamath81822022017-12-08 11:56:01 +00004237 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4238 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004239 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004240 if (type == WAKE_TYPE_PARTIAL) {
4241 // Only care about partial wake locks, since full wake locks
4242 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004243 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004244 if (historyName == null) {
4245 historyName = name;
4246 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004247 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004248 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4249 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004250 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004251 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004252 }
4253 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004254 if (mWakeLockNesting == 0) {
4255 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4256 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4257 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004258 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004259 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004260 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004261 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004262 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004263 } else if (!mWakeLockImportant && !unimportantForLogging
4264 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004265 if (mHistoryLastWritten.wakelockTag != null) {
4266 // We'll try to update the last tag.
4267 mHistoryLastWritten.wakelockTag = null;
4268 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004269 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004270 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004271 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004272 }
4273 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004274 }
4275 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004276 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004277 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004278 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4279 // We only update the cpu time when a wake lock is acquired if the screen is off.
4280 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4281 if (DEBUG_ENERGY_CPU) {
4282 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4283 }
4284 requestWakelockCpuUpdate();
4285 }
Narayan Kamath81822022017-12-08 11:56:01 +00004286
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004287 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004288
Yangster-mac20877162017-12-22 17:19:39 -08004289 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004290 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004291 getPowerManagerWakeLockLevel(type), name,
4292 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Yangster-macafad8c62018-01-05 22:30:49 -08004293 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004294 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004295 getPowerManagerWakeLockLevel(type), name,
4296 StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
Narayan Kamath81822022017-12-08 11:56:01 +00004297 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004298 }
4299 }
4300
Narayan Kamath81822022017-12-08 11:56:01 +00004301 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4302 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004303 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004304 if (type == WAKE_TYPE_PARTIAL) {
4305 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004306 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004307 if (historyName == null) {
4308 historyName = name;
4309 }
4310 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4311 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004312 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004313 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004314 }
4315 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004316 if (mWakeLockNesting == 0) {
4317 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4318 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4319 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004320 mInitialAcquireWakeName = null;
4321 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004322 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004323 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004324 }
4325 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004326 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4327 if (DEBUG_ENERGY_CPU) {
4328 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4329 }
4330 requestWakelockCpuUpdate();
4331 }
Narayan Kamath81822022017-12-08 11:56:01 +00004332
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004333 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004334 if (wc != null) {
Bookatz1a1b0462018-01-12 11:47:03 -08004335 StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
Bookatz90867622018-01-31 15:05:57 -08004336 getPowerManagerWakeLockLevel(type), name,
4337 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Yangster-macafad8c62018-01-05 22:30:49 -08004338 } else {
Bookatz1a1b0462018-01-12 11:47:03 -08004339 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08004340 getPowerManagerWakeLockLevel(type), name,
4341 StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
Narayan Kamath81822022017-12-08 11:56:01 +00004342 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004343 }
4344 }
4345
Bookatz1a1b0462018-01-12 11:47:03 -08004346 /**
4347 * Converts BatteryStats wakelock types back into PowerManager wakelock levels.
4348 * This is the inverse map of Notifier.getBatteryStatsWakeLockMonitorType().
4349 * These are estimations, since batterystats loses some of the original data.
4350 * TODO: Delete this. Instead, StatsLog.write should be called from PowerManager's Notifier.
4351 */
4352 private int getPowerManagerWakeLockLevel(int battertStatsWakelockType) {
4353 switch (battertStatsWakelockType) {
4354 // PowerManager.PARTIAL_WAKE_LOCK or PROXIMITY_SCREEN_OFF_WAKE_LOCK
4355 case BatteryStats.WAKE_TYPE_PARTIAL:
4356 return PowerManager.PARTIAL_WAKE_LOCK;
4357
4358 // PowerManager.SCREEN_DIM_WAKE_LOCK or SCREEN_BRIGHT_WAKE_LOCK
4359 case BatteryStats.WAKE_TYPE_FULL:
4360 return PowerManager.FULL_WAKE_LOCK;
4361
4362 case BatteryStats.WAKE_TYPE_DRAW:
4363 return PowerManager.DRAW_WAKE_LOCK;
4364
4365 // It appears that nothing can ever make a Window and PowerManager lacks an equivalent.
4366 case BatteryStats.WAKE_TYPE_WINDOW:
4367 Slog.e(TAG, "Illegal window wakelock type observed in batterystats.");
4368 return -1;
4369
4370 default:
4371 Slog.e(TAG, "Illegal wakelock type in batterystats: " + battertStatsWakelockType);
4372 return -1;
4373 }
4374 }
4375
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004376 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4377 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004378 final long elapsedRealtime = mClocks.elapsedRealtime();
4379 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004380 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004381 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004382 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4383 unimportantForLogging, elapsedRealtime, uptime);
4384 }
4385
4386 List<WorkChain> wcs = ws.getWorkChains();
4387 if (wcs != null) {
4388 for (int i = 0; i < wcs.size(); ++i) {
4389 final WorkChain wc = wcs.get(i);
4390 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4391 unimportantForLogging, elapsedRealtime, uptime);
4392 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004393 }
4394 }
4395
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004396 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4397 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004398 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004399 final long elapsedRealtime = mClocks.elapsedRealtime();
4400 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004401
4402 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4403
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004404 // For correct semantics, we start the need worksources first, so that we won't
4405 // make inappropriate history items as if all wake locks went away and new ones
4406 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004407 //
4408 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004409 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004410 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004411 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004412 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004413 }
Narayan Kamath81822022017-12-08 11:56:01 +00004414 if (wcs != null) {
4415 List<WorkChain> newChains = wcs[0];
4416 if (newChains != null) {
4417 for (int i = 0; i < newChains.size(); ++i) {
4418 final WorkChain newChain = newChains.get(i);
4419 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4420 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4421 uptime);
4422 }
4423 }
4424 }
4425
4426 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004427 final int NO = ws.size();
4428 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004429 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4430 uptime);
4431 }
4432 if (wcs != null) {
4433 List<WorkChain> goneChains = wcs[1];
4434 if (goneChains != null) {
4435 for (int i = 0; i < goneChains.size(); ++i) {
4436 final WorkChain goneChain = goneChains.get(i);
4437 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4438 historyName, type, elapsedRealtime, uptime);
4439 }
4440 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004441 }
4442 }
4443
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004444 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4445 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004446 final long elapsedRealtime = mClocks.elapsedRealtime();
4447 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004448 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004449 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004450 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4451 uptime);
4452 }
4453
4454 List<WorkChain> wcs = ws.getWorkChains();
4455 if (wcs != null) {
4456 for (int i = 0; i < wcs.size(); ++i) {
4457 final WorkChain wc = wcs.get(i);
4458 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4459 elapsedRealtime, uptime);
4460 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004461 }
4462 }
4463
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004464 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004465 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004466 uid, null, name, historyName,
4467 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08004468
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004469 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004470 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004471 }
4472
4473 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4474 WorkSource workSource) {
4475 final int N = workSource.size();
4476 for (int i = 0; i < N; ++i) {
4477 final int uid = mapUid(workSource.get(i));
4478 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004479 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004480 workSource.get(i), workSource.getName(i), name, historyName,
4481 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004482 }
4483
4484 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4485 if (workChains != null) {
4486 for (int i = 0; i < workChains.size(); ++i) {
4487 final WorkChain workChain = workChains.get(i);
4488 final int uid = workChain.getAttributionUid();
4489 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4490
Yangster-macafad8c62018-01-05 22:30:49 -08004491 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004492 workChain.getUids(), workChain.getTags(), name, historyName,
4493 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath96a92562018-01-02 18:57:17 +00004494 }
4495 }
4496 }
4497
4498 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004499 final long elapsedRealtime = mClocks.elapsedRealtime();
4500 final long uptime = mClocks.uptimeMillis();
4501 if (historyName == null) {
4502 historyName = name;
4503 }
4504 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4505 0)) {
4506 return;
4507 }
4508 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4509 historyName, uid);
4510 }
4511
4512 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Bookatz90867622018-01-31 15:05:57 -08004513 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, null,
4514 name, historyName, StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08004515
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004516 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004517 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004518 }
4519
4520 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4521 WorkSource workSource) {
4522 final int N = workSource.size();
4523 for (int i = 0; i < N; ++i) {
4524 final int uid = mapUid(workSource.get(i));
4525 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004526 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004527 workSource.get(i), workSource.getName(i), name, historyName,
4528 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004529 }
4530
4531 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4532 if (workChains != null) {
4533 for (int i = 0; i < workChains.size(); ++i) {
4534 final WorkChain workChain = workChains.get(i);
4535 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004536 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004537 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004538 workChain.getUids(), workChain.getTags(), name, historyName,
4539 StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath96a92562018-01-02 18:57:17 +00004540 }
4541 }
4542 }
4543
4544 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004545 final long elapsedRealtime = mClocks.elapsedRealtime();
4546 final long uptime = mClocks.uptimeMillis();
4547 if (historyName == null) {
4548 historyName = name;
4549 }
4550 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4551 0)) {
4552 return;
4553 }
4554 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4555 historyName, uid);
4556 }
4557
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004558 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4559 if (mLastWakeupReason != null) {
4560 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004561 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004562 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz90867622018-01-31 15:05:57 -08004563 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
4564 /* duration_usec */ deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004565 mLastWakeupReason = null;
4566 }
4567 }
4568
4569 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004570 final long elapsedRealtime = mClocks.elapsedRealtime();
4571 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004572 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004573 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004574 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004575 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4576 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004577 mHistoryCur.wakeReasonTag.uid = 0;
4578 mLastWakeupReason = reason;
4579 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004580 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004581 }
4582
Adam Lesinski72478f02015-06-17 15:39:43 -07004583 public boolean startAddingCpuLocked() {
Sudheer Shankac57729a2018-02-09 15:44:42 -08004584 mExternalSync.cancelCpuSyncDueToWakelockChange();
Adam Lesinski72478f02015-06-17 15:39:43 -07004585 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004586 }
4587
Adam Lesinski72478f02015-06-17 15:39:43 -07004588 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4589 int statSystemTime, int statIOWaitTime, int statIrqTime,
4590 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004591 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4592 + " user=" + statUserTime + " sys=" + statSystemTime
4593 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4594 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4595 mCurStepCpuUserTime += totalUTime;
4596 mCurStepCpuSystemTime += totalSTime;
4597 mCurStepStatUserTime += statUserTime;
4598 mCurStepStatSystemTime += statSystemTime;
4599 mCurStepStatIOWaitTime += statIOWaitTime;
4600 mCurStepStatIrqTime += statIrqTime;
4601 mCurStepStatSoftIrqTime += statSoftIrqTime;
4602 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004603 }
4604
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004605 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004606 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004607 Uid u = mUidStats.get(uid);
4608 if (u != null) {
4609 u.mPids.remove(pid);
4610 }
4611 }
4612
4613 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004614 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004615 Uid u = mUidStats.get(uid);
4616 if (u != null) {
4617 Uid.Pid p = u.mPids.get(pid);
4618 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004619 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004620 }
4621 }
4622 return 0;
4623 }
4624
Dianne Hackborn287952c2010-09-22 22:34:31 -07004625 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004626 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004627 Uid u = mUidStats.get(uid);
4628 if (u != null) {
4629 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4630 }
4631 }
4632
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004633 int mSensorNesting;
4634
4635 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004636 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004637 final long elapsedRealtime = mClocks.elapsedRealtime();
4638 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004639 if (mSensorNesting == 0) {
4640 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4641 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4642 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004643 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004644 }
4645 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004646 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004647 }
4648
4649 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004650 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004651 final long elapsedRealtime = mClocks.elapsedRealtime();
4652 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004653 mSensorNesting--;
4654 if (mSensorNesting == 0) {
4655 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4656 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4657 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004658 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004659 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004660 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004661 }
4662
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004663 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004664
Narayan Kamath32684dd2018-01-08 17:32:51 +00004665 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4666 for (int i = 0; i < newWs.size(); ++i) {
4667 noteStartGpsLocked(newWs.get(i), null);
4668 }
4669
4670 for (int i = 0; i < oldWs.size(); ++i) {
4671 noteStopGpsLocked((oldWs.get(i)), null);
4672 }
4673
4674 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4675 if (wcs != null) {
4676 if (wcs[0] != null) {
4677 final List<WorkChain> newChains = wcs[0];
4678 for (int i = 0; i < newChains.size(); ++i) {
4679 noteStartGpsLocked(-1, newChains.get(i));
4680 }
4681 }
4682
4683 if (wcs[1] != null) {
4684 final List<WorkChain> goneChains = wcs[1];
4685 for (int i = 0; i < goneChains.size(); ++i) {
4686 noteStopGpsLocked(-1, goneChains.get(i));
4687 }
4688 }
4689 }
4690 }
4691
4692 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4693 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004694 final long elapsedRealtime = mClocks.elapsedRealtime();
4695 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004696 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004697 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004698 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4699 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004700 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004701 }
4702 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004703
4704 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004705 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4706 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004707 } else {
4708 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08004709 workChain.getUids(), workChain.getTags(),
4710 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004711 }
4712
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004713 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004714 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004715
Narayan Kamath32684dd2018-01-08 17:32:51 +00004716 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4717 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004718 final long elapsedRealtime = mClocks.elapsedRealtime();
4719 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004720 mGpsNesting--;
4721 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004722 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004723 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4724 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004725 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004726 stopAllGpsSignalQualityTimersLocked(-1);
4727 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004728 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004729
4730 if (workChain == null) {
Bookatz90867622018-01-31 15:05:57 -08004731 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
4732 StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004733 } else {
4734 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08004735 workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath32684dd2018-01-08 17:32:51 +00004736 }
4737
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004738 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004739 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004740
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004741 public void noteGpsSignalQualityLocked(int signalLevel) {
4742 if (mGpsNesting == 0) {
4743 return;
4744 }
4745 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4746 stopAllGpsSignalQualityTimersLocked(-1);
4747 return;
4748 }
4749 final long elapsedRealtime = mClocks.elapsedRealtime();
4750 final long uptime = mClocks.uptimeMillis();
4751 if (mGpsSignalQualityBin != signalLevel) {
4752 if (mGpsSignalQualityBin >= 0) {
4753 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4754 }
4755 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4756 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4757 }
4758 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4759 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4760 addHistoryRecordLocked(elapsedRealtime, uptime);
4761 mGpsSignalQualityBin = signalLevel;
4762 }
4763 return;
4764 }
4765
Andreas Gampe3f24e692018-02-05 13:24:28 -08004766 @GuardedBy("this")
Jeff Browne95c3cd2014-05-02 16:59:26 -07004767 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004768 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004769
4770 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4771 // original 4 are mapped to one of the originals.
4772 if (state > MAX_TRACKED_SCREEN_STATE) {
4773 switch (state) {
4774 case Display.STATE_VR:
4775 state = Display.STATE_ON;
4776 break;
4777 default:
4778 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4779 break;
4780 }
4781 }
4782
Jeff Browne95c3cd2014-05-02 16:59:26 -07004783 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004784 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004785 final int oldState = mScreenState;
4786 mScreenState = state;
4787 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4788 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004789
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004790 if (state != Display.STATE_UNKNOWN) {
4791 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004792 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4793 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4794 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004795 } else {
4796 Slog.wtf(TAG, "Unexpected screen state: " + state);
4797 }
4798 }
4799
Mike Mac2f518a2017-09-19 16:06:03 -07004800 final long elapsedRealtime = mClocks.elapsedRealtime();
4801 final long uptime = mClocks.uptimeMillis();
4802
4803 boolean updateHistory = false;
4804 if (isScreenDoze(state)) {
4805 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4806 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4807 updateHistory = true;
4808 } else if (isScreenDoze(oldState)) {
4809 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4810 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4811 updateHistory = true;
4812 }
4813 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004814 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4815 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4816 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004817 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4818 if (mScreenBrightnessBin >= 0) {
4819 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4820 }
Mike Mac2f518a2017-09-19 16:06:03 -07004821 updateHistory = true;
4822 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004823 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4824 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4825 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004826 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4827 if (mScreenBrightnessBin >= 0) {
4828 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4829 }
Mike Mac2f518a2017-09-19 16:06:03 -07004830 updateHistory = true;
4831 }
4832 if (updateHistory) {
4833 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4834 + Display.stateToString(state));
4835 addHistoryRecordLocked(elapsedRealtime, uptime);
4836 }
Sudheer Shankac57729a2018-02-09 15:44:42 -08004837 mExternalSync.scheduleCpuSyncDueToScreenStateChange(
4838 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
Mike Mac2f518a2017-09-19 16:06:03 -07004839 if (isScreenOn(state)) {
4840 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4841 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4842 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004843 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004844 elapsedRealtime, uptime);
4845 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004846 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004847 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004848 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004849 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004850 }
4851 // Update discharge amounts.
4852 if (mOnBatteryInternal) {
4853 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004854 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004855 }
4856 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004857
Dianne Hackborn617f8772009-03-31 15:04:46 -07004858 public void noteScreenBrightnessLocked(int brightness) {
4859 // Bin the brightness.
4860 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4861 if (bin < 0) bin = 0;
4862 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4863 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004864 final long elapsedRealtime = mClocks.elapsedRealtime();
4865 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004866 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4867 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004868 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4869 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004870 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004871 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004872 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004873 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004874 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004875 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004876 }
4877 mScreenBrightnessBin = bin;
4878 }
4879 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004880
Dianne Hackborn617f8772009-03-31 15:04:46 -07004881 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004882 if (mOnBatteryInternal) {
4883 uid = mapUid(uid);
4884 getUidStatsLocked(uid).noteUserActivityLocked(event);
4885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004886 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004887
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004888 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004889 final long elapsedRealtime = mClocks.elapsedRealtime();
4890 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004891 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4892 reason, reasonUid);
4893 }
4894
Jeff Browne95c3cd2014-05-02 16:59:26 -07004895 public void noteInteractiveLocked(boolean interactive) {
4896 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08004897 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004898 mInteractive = interactive;
4899 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
4900 if (interactive) {
4901 mInteractiveTimer.startRunningLocked(elapsedRealtime);
4902 } else {
4903 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
4904 }
4905 }
4906 }
4907
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004908 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004909 final long elapsedRealtime = mClocks.elapsedRealtime();
4910 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004911 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4912 extra, type);
4913 mNumConnectivityChange++;
4914 }
4915
Adam Lesinski5f056f62016-07-14 16:56:08 -07004916 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4917 final long uptimeMillis, int uid) {
4918 uid = mapUid(uid);
4919 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4920 uid);
4921 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4922 }
4923
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004924 /**
4925 * Updates the radio power state and returns true if an external stats collection should occur.
4926 */
4927 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004928 final long elapsedRealtime = mClocks.elapsedRealtime();
4929 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004930 if (mMobileRadioPowerState != powerState) {
4931 long realElapsedRealtimeMs;
4932 final boolean active =
4933 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4934 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4935 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004936 if (uid > 0) {
4937 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4938 }
4939
Adam Lesinski9acfd812016-04-19 18:29:50 -07004940 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004941 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4942 } else {
4943 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004944 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004945 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4946 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4947 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004948 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004949 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4950 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4951 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004952 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004953 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4954 }
4955 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4956 + Integer.toHexString(mHistoryCur.states));
4957 addHistoryRecordLocked(elapsedRealtime, uptime);
4958 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08004959 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004960 if (active) {
4961 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4962 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4963 } else {
4964 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004965 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004966 // Tell the caller to collect radio network/power stats.
4967 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004968 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004969 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004970 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004971 }
4972
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004973 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004974 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004975 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4976 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4977 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004978 final long elapsedRealtime = mClocks.elapsedRealtime();
4979 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004980 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004981 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004982 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4983 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004984 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004985 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004986 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004987 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4988 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004989 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004990 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004991 }
4992 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatz90867622018-01-31 15:05:57 -08004993 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
4994 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
4995 StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004996 }
4997 }
4998
Bookatzddccf0a2017-11-28 16:48:14 -08004999 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005000 final long elapsedRealtime = mClocks.elapsedRealtime();
5001 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005002 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005003 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005004 // We don't go out of general idling mode until explicitly taken out of
5005 // device idle through going active or significant motion.
5006 nowIdling = true;
5007 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005008 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
5009 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
5010 // We don't go out of general light idling mode until explicitly taken out of
5011 // device idle through going active or significant motion.
5012 nowLightIdling = true;
5013 }
5014 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
5015 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
5016 activeReason, activeUid);
5017 }
Bookatzddccf0a2017-11-28 16:48:14 -08005018 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
5019 int statsmode;
5020 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
5021 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
5022 else statsmode = DEVICE_IDLE_MODE_OFF;
5023 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
5024 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005025 if (mDeviceIdling != nowIdling) {
5026 mDeviceIdling = nowIdling;
5027 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
5028 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
5029 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005030 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005031 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
5032 } else {
5033 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
5034 }
5035 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005036 if (mDeviceLightIdling != nowLightIdling) {
5037 mDeviceLightIdling = nowLightIdling;
5038 if (nowLightIdling) {
5039 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005040 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005041 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005042 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005043 }
5044 if (mDeviceIdleMode != mode) {
5045 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
5046 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
5047 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
5048 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005049 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005050 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
5051 mLastIdleTimeStart = elapsedRealtime;
5052 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
5053 if (lastDuration > mLongestLightIdleTime) {
5054 mLongestLightIdleTime = lastDuration;
5055 }
5056 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005057 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005058 if (lastDuration > mLongestFullIdleTime) {
5059 mLongestFullIdleTime = lastDuration;
5060 }
5061 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
5062 }
5063 if (mode == DEVICE_IDLE_MODE_LIGHT) {
5064 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005065 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005066 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
5067 }
5068 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08005069 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005070 }
5071 }
5072
Dianne Hackborn3accca02013-09-20 09:32:11 -07005073 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08005074 final long elapsedRealtime = mClocks.elapsedRealtime();
5075 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07005076 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005077 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07005078 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005079 PackageChange pc = new PackageChange();
5080 pc.mPackageName = pkgName;
5081 pc.mUpdate = true;
5082 pc.mVersionCode = versionCode;
5083 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005084 }
5085
5086 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005087 final long elapsedRealtime = mClocks.elapsedRealtime();
5088 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005089 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5090 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005091 PackageChange pc = new PackageChange();
5092 pc.mPackageName = pkgName;
5093 pc.mUpdate = true;
5094 addPackageChange(pc);
5095 }
5096
5097 private void addPackageChange(PackageChange pc) {
5098 if (mDailyPackageChanges == null) {
5099 mDailyPackageChanges = new ArrayList<>();
5100 }
5101 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005102 }
5103
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005104 void stopAllGpsSignalQualityTimersLocked(int except) {
5105 final long elapsedRealtime = mClocks.elapsedRealtime();
5106 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5107 if (i == except) {
5108 continue;
5109 }
5110 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5111 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5112 }
5113 }
5114 }
5115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005116 public void notePhoneOnLocked() {
5117 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005118 final long elapsedRealtime = mClocks.elapsedRealtime();
5119 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005120 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005121 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5122 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005123 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005125 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005126 }
5127 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 public void notePhoneOffLocked() {
5130 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005131 final long elapsedRealtime = mClocks.elapsedRealtime();
5132 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005133 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005134 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5135 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005136 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005138 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 }
5140 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005141
Dianne Hackborn3251b902014-06-20 14:40:53 -07005142 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005143 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005144 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005145 if (i == except) {
5146 continue;
5147 }
5148 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005149 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005150 }
5151 }
5152 }
5153
Dianne Hackborne4a59512010-12-07 11:08:07 -08005154 private int fixPhoneServiceState(int state, int signalBin) {
5155 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5156 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5157 // to infer that we are scanning from other data.
5158 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005159 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005160 state = ServiceState.STATE_IN_SERVICE;
5161 }
5162 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005163
Dianne Hackborne4a59512010-12-07 11:08:07 -08005164 return state;
5165 }
5166
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005167 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005168 boolean scanning = false;
5169 boolean newHistory = false;
5170
5171 mPhoneServiceStateRaw = state;
5172 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005173 mPhoneSignalStrengthBinRaw = strengthBin;
5174
Joe Onoratoabded112016-02-08 16:49:39 -08005175 final long elapsedRealtime = mClocks.elapsedRealtime();
5176 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005177
5178 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5179 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5180 // to infer that we are scanning from other data.
5181 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005182 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005183 state = ServiceState.STATE_IN_SERVICE;
5184 }
5185 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005186
5187 // If the phone is powered off, stop all timers.
5188 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005189 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005190
Dianne Hackborne4a59512010-12-07 11:08:07 -08005191 // If we are in service, make sure the correct signal string timer is running.
5192 } else if (state == ServiceState.STATE_IN_SERVICE) {
5193 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005194
5195 // If we're out of service, we are in the lowest signal strength
5196 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005197 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005198 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005199 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005200 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005201 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005202 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005203 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5204 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005205 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005206 }
5207 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005208
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005209 if (!scanning) {
5210 // If we are no longer scanning, then stop the scanning timer.
5211 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5212 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5213 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5214 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005215 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005216 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005217 }
5218 }
5219
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005220 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005221 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5222 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005223 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005224 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005225 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005226 mPhoneServiceState = state;
5227 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005228
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005229 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005230 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005231 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005232 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005233 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005234 if (strengthBin >= 0) {
5235 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005236 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005237 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005238 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5239 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005240 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005241 + Integer.toHexString(mHistoryCur.states));
5242 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005243 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005244 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005245 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005246 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005247 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005248 }
5249
5250 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005251 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005252 }
5253 }
5254
5255 /**
5256 * Telephony stack updates the phone state.
5257 * @param state phone state from ServiceState.getState()
5258 */
5259 public void notePhoneStateLocked(int state, int simState) {
5260 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005261 }
5262
Wink Savillee9b06d72009-05-18 21:47:50 -07005263 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005264 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005265 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005266 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005267 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005268
Dianne Hackborn627bba72009-03-24 22:32:56 -07005269 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
5270 int bin = DATA_CONNECTION_NONE;
5271 if (hasData) {
5272 switch (dataType) {
5273 case TelephonyManager.NETWORK_TYPE_EDGE:
5274 bin = DATA_CONNECTION_EDGE;
5275 break;
5276 case TelephonyManager.NETWORK_TYPE_GPRS:
5277 bin = DATA_CONNECTION_GPRS;
5278 break;
5279 case TelephonyManager.NETWORK_TYPE_UMTS:
5280 bin = DATA_CONNECTION_UMTS;
5281 break;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005282 case TelephonyManager.NETWORK_TYPE_CDMA:
5283 bin = DATA_CONNECTION_CDMA;
5284 break;
5285 case TelephonyManager.NETWORK_TYPE_EVDO_0:
5286 bin = DATA_CONNECTION_EVDO_0;
5287 break;
5288 case TelephonyManager.NETWORK_TYPE_EVDO_A:
5289 bin = DATA_CONNECTION_EVDO_A;
5290 break;
5291 case TelephonyManager.NETWORK_TYPE_1xRTT:
5292 bin = DATA_CONNECTION_1xRTT;
5293 break;
5294 case TelephonyManager.NETWORK_TYPE_HSDPA:
5295 bin = DATA_CONNECTION_HSDPA;
5296 break;
5297 case TelephonyManager.NETWORK_TYPE_HSUPA:
5298 bin = DATA_CONNECTION_HSUPA;
5299 break;
5300 case TelephonyManager.NETWORK_TYPE_HSPA:
5301 bin = DATA_CONNECTION_HSPA;
5302 break;
5303 case TelephonyManager.NETWORK_TYPE_IDEN:
5304 bin = DATA_CONNECTION_IDEN;
5305 break;
5306 case TelephonyManager.NETWORK_TYPE_EVDO_B:
5307 bin = DATA_CONNECTION_EVDO_B;
5308 break;
Robert Greenwalt962a9902010-11-02 11:10:25 -07005309 case TelephonyManager.NETWORK_TYPE_LTE:
5310 bin = DATA_CONNECTION_LTE;
5311 break;
5312 case TelephonyManager.NETWORK_TYPE_EHRPD:
5313 bin = DATA_CONNECTION_EHRPD;
5314 break;
Patrick Tjinb71703c2013-11-06 09:27:03 -08005315 case TelephonyManager.NETWORK_TYPE_HSPAP:
5316 bin = DATA_CONNECTION_HSPAP;
5317 break;
Siddharth Rayc72081d2018-02-13 11:31:54 -08005318 case TelephonyManager.NETWORK_TYPE_GSM:
5319 bin = DATA_CONNECTION_GSM;
5320 break;
5321 case TelephonyManager.NETWORK_TYPE_TD_SCDMA:
5322 bin = DATA_CONNECTION_TD_SCDMA;
5323 break;
5324 case TelephonyManager.NETWORK_TYPE_IWLAN:
5325 bin = DATA_CONNECTION_IWLAN;
5326 break;
5327 case TelephonyManager.NETWORK_TYPE_LTE_CA:
5328 bin = DATA_CONNECTION_LTE_CA;
5329 break;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005330 default:
5331 bin = DATA_CONNECTION_OTHER;
5332 break;
5333 }
5334 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005335 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005336 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005337 final long elapsedRealtime = mClocks.elapsedRealtime();
5338 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005339 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5340 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005341 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5342 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005343 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005344 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005345 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005346 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005347 }
5348 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005349 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005350 }
5351 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005352
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005353 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005354 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005355 final long elapsedRealtime = mClocks.elapsedRealtime();
5356 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005357 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005358 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5359 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005360 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005361 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005362 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005363 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005364 }
5365 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005366
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005367 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005368 final long elapsedRealtime = mClocks.elapsedRealtime();
5369 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005370 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005371 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005372 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5373 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005374 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005375 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005376 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005377 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005378 }
5379 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005380
5381 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005382 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005383 final long elapsedRealtime = mClocks.elapsedRealtime();
5384 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005385 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005386 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005387 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5388 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005389 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005390 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005391 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005392 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005393 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005394 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005395
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005396 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005397 if (mAudioOnNesting == 0) {
5398 return;
5399 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005400 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005401 final long elapsedRealtime = mClocks.elapsedRealtime();
5402 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005403 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005404 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005405 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5406 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005407 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005408 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005409 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005410 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005411 }
5412
5413 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005414 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005415 final long elapsedRealtime = mClocks.elapsedRealtime();
5416 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005417 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005418 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005419 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5420 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005421 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005422 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005423 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005424 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005425 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005426 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005427
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005428 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005429 if (mVideoOnNesting == 0) {
5430 return;
5431 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005432 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005433 final long elapsedRealtime = mClocks.elapsedRealtime();
5434 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005435 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005436 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005437 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5438 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005439 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005440 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005441 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005442 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005443 }
5444
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005445 public void noteResetAudioLocked() {
5446 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005447 final long elapsedRealtime = mClocks.elapsedRealtime();
5448 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005449 mAudioOnNesting = 0;
5450 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5451 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5452 + Integer.toHexString(mHistoryCur.states));
5453 addHistoryRecordLocked(elapsedRealtime, uptime);
5454 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5455 for (int i=0; i<mUidStats.size(); i++) {
5456 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5457 uid.noteResetAudioLocked(elapsedRealtime);
5458 }
5459 }
5460 }
5461
5462 public void noteResetVideoLocked() {
5463 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005464 final long elapsedRealtime = mClocks.elapsedRealtime();
5465 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005466 mAudioOnNesting = 0;
5467 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5468 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5469 + Integer.toHexString(mHistoryCur.states));
5470 addHistoryRecordLocked(elapsedRealtime, uptime);
5471 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5472 for (int i=0; i<mUidStats.size(); i++) {
5473 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5474 uid.noteResetVideoLocked(elapsedRealtime);
5475 }
5476 }
5477 }
5478
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005479 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005480 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005481 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005482 }
5483
5484 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005485 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005486 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005487 }
5488
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005489 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005490 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005491 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5492 }
5493
5494 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005495 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005496 getUidStatsLocked(uid).noteVibratorOffLocked();
5497 }
5498
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005499 public void noteFlashlightOnLocked(int uid) {
5500 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005501 final long elapsedRealtime = mClocks.elapsedRealtime();
5502 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005503 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005504 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5505 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005506 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005507 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005508 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5509 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005510 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5511 }
5512
5513 public void noteFlashlightOffLocked(int uid) {
5514 if (mFlashlightOnNesting == 0) {
5515 return;
5516 }
5517 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005518 final long elapsedRealtime = mClocks.elapsedRealtime();
5519 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005520 if (--mFlashlightOnNesting == 0) {
5521 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5522 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5523 + Integer.toHexString(mHistoryCur.states2));
5524 addHistoryRecordLocked(elapsedRealtime, uptime);
5525 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5526 }
5527 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5528 }
5529
5530 public void noteCameraOnLocked(int uid) {
5531 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005532 final long elapsedRealtime = mClocks.elapsedRealtime();
5533 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005534 if (mCameraOnNesting++ == 0) {
5535 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5536 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5537 + Integer.toHexString(mHistoryCur.states2));
5538 addHistoryRecordLocked(elapsedRealtime, uptime);
5539 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5540 }
5541 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5542 }
5543
5544 public void noteCameraOffLocked(int uid) {
5545 if (mCameraOnNesting == 0) {
5546 return;
5547 }
5548 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005549 final long elapsedRealtime = mClocks.elapsedRealtime();
5550 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005551 if (--mCameraOnNesting == 0) {
5552 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5553 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5554 + Integer.toHexString(mHistoryCur.states2));
5555 addHistoryRecordLocked(elapsedRealtime, uptime);
5556 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5557 }
5558 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5559 }
5560
5561 public void noteResetCameraLocked() {
5562 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005563 final long elapsedRealtime = mClocks.elapsedRealtime();
5564 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005565 mCameraOnNesting = 0;
5566 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5567 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5568 + Integer.toHexString(mHistoryCur.states2));
5569 addHistoryRecordLocked(elapsedRealtime, uptime);
5570 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5571 for (int i=0; i<mUidStats.size(); i++) {
5572 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5573 uid.noteResetCameraLocked(elapsedRealtime);
5574 }
5575 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005576 }
5577
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005578 public void noteResetFlashlightLocked() {
5579 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005580 final long elapsedRealtime = mClocks.elapsedRealtime();
5581 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005582 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005583 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5584 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005585 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005586 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005587 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5588 for (int i=0; i<mUidStats.size(); i++) {
5589 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5590 uid.noteResetFlashlightLocked(elapsedRealtime);
5591 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005592 }
5593 }
5594
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005595 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5596 boolean isUnoptimized) {
5597 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005598 final long elapsedRealtime = mClocks.elapsedRealtime();
5599 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005600 if (mBluetoothScanNesting == 0) {
5601 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5602 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5603 + Integer.toHexString(mHistoryCur.states2));
5604 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005605 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005606 }
5607 mBluetoothScanNesting++;
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005608
Yangster-macafad8c62018-01-05 22:30:49 -08005609 if (workChain != null) {
5610 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005611 workChain.getUids(), workChain.getTags(),
5612 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005613 if (isUnoptimized) {
5614 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005615 workChain.getUids(), workChain.getTags(),
5616 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005617 }
5618 } else {
Bookatz90867622018-01-31 15:05:57 -08005619 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null,
5620 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005621 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005622 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08005623 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__ON);
Yangster-macafad8c62018-01-05 22:30:49 -08005624 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005625 }
5626
Bookatzb1f04f32017-05-19 13:57:32 -07005627 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005628 if (workChain != null) {
5629 getUidStatsLocked(uid).addBluetoothWorkChain(workChain, isUnoptimized);
5630 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005631 }
5632
Bookatzb1f04f32017-05-19 13:57:32 -07005633 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005634 final int N = ws.size();
5635 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005636 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5637 }
5638
5639 final List<WorkChain> workChains = ws.getWorkChains();
5640 if (workChains != null) {
5641 for (int i = 0; i < workChains.size(); ++i) {
5642 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5643 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005644 }
5645 }
5646
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005647 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5648 boolean isUnoptimized) {
5649 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005650 final long elapsedRealtime = mClocks.elapsedRealtime();
5651 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005652 mBluetoothScanNesting--;
5653 if (mBluetoothScanNesting == 0) {
5654 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5655 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5656 + Integer.toHexString(mHistoryCur.states2));
5657 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005658 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005659 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005660
Yangster-macafad8c62018-01-05 22:30:49 -08005661 if (workChain != null) {
5662 StatsLog.write(
Bookatz90867622018-01-31 15:05:57 -08005663 StatsLog.BLE_SCAN_STATE_CHANGED, workChain.getUids(), workChain.getTags(),
5664 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005665 if (isUnoptimized) {
5666 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08005667 workChain.getUids(), workChain.getTags(),
5668 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005669 }
5670 } else {
Bookatz90867622018-01-31 15:05:57 -08005671 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null,
5672 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005673 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005674 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
Bookatz90867622018-01-31 15:05:57 -08005675 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Yangster-macafad8c62018-01-05 22:30:49 -08005676 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005677 }
5678
Bookatz94c5a312017-07-11 16:49:17 -07005679 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005680 if (workChain != null) {
5681 getUidStatsLocked(uid).removeBluetoothWorkChain(workChain, isUnoptimized);
5682 }
5683 }
5684
5685 private int getAttributionUid(int uid, WorkChain workChain) {
5686 if (workChain != null) {
5687 return mapUid(workChain.getAttributionUid());
5688 }
5689
5690 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005691 }
5692
Bookatz94c5a312017-07-11 16:49:17 -07005693 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005694 final int N = ws.size();
5695 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005696 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5697 }
5698
5699 final List<WorkChain> workChains = ws.getWorkChains();
5700 if (workChains != null) {
5701 for (int i = 0; i < workChains.size(); ++i) {
5702 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5703 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005704 }
5705 }
5706
5707 public void noteResetBluetoothScanLocked() {
5708 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005709 final long elapsedRealtime = mClocks.elapsedRealtime();
5710 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005711 mBluetoothScanNesting = 0;
5712 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5713 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5714 + Integer.toHexString(mHistoryCur.states2));
5715 addHistoryRecordLocked(elapsedRealtime, uptime);
5716 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005717
5718
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005719 for (int i=0; i<mUidStats.size(); i++) {
5720 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5721 uid.noteResetBluetoothScanLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005722
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005723 List<WorkChain> allWorkChains = uid.getAllBluetoothWorkChains();
5724 if (allWorkChains != null) {
5725 for (int j = 0; j < allWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005726 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005727 allWorkChains.get(j).getUids(),
Bookatz90867622018-01-31 15:05:57 -08005728 allWorkChains.get(j).getTags(),
5729 StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005730 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005731 allWorkChains.clear();
5732 }
5733
5734 List<WorkChain> unoptimizedWorkChains = uid.getUnoptimizedBluetoothWorkChains();
5735 if (unoptimizedWorkChains != null) {
5736 for (int j = 0; j < unoptimizedWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005737 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005738 unoptimizedWorkChains.get(j).getUids(),
Bookatz90867622018-01-31 15:05:57 -08005739 unoptimizedWorkChains.get(j).getTags(),
5740 StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005741 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005742 unoptimizedWorkChains.clear();
5743 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005744 }
5745 }
5746 }
5747
Bookatz4ebc0642017-05-11 12:21:19 -07005748 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005749 final int N = ws.size();
5750 for (int i = 0; i < N; i++) {
5751 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005752 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005753 StatsLog.write_non_chained(StatsLog.BLE_SCAN_RESULT_RECEIVED, ws.get(i), ws.getName(i),
5754 numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005755 }
5756
5757 final List<WorkChain> workChains = ws.getWorkChains();
5758 if (workChains != null) {
5759 for (int i = 0; i < workChains.size(); ++i) {
5760 final WorkChain wc = workChains.get(i);
5761 int uid = mapUid(wc.getAttributionUid());
5762 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-macafad8c62018-01-05 22:30:49 -08005763 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED,
5764 wc.getUids(), wc.getTags(), numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005765 }
Bookatz956f36bf2017-04-28 09:48:17 -07005766 }
5767 }
5768
Adam Lesinski5f056f62016-07-14 16:56:08 -07005769 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5770 final long uptimeMillis, int uid) {
5771 uid = mapUid(uid);
5772 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5773 uid);
5774 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5775 }
5776
5777 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005778 final long elapsedRealtime = mClocks.elapsedRealtime();
5779 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005780 if (mWifiRadioPowerState != powerState) {
5781 final boolean active =
5782 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5783 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5784 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005785 if (uid > 0) {
5786 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5787 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005788 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005789 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005790 } else {
5791 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005792 mWifiActiveTimer.stopRunningLocked(
5793 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005794 }
5795 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5796 + Integer.toHexString(mHistoryCur.states));
5797 addHistoryRecordLocked(elapsedRealtime, uptime);
5798 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005799 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005800 }
5801 }
5802
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005803 public void noteWifiRunningLocked(WorkSource ws) {
5804 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005805 final long elapsedRealtime = mClocks.elapsedRealtime();
5806 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005807 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005808 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5809 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005810 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005811 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005812 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005813 int N = ws.size();
5814 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005815 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005816 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005817 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005818
5819 List<WorkChain> workChains = ws.getWorkChains();
5820 if (workChains != null) {
5821 for (int i = 0; i < workChains.size(); ++i) {
5822 int uid = mapUid(workChains.get(i).getAttributionUid());
5823 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5824 }
5825 }
5826
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005827 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005828 } else {
5829 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005830 }
5831 }
5832
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005833 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5834 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005835 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005836 int N = oldWs.size();
5837 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005838 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005839 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005840 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005841
5842 List<WorkChain> workChains = oldWs.getWorkChains();
5843 if (workChains != null) {
5844 for (int i = 0; i < workChains.size(); ++i) {
5845 int uid = mapUid(workChains.get(i).getAttributionUid());
5846 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5847 }
5848 }
5849
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005850 N = newWs.size();
5851 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005852 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005853 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005854 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005855
5856 workChains = newWs.getWorkChains();
5857 if (workChains != null) {
5858 for (int i = 0; i < workChains.size(); ++i) {
5859 int uid = mapUid(workChains.get(i).getAttributionUid());
5860 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5861 }
5862 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005863 } else {
5864 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5865 }
5866 }
5867
5868 public void noteWifiStoppedLocked(WorkSource ws) {
5869 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005870 final long elapsedRealtime = mClocks.elapsedRealtime();
5871 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005872 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005873 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5874 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005875 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005876 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005877 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005878 int N = ws.size();
5879 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005880 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005881 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005882 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005883
5884 List<WorkChain> workChains = ws.getWorkChains();
5885 if (workChains != null) {
5886 for (int i = 0; i < workChains.size(); ++i) {
5887 int uid = mapUid(workChains.get(i).getAttributionUid());
5888 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5889 }
5890 }
5891
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005892 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005893 } else {
5894 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005895 }
5896 }
5897
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005898 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5899 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5900 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005901 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005902 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005903 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005904 }
5905 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005906 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005907 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005908 }
5909 }
5910
Dianne Hackborn3251b902014-06-20 14:40:53 -07005911 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5912 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5913 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005914 final long elapsedRealtime = mClocks.elapsedRealtime();
5915 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005916 if (mWifiSupplState >= 0) {
5917 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5918 }
5919 mWifiSupplState = supplState;
5920 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5921 mHistoryCur.states2 =
5922 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5923 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5924 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5925 + Integer.toHexString(mHistoryCur.states2));
5926 addHistoryRecordLocked(elapsedRealtime, uptime);
5927 }
5928 }
5929
5930 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005931 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005932 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5933 if (i == except) {
5934 continue;
5935 }
5936 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5937 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5938 }
5939 }
5940 }
5941
5942 public void noteWifiRssiChangedLocked(int newRssi) {
5943 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5944 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5945 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005946 final long elapsedRealtime = mClocks.elapsedRealtime();
5947 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005948 if (mWifiSignalStrengthBin >= 0) {
5949 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5950 elapsedRealtime);
5951 }
5952 if (strengthBin >= 0) {
5953 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5954 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Bookatze5885242017-10-24 20:10:31 -07005955 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07005956 }
5957 mHistoryCur.states2 =
5958 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5959 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5960 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5961 + Integer.toHexString(mHistoryCur.states2));
5962 addHistoryRecordLocked(elapsedRealtime, uptime);
5963 } else {
5964 stopAllWifiSignalStrengthTimersLocked(-1);
5965 }
5966 mWifiSignalStrengthBin = strengthBin;
5967 }
5968 }
5969
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005970 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005971
The Android Open Source Project10592532009-03-18 17:39:46 -07005972 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005973 final long elapsedRealtime = mClocks.elapsedRealtime();
5974 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005975 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005976 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005977 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5978 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005979 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005980 }
5981 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005982 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005983 }
5984
5985 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005986 final long elapsedRealtime = mClocks.elapsedRealtime();
5987 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005988 mWifiFullLockNesting--;
5989 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005990 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005991 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
5992 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005993 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005994 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005995 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005996 }
5997
Nick Pelly6ccaa542012-06-15 15:22:47 -07005998 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005999
Nick Pelly6ccaa542012-06-15 15:22:47 -07006000 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006001 final long elapsedRealtime = mClocks.elapsedRealtime();
6002 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006003 if (mWifiScanNesting == 0) {
6004 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
6005 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006006 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006007 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006008 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006009 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006010 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006011 }
6012
Nick Pelly6ccaa542012-06-15 15:22:47 -07006013 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006014 final long elapsedRealtime = mClocks.elapsedRealtime();
6015 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07006016 mWifiScanNesting--;
6017 if (mWifiScanNesting == 0) {
6018 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
6019 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006020 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006021 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006022 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006023 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07006024 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006025
Robert Greenwalta029ea12013-09-25 16:38:12 -07006026 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006027 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006028 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006029 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006030 }
6031
6032 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006033 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006034 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006035 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006036 }
6037
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006038 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006039
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006040 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006041 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006042 final long elapsedRealtime = mClocks.elapsedRealtime();
6043 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006044 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006045 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006046 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
6047 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006048 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006049
6050 // Start Wifi Multicast overall timer
6051 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
6052 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
6053 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
6054 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006055 }
6056 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006057 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006058 }
6059
6060 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08006061 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08006062 final long elapsedRealtime = mClocks.elapsedRealtime();
6063 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006064 mWifiMulticastNesting--;
6065 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006066 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006067 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
6068 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07006069 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006070
6071 // Stop Wifi Multicast overall timer
6072 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
6073 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
6074 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
6075 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006076 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006077 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006078 }
6079
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006080 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
6081 int N = ws.size();
6082 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006083 final int uid = mapUid(ws.get(i));
6084 noteFullWifiLockAcquiredLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006085 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6086 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006087 }
6088
6089 final List<WorkChain> workChains = ws.getWorkChains();
6090 if (workChains != null) {
6091 for (int i = 0; i < workChains.size(); ++i) {
6092 final WorkChain workChain = workChains.get(i);
6093 final int uid = mapUid(workChain.getAttributionUid());
6094 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006095 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006096 workChain.getUids(), workChain.getTags(),
6097 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006098 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006099 }
6100 }
6101
6102 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
6103 int N = ws.size();
6104 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006105 final int uid = mapUid(ws.get(i));
6106 noteFullWifiLockReleasedLocked(uid);
Bookatz90867622018-01-31 15:05:57 -08006107 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
6108 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006109 }
6110
6111 final List<WorkChain> workChains = ws.getWorkChains();
6112 if (workChains != null) {
6113 for (int i = 0; i < workChains.size(); ++i) {
6114 final WorkChain workChain = workChains.get(i);
6115 final int uid = mapUid(workChain.getAttributionUid());
6116 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006117 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006118 workChain.getUids(), workChain.getTags(),
6119 StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006120 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006121 }
6122 }
6123
Nick Pelly6ccaa542012-06-15 15:22:47 -07006124 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006125 int N = ws.size();
6126 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006127 final int uid = mapUid(ws.get(i));
6128 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006129 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006130 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006131 }
6132
6133 final List<WorkChain> workChains = ws.getWorkChains();
6134 if (workChains != null) {
6135 for (int i = 0; i < workChains.size(); ++i) {
6136 final WorkChain workChain = workChains.get(i);
6137 final int uid = mapUid(workChain.getAttributionUid());
6138 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006139 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
Bookatz90867622018-01-31 15:05:57 -08006140 workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006141 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006142 }
6143 }
6144
Nick Pelly6ccaa542012-06-15 15:22:47 -07006145 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006146 int N = ws.size();
6147 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006148 final int uid = mapUid(ws.get(i));
6149 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006150 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
Bookatz90867622018-01-31 15:05:57 -08006151 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006152 }
6153
6154 final List<WorkChain> workChains = ws.getWorkChains();
6155 if (workChains != null) {
6156 for (int i = 0; i < workChains.size(); ++i) {
6157 final WorkChain workChain = workChains.get(i);
6158 final int uid = mapUid(workChain.getAttributionUid());
6159 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006160 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
Bookatz90867622018-01-31 15:05:57 -08006161 workChain.getUids(), workChain.getTags(),
6162 StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006163 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006164 }
6165 }
6166
Robert Greenwalta029ea12013-09-25 16:38:12 -07006167 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6168 int N = ws.size();
6169 for (int i=0; i<N; i++) {
6170 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6171 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006172
6173 final List<WorkChain> workChains = ws.getWorkChains();
6174 if (workChains != null) {
6175 for (int i = 0; i < workChains.size(); ++i) {
6176 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6177 }
6178 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006179 }
6180
6181 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6182 int N = ws.size();
6183 for (int i=0; i<N; i++) {
6184 noteWifiBatchedScanStoppedLocked(ws.get(i));
6185 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006186
6187 final List<WorkChain> workChains = ws.getWorkChains();
6188 if (workChains != null) {
6189 for (int i = 0; i < workChains.size(); ++i) {
6190 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6191 }
6192 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006193 }
6194
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006195 private static String[] includeInStringArray(String[] array, String str) {
6196 if (ArrayUtils.indexOf(array, str) >= 0) {
6197 return array;
6198 }
6199 String[] newArray = new String[array.length+1];
6200 System.arraycopy(array, 0, newArray, 0, array.length);
6201 newArray[array.length] = str;
6202 return newArray;
6203 }
6204
6205 private static String[] excludeFromStringArray(String[] array, String str) {
6206 int index = ArrayUtils.indexOf(array, str);
6207 if (index >= 0) {
6208 String[] newArray = new String[array.length-1];
6209 if (index > 0) {
6210 System.arraycopy(array, 0, newArray, 0, index);
6211 }
6212 if (index < array.length-1) {
6213 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6214 }
6215 return newArray;
6216 }
6217 return array;
6218 }
6219
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006220 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006221 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006222
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006223 synchronized (mModemNetworkLock) {
6224 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6225 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6226 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6227 } else {
6228 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6229 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6230 }
6231 }
6232
6233 synchronized (mWifiNetworkLock) {
6234 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6235 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6236 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6237 } else {
6238 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6239 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6240 }
6241 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006242 }
6243
David Chenc8a43242017-10-17 16:23:28 -07006244 public String[] getWifiIfaces() {
6245 synchronized (mWifiNetworkLock) {
6246 return mWifiIfaces;
6247 }
6248 }
6249
6250 public String[] getMobileIfaces() {
6251 synchronized (mModemNetworkLock) {
6252 return mModemIfaces;
6253 }
6254 }
6255
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006256 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6257 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006259
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006260 @Override public int getScreenOnCount(int which) {
6261 return mScreenOnTimer.getCountLocked(which);
6262 }
6263
Mike Mac2f518a2017-09-19 16:06:03 -07006264 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6265 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6266 }
6267
6268 @Override public int getScreenDozeCount(int which) {
6269 return mScreenDozeTimer.getCountLocked(which);
6270 }
6271
Dianne Hackborn617f8772009-03-31 15:04:46 -07006272 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006273 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006274 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006275 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006276 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006277
Kweku Adams87b19ec2017-10-09 12:40:03 -07006278 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6279 return mScreenBrightnessTimer[brightnessBin];
6280 }
6281
Jeff Browne95c3cd2014-05-02 16:59:26 -07006282 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6283 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006284 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006285
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006286 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6287 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006288 }
6289
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006290 @Override public int getPowerSaveModeEnabledCount(int which) {
6291 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6292 }
6293
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006294 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6295 int which) {
6296 switch (mode) {
6297 case DEVICE_IDLE_MODE_LIGHT:
6298 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006299 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006300 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6301 }
6302 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006303 }
6304
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006305 @Override public int getDeviceIdleModeCount(int mode, int which) {
6306 switch (mode) {
6307 case DEVICE_IDLE_MODE_LIGHT:
6308 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006309 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006310 return mDeviceIdleModeFullTimer.getCountLocked(which);
6311 }
6312 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006313 }
6314
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006315 @Override public long getLongestDeviceIdleModeTime(int mode) {
6316 switch (mode) {
6317 case DEVICE_IDLE_MODE_LIGHT:
6318 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006319 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006320 return mLongestFullIdleTime;
6321 }
6322 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006323 }
6324
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006325 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6326 switch (mode) {
6327 case DEVICE_IDLE_MODE_LIGHT:
6328 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006329 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006330 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6331 }
6332 return 0;
6333 }
6334
6335 @Override public int getDeviceIdlingCount(int mode, int which) {
6336 switch (mode) {
6337 case DEVICE_IDLE_MODE_LIGHT:
6338 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006339 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006340 return mDeviceIdlingTimer.getCountLocked(which);
6341 }
6342 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006343 }
6344
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006345 @Override public int getNumConnectivityChange(int which) {
6346 int val = mNumConnectivityChange;
6347 if (which == STATS_CURRENT) {
6348 val -= mLoadedNumConnectivityChange;
6349 } else if (which == STATS_SINCE_UNPLUGGED) {
6350 val -= mUnpluggedNumConnectivityChange;
6351 }
6352 return val;
6353 }
6354
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006355 @Override public long getGpsSignalQualityTime(int strengthBin,
6356 long elapsedRealtimeUs, int which) {
6357 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6358 return 0;
6359 }
6360 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6361 elapsedRealtimeUs, which);
6362 }
6363
6364 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006365 final double opVolt = mPowerProfile.getAveragePower(
6366 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6367 if (opVolt == 0) {
6368 return 0;
6369 }
6370 double energyUsedMaMs = 0.0;
6371 final int which = STATS_SINCE_CHARGED;
6372 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6373 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6374 energyUsedMaMs
6375 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6376 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6377 }
6378 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006379 }
6380
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006381 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6382 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006384
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006385 @Override public int getPhoneOnCount(int which) {
6386 return mPhoneOnTimer.getCountLocked(which);
6387 }
6388
Dianne Hackborn627bba72009-03-24 22:32:56 -07006389 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006390 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006391 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006392 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006393 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006394
6395 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006396 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006397 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006398 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006399 }
6400
Kweku Adams87b19ec2017-10-09 12:40:03 -07006401 @Override public Timer getPhoneSignalScanningTimer() {
6402 return mPhoneSignalScanningTimer;
6403 }
6404
Catherine Liufb900812012-07-17 14:12:56 -05006405 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6406 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006407 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006408
Kweku Adams87b19ec2017-10-09 12:40:03 -07006409 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6410 return mPhoneSignalStrengthsTimer[strengthBin];
6411 }
6412
Dianne Hackborn627bba72009-03-24 22:32:56 -07006413 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006414 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006415 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006416 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006417 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006418
Dianne Hackborn617f8772009-03-31 15:04:46 -07006419 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006420 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006421 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006422
Kweku Adams87b19ec2017-10-09 12:40:03 -07006423 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6424 return mPhoneDataConnectionsTimer[dataType];
6425 }
6426
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006427 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6428 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006429 }
6430
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006431 @Override public int getMobileRadioActiveCount(int which) {
6432 return mMobileRadioActiveTimer.getCountLocked(which);
6433 }
6434
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006435 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6436 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6437 }
6438
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006439 @Override public long getMobileRadioActiveUnknownTime(int which) {
6440 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6441 }
6442
6443 @Override public int getMobileRadioActiveUnknownCount(int which) {
6444 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6445 }
6446
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006447 @Override public long getWifiMulticastWakelockTime(
6448 long elapsedRealtimeUs, int which) {
6449 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6450 elapsedRealtimeUs, which);
6451 }
6452
6453 @Override public int getWifiMulticastWakelockCount(int which) {
6454 return mWifiMulticastWakelockTimer.getCountLocked(which);
6455 }
6456
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006457 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6458 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006459 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006460
Siddharth Rayb50a6842017-12-14 15:15:28 -08006461 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6462 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6463 }
6464
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006465 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6466 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006467 }
6468
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006469 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006470 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006471 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006472 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006473 }
6474
6475 @Override public int getWifiStateCount(int wifiState, int which) {
6476 return mWifiStateTimer[wifiState].getCountLocked(which);
6477 }
6478
Kweku Adams87b19ec2017-10-09 12:40:03 -07006479 @Override public Timer getWifiStateTimer(int wifiState) {
6480 return mWifiStateTimer[wifiState];
6481 }
6482
Dianne Hackborn3251b902014-06-20 14:40:53 -07006483 @Override public long getWifiSupplStateTime(int state,
6484 long elapsedRealtimeUs, int which) {
6485 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6486 elapsedRealtimeUs, which);
6487 }
6488
6489 @Override public int getWifiSupplStateCount(int state, int which) {
6490 return mWifiSupplStateTimer[state].getCountLocked(which);
6491 }
6492
Kweku Adams87b19ec2017-10-09 12:40:03 -07006493 @Override public Timer getWifiSupplStateTimer(int state) {
6494 return mWifiSupplStateTimer[state];
6495 }
6496
Dianne Hackborn3251b902014-06-20 14:40:53 -07006497 @Override public long getWifiSignalStrengthTime(int strengthBin,
6498 long elapsedRealtimeUs, int which) {
6499 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6500 elapsedRealtimeUs, which);
6501 }
6502
6503 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6504 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6505 }
6506
Kweku Adams87b19ec2017-10-09 12:40:03 -07006507 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6508 return mWifiSignalStrengthsTimer[strengthBin];
6509 }
6510
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006511 @Override
6512 public ControllerActivityCounter getBluetoothControllerActivity() {
6513 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006514 }
6515
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006516 @Override
6517 public ControllerActivityCounter getWifiControllerActivity() {
6518 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006519 }
6520
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006521 @Override
6522 public ControllerActivityCounter getModemControllerActivity() {
6523 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006524 }
6525
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006526 @Override
6527 public boolean hasBluetoothActivityReporting() {
6528 return mHasBluetoothReporting;
6529 }
6530
6531 @Override
6532 public boolean hasWifiActivityReporting() {
6533 return mHasWifiReporting;
6534 }
6535
6536 @Override
6537 public boolean hasModemActivityReporting() {
6538 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006539 }
6540
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006541 @Override
6542 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006543 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6544 }
6545
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006546 @Override
6547 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006548 return mFlashlightOnTimer.getCountLocked(which);
6549 }
6550
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006551 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006552 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6553 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6554 }
6555
6556 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006557 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6558 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6559 }
6560
6561 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006562 public long getNetworkActivityBytes(int type, int which) {
6563 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6564 return mNetworkByteActivityCounters[type].getCountLocked(which);
6565 } else {
6566 return 0;
6567 }
6568 }
6569
6570 @Override
6571 public long getNetworkActivityPackets(int type, int which) {
6572 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6573 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006574 } else {
6575 return 0;
6576 }
6577 }
6578
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006579 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006580 final long currentTime = System.currentTimeMillis();
6581 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006582 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6583 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006584 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006585 return mStartClockTime;
6586 }
6587
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006588 @Override public String getStartPlatformVersion() {
6589 return mStartPlatformVersion;
6590 }
6591
6592 @Override public String getEndPlatformVersion() {
6593 return mEndPlatformVersion;
6594 }
6595
6596 @Override public int getParcelVersion() {
6597 return VERSION;
6598 }
6599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006600 @Override public boolean getIsOnBattery() {
6601 return mOnBattery;
6602 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6605 return mUidStats;
6606 }
6607
Adam Lesinski5f056f62016-07-14 16:56:08 -07006608 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6609 if (timer != null) {
6610 timer.detach();
6611 }
6612 }
6613
6614 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6615 boolean detachIfReset) {
6616 if (timer != null) {
6617 return timer.reset(detachIfReset);
6618 }
6619 return true;
6620 }
6621
Bookatz867c0d72017-03-07 18:23:42 -08006622 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6623 if (timer != null) {
6624 return timer.reset(detachIfReset);
6625 }
6626 return true;
6627 }
6628
Adam Lesinski5f056f62016-07-14 16:56:08 -07006629 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6630 if (counter != null) {
6631 counter.detach();
6632 }
6633 }
6634
6635 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6636 boolean detachIfReset) {
6637 if (counter != null) {
6638 counter.reset(detachIfReset);
6639 }
6640 }
6641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 /**
6643 * The statistics associated with a particular uid.
6644 */
Joe Onoratoabded112016-02-08 16:49:39 -08006645 public static class Uid extends BatteryStats.Uid {
6646 /**
6647 * BatteryStatsImpl that we are associated with.
6648 */
6649 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006651 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006652
Bookatz867c0d72017-03-07 18:23:42 -08006653 /** TimeBase for when uid is in background and device is on battery. */
6654 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6655 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006656 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6657 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006658
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006659 boolean mWifiRunning;
6660 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006661
The Android Open Source Project10592532009-03-18 17:39:46 -07006662 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006663 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006664
Nick Pelly6ccaa542012-06-15 15:22:47 -07006665 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006666 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006667
Dianne Hackborn61659e52014-07-09 16:13:01 -07006668 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006669 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6670 StopwatchTimer[] mWifiBatchedScanTimer;
6671
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006672 boolean mWifiMulticastEnabled;
6673 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006674
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006675 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006676 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006677 StopwatchTimer mFlashlightTurnedOnTimer;
6678 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006679 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006680 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006681 /** Total time spent by the uid holding any partial wakelocks. */
6682 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006683 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006684 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006685 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006686 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006687
Dianne Hackborna8d10942015-11-19 17:55:19 -08006688 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006689 StopwatchTimer[] mProcessStateTimer;
6690
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006691 boolean mInForegroundService = false;
6692
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006693 BatchTimer mVibratorOnTimer;
6694
Dianne Hackborn617f8772009-03-31 15:04:46 -07006695 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006696
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006697 LongSamplingCounter[] mNetworkByteActivityCounters;
6698 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006699 LongSamplingCounter mMobileRadioActiveTime;
6700 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006703 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6704 */
6705 private LongSamplingCounter mMobileRadioApWakeupCount;
6706
6707 /**
6708 * How many times this UID woke up the Application Processor due to a Wifi packet.
6709 */
6710 private LongSamplingCounter mWifiRadioApWakeupCount;
6711
6712 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006713 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006714 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006715 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006716 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006717
6718 /**
6719 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006720 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006721 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006722 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6723
6724 /**
6725 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6726 * Can be null if the UID has had no such activity.
6727 */
6728 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006729
6730 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006731 * The CPU times we had at the last history details update.
6732 */
6733 long mLastStepUserTime;
6734 long mLastStepSystemTime;
6735 long mCurStepUserTime;
6736 long mCurStepSystemTime;
6737
Joe Onoratoabded112016-02-08 16:49:39 -08006738 LongSamplingCounter mUserCpuTime;
6739 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006740 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006741 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006742
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006743 LongSamplingCounterArray mCpuFreqTimeMs;
6744 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006745 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006746
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006747 LongSamplingCounterArray[] mProcStateTimeMs;
6748 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6749
6750 IntArray mChildUids;
6751
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006752 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006753 * The statistics we have collected for this uid's wake locks.
6754 */
Joe Onoratoabded112016-02-08 16:49:39 -08006755 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006756
6757 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006758 * The statistics we have collected for this uid's syncs.
6759 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006760 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006761
6762 /**
6763 * The statistics we have collected for this uid's jobs.
6764 */
Bookatzaa4594a2017-03-24 12:39:56 -07006765 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006766
6767 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006768 * Count of the jobs that have completed and the reasons why they completed.
6769 */
6770 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6771
6772 /**
Amith Yamasani977e11f2018-02-16 11:29:54 -08006773 * Count of app launch events that had associated deferred job counts or info about
6774 * last time a job was run.
6775 */
6776 Counter mJobsDeferredEventCount;
6777
6778 /**
6779 * Count of deferred jobs that were pending when the app was launched or brought to
6780 * the foreground through a user interaction.
6781 */
6782 Counter mJobsDeferredCount;
6783
6784 /**
6785 * Sum of time since the last time a job was run for this app before it was launched.
6786 */
6787 LongSamplingCounter mJobsFreshnessTimeMs;
6788
6789 /**
6790 * Array of counts of instances where the time since the last job was run for the app
6791 * fell within one of the thresholds in {@link #JOB_FRESHNESS_BUCKETS}.
6792 */
6793 final Counter[] mJobsFreshnessBuckets;
6794
6795 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 * The statistics we have collected for this uid's sensor activations.
6797 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006798 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799
6800 /**
6801 * The statistics we have collected for this uid's processes.
6802 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006803 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006804
6805 /**
6806 * The statistics we have collected for this uid's processes.
6807 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006808 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006809
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006810 /**
6811 * The transient wake stats we have collected for this uid's pids.
6812 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006813 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006814
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00006815 /**
6816 * The list of WorkChains associated with active bluetooth scans.
6817 *
6818 * NOTE: This is a hack and it only needs to exist because there's a "reset" API that is
6819 * supposed to stop and log all WorkChains that were currently active.
6820 */
6821 ArrayList<WorkChain> mAllBluetoothChains = null;
6822 ArrayList<WorkChain> mUnoptimizedBluetoothChains = null;
6823
Joe Onoratoabded112016-02-08 16:49:39 -08006824 public Uid(BatteryStatsImpl bsi, int uid) {
6825 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006826 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006827
Bookatz867c0d72017-03-07 18:23:42 -08006828 mOnBatteryBackgroundTimeBase = new TimeBase();
6829 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6830 mBsi.mClocks.elapsedRealtime() * 1000);
6831
Bookatzc8c44962017-05-11 12:12:54 -07006832 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6833 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6834 mBsi.mClocks.elapsedRealtime() * 1000);
6835
Joe Onoratoabded112016-02-08 16:49:39 -08006836 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6837 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006838 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6839 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006840
Dianne Hackborn657153b2016-07-29 14:54:14 -07006841 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006842 @Override public Wakelock instantiateObject() {
6843 return new Wakelock(mBsi, Uid.this);
6844 }
6845 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006846 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6847 @Override public DualTimer instantiateObject() {
6848 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6849 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006850 }
6851 };
Bookatzaa4594a2017-03-24 12:39:56 -07006852 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6853 @Override public DualTimer instantiateObject() {
6854 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6855 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006856 }
6857 };
6858
6859 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6860 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6861 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6862 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006863 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6864 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006865 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006866 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6867 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006868 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
Amith Yamasani977e11f2018-02-16 11:29:54 -08006869 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase);
6870 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase);
6871 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6872 mJobsFreshnessBuckets = new Counter[JOB_FRESHNESS_BUCKETS.length];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006873 }
6874
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006875 @VisibleForTesting
6876 public void setProcessStateForTest(int procState) {
6877 mProcessState = procState;
6878 }
6879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006880 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006881 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006882 return nullIfAllZeros(mCpuFreqTimeMs, which);
6883 }
6884
6885 @Override
6886 public long[] getScreenOffCpuFreqTimes(int which) {
6887 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6888 }
6889
6890 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006891 public long getCpuActiveTime() {
6892 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6893 }
6894
6895 @Override
6896 public long[] getCpuClusterTimes() {
6897 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6898 }
6899
6900
6901 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006902 public long[] getCpuFreqTimes(int which, int procState) {
6903 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006904 return null;
6905 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006906 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006907 return null;
6908 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006909 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6910 mProcStateTimeMs = null;
6911 return null;
6912 }
6913 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6914 }
6915
6916 @Override
6917 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6918 if (which < 0 || which >= NUM_PROCESS_STATE) {
6919 return null;
6920 }
6921 if (mProcStateScreenOffTimeMs == null) {
6922 return null;
6923 }
6924 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6925 mProcStateScreenOffTimeMs = null;
6926 return null;
6927 }
6928 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6929 }
6930
6931 public void addIsolatedUid(int isolatedUid) {
6932 if (mChildUids == null) {
6933 mChildUids = new IntArray();
6934 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6935 return;
6936 }
6937 mChildUids.add(isolatedUid);
6938 }
6939
6940 public void removeIsolatedUid(int isolatedUid) {
6941 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6942 if (idx < 0) {
6943 return;
6944 }
6945 mChildUids.remove(idx);
6946 }
6947
6948 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6949 if (cpuTimesMs == null) {
6950 return null;
6951 }
6952 final long[] counts = cpuTimesMs.getCountsLocked(which);
6953 if (counts == null) {
6954 return null;
6955 }
6956 // Return counts only if at least one of the elements is non-zero.
6957 for (int i = counts.length - 1; i >= 0; --i) {
6958 if (counts[i] != 0) {
6959 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006960 }
6961 }
6962 return null;
6963 }
6964
Sudheer Shankae544d162017-12-28 17:06:20 -08006965 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006966 if (mProcStateTimeMs == null) {
6967 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006968 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006969 if (mProcStateTimeMs[procState] == null
6970 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
6971 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6972 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006973 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006974 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006975 }
6976
Sudheer Shankae544d162017-12-28 17:06:20 -08006977 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6978 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006979 if (mProcStateScreenOffTimeMs == null) {
6980 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006981 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006982 if (mProcStateScreenOffTimeMs[procState] == null
6983 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
6984 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
6985 mBsi.mOnBatteryScreenOffTimeBase);
6986 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006987 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006988 }
6989
6990 @Override
Bookatzc8c44962017-05-11 12:12:54 -07006991 public Timer getAggregatedPartialWakelockTimer() {
6992 return mAggregatedPartialWakelockTimer;
6993 }
6994
6995 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006996 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006997 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 }
6999
7000 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07007001 public Timer getMulticastWakelockStats() {
7002 return mWifiMulticastTimer;
7003 }
7004
7005 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007006 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007007 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007008 }
7009
7010 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007011 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007012 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007013 }
7014
7015 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007016 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
7017 return mJobCompletions;
7018 }
7019
7020 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07007021 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 return mSensorStats;
7023 }
7024
7025 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007026 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 return mProcessStats;
7028 }
7029
7030 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07007031 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007032 return mPackageStats;
7033 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007034
7035 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007036 public int getUid() {
7037 return mUid;
7038 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007039
7040 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007041 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007042 if (!mWifiRunning) {
7043 mWifiRunning = true;
7044 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007045 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7046 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007047 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007048 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007049 }
7050 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007051
Dianne Hackborn617f8772009-03-31 15:04:46 -07007052 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007053 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007054 if (mWifiRunning) {
7055 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007056 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007057 }
7058 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007059
Dianne Hackborn617f8772009-03-31 15:04:46 -07007060 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007061 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007062 if (!mFullWifiLockOut) {
7063 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007064 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007065 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7066 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007067 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007068 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007069 }
7070 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007071
The Android Open Source Project10592532009-03-18 17:39:46 -07007072 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007073 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07007074 if (mFullWifiLockOut) {
7075 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007076 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007077 }
7078 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007079
The Android Open Source Project10592532009-03-18 17:39:46 -07007080 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007081 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007082 if (!mWifiScanStarted) {
7083 mWifiScanStarted = true;
7084 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007085 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7086 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
7087 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007088 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007089 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007090 }
7091 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007092
The Android Open Source Project10592532009-03-18 17:39:46 -07007093 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007094 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007095 if (mWifiScanStarted) {
7096 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007097 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07007098 }
7099 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007100
7101 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007102 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007103 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07007104 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007105 csph = csph >> 3;
7106 bin++;
7107 }
7108
7109 if (mWifiBatchedScanBinStarted == bin) return;
7110
7111 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7112 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007113 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007114 }
7115 mWifiBatchedScanBinStarted = bin;
7116 if (mWifiBatchedScanTimer[bin] == null) {
7117 makeWifiBatchedScanBin(bin, null);
7118 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007119 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007120 }
7121
7122 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007123 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007124 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
7125 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007126 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007127 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7128 }
7129 }
7130
7131 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007132 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007133 if (!mWifiMulticastEnabled) {
7134 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007135 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007136 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7137 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007138 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007139 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007140 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007141 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7142 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007143 }
7144 }
7145
7146 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007147 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007148 if (mWifiMulticastEnabled) {
7149 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007150 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007151 StatsLog.write_non_chained(
Bookatz90867622018-01-31 15:05:57 -08007152 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
7153 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007154 }
7155 }
7156
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007157 @Override
7158 public ControllerActivityCounter getWifiControllerActivity() {
7159 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007160 }
7161
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007162 @Override
7163 public ControllerActivityCounter getBluetoothControllerActivity() {
7164 return mBluetoothControllerActivity;
7165 }
7166
7167 @Override
7168 public ControllerActivityCounter getModemControllerActivity() {
7169 return mModemControllerActivity;
7170 }
7171
7172 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7173 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007174 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007175 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007176 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007177 return mWifiControllerActivity;
7178 }
7179
7180 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7181 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007182 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007183 NUM_BT_TX_LEVELS);
7184 }
7185 return mBluetoothControllerActivity;
7186 }
7187
7188 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7189 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007190 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007191 ModemActivityInfo.TX_POWER_LEVELS);
7192 }
7193 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007194 }
7195
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007196 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7197 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007198 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7199 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007200 }
7201 return mAudioTurnedOnTimer;
7202 }
7203
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007204 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007205 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007206 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7207 StatsLog.AUDIO_STATE_CHANGED__STATE__ON);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007208 }
7209
7210 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7211 if (mAudioTurnedOnTimer != null) {
7212 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007213 if (!mAudioTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08007214 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7215 StatsLog.AUDIO_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007216 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007217 }
7218 }
7219
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007220 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7221 if (mAudioTurnedOnTimer != null) {
7222 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007223 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
7224 StatsLog.AUDIO_STATE_CHANGED__STATE__OFF);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007225 }
7226 }
7227
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007228 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7229 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007230 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7231 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007232 }
7233 return mVideoTurnedOnTimer;
7234 }
7235
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007236 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007237 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007238 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
7239 StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__ON);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007240 }
7241
7242 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7243 if (mVideoTurnedOnTimer != null) {
7244 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007245 if (!mVideoTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007246 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(),
Bookatz90867622018-01-31 15:05:57 -08007247 null, StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007248 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007249 }
7250 }
7251
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007252 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7253 if (mVideoTurnedOnTimer != null) {
7254 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007255 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08007256 StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__OFF);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007257 }
7258 }
7259
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007260 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7261 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007262 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7263 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007264 }
7265 return mFlashlightTurnedOnTimer;
7266 }
7267
7268 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7269 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007270 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7271 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__ON);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007272 }
7273
7274 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7275 if (mFlashlightTurnedOnTimer != null) {
7276 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007277 if (!mFlashlightTurnedOnTimer.isRunningLocked()) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08007278 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -08007279 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007280 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007281 }
7282 }
7283
7284 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7285 if (mFlashlightTurnedOnTimer != null) {
7286 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007287 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7288 StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__OFF);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007289 }
7290 }
7291
7292 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7293 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007294 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7295 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007296 }
7297 return mCameraTurnedOnTimer;
7298 }
7299
7300 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7301 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007302 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7303 StatsLog.CAMERA_STATE_CHANGED__STATE__ON);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007304 }
7305
7306 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7307 if (mCameraTurnedOnTimer != null) {
7308 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007309 if (!mCameraTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -08007310 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7311 StatsLog.CAMERA_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -07007312 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007313 }
7314 }
7315
7316 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7317 if (mCameraTurnedOnTimer != null) {
7318 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -08007319 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
7320 StatsLog.CAMERA_STATE_CHANGED__STATE__OFF);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007321 }
7322 }
7323
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007324 public StopwatchTimer createForegroundActivityTimerLocked() {
7325 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007326 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7327 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007328 }
7329 return mForegroundActivityTimer;
7330 }
7331
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007332 public StopwatchTimer createForegroundServiceTimerLocked() {
7333 if (mForegroundServiceTimer == null) {
7334 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7335 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7336 }
7337 return mForegroundServiceTimer;
7338 }
7339
Bookatzc8c44962017-05-11 12:12:54 -07007340 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7341 if (mAggregatedPartialWakelockTimer == null) {
7342 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7343 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7344 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7345 }
7346 return mAggregatedPartialWakelockTimer;
7347 }
7348
Bookatz867c0d72017-03-07 18:23:42 -08007349 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007350 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007351 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7352 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7353 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007354 }
7355 return mBluetoothScanTimer;
7356 }
7357
Bookatzb1f04f32017-05-19 13:57:32 -07007358 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7359 if (mBluetoothUnoptimizedScanTimer == null) {
7360 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7361 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7362 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7363 }
7364 return mBluetoothUnoptimizedScanTimer;
7365 }
7366
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007367 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7368 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007369 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007370 if (isUnoptimized) {
7371 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7372 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007373 }
7374
Bookatz94c5a312017-07-11 16:49:17 -07007375 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007376 if (mBluetoothScanTimer != null) {
7377 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7378 }
Bookatz94c5a312017-07-11 16:49:17 -07007379 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007380 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7381 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007382 }
7383
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007384 public void addBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7385 if (mAllBluetoothChains == null) {
7386 mAllBluetoothChains = new ArrayList<WorkChain>(4);
7387 }
7388
7389 if (isUnoptimized && mUnoptimizedBluetoothChains == null) {
7390 mUnoptimizedBluetoothChains = new ArrayList<WorkChain>(4);
7391 }
7392
7393 mAllBluetoothChains.add(workChain);
7394 if (isUnoptimized) {
7395 mUnoptimizedBluetoothChains.add(workChain);
7396 }
7397 }
7398
7399 public void removeBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7400 if (mAllBluetoothChains != null) {
7401 mAllBluetoothChains.remove(workChain);
7402 }
7403
7404 if (isUnoptimized && mUnoptimizedBluetoothChains != null) {
7405 mUnoptimizedBluetoothChains.remove(workChain);
7406 }
7407 }
7408
7409 public List<WorkChain> getAllBluetoothWorkChains() {
7410 return mAllBluetoothChains;
7411 }
7412
7413 public List<WorkChain> getUnoptimizedBluetoothWorkChains() {
7414 return mUnoptimizedBluetoothChains;
7415 }
7416
7417
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007418 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7419 if (mBluetoothScanTimer != null) {
7420 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7421 }
Bookatzb1f04f32017-05-19 13:57:32 -07007422 if (mBluetoothUnoptimizedScanTimer != null) {
7423 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7424 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007425 }
7426
Bookatz956f36bf2017-04-28 09:48:17 -07007427 public Counter createBluetoothScanResultCounterLocked() {
7428 if (mBluetoothScanResultCounter == null) {
7429 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7430 }
7431 return mBluetoothScanResultCounter;
7432 }
7433
Bookatzb1f04f32017-05-19 13:57:32 -07007434 public Counter createBluetoothScanResultBgCounterLocked() {
7435 if (mBluetoothScanResultBgCounter == null) {
7436 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7437 }
7438 return mBluetoothScanResultBgCounter;
7439 }
7440
Bookatz4ebc0642017-05-11 12:21:19 -07007441 public void noteBluetoothScanResultsLocked(int numNewResults) {
7442 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007443 // Uses background timebase, so the count will only be incremented if uid in background.
7444 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007445 }
7446
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007447 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007448 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007449 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007450 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007451 }
7452
7453 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007454 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007455 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007456 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007457 }
7458 }
7459
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007460 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7461 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7462 }
7463
7464 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7465 if (mForegroundServiceTimer != null) {
7466 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7467 }
7468 }
7469
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007470 public BatchTimer createVibratorOnTimerLocked() {
7471 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007472 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7473 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007474 }
7475 return mVibratorOnTimer;
7476 }
7477
7478 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007479 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007480 }
7481
7482 public void noteVibratorOffLocked() {
7483 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007484 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007485 }
7486 }
7487
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007488 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007489 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007490 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007491 return 0;
7492 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007493 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007494 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007495
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007496 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007497 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007498 if (mFullWifiLockTimer == null) {
7499 return 0;
7500 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007501 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007502 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007503
7504 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007505 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007506 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007507 return 0;
7508 }
Bookatzaa4594a2017-03-24 12:39:56 -07007509 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007510 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007511
7512 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007513 public int getWifiScanCount(int which) {
7514 if (mWifiScanTimer == null) {
7515 return 0;
7516 }
Bookatzaa4594a2017-03-24 12:39:56 -07007517 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007518 }
7519
7520 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007521 public Timer getWifiScanTimer() {
7522 return mWifiScanTimer;
7523 }
7524
7525 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007526 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007527 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007528 return 0;
7529 }
7530 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7531 }
7532
7533 @Override
7534 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7535 if (mWifiScanTimer == null) {
7536 return 0;
7537 }
7538 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007539 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007540 }
7541
7542 @Override
7543 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007544 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007545 return 0;
7546 }
7547 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7548 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007549 }
7550
7551 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007552 public Timer getWifiScanBackgroundTimer() {
7553 if (mWifiScanTimer == null) {
7554 return null;
7555 }
7556 return mWifiScanTimer.getSubTimer();
7557 }
7558
7559 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007560 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007561 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7562 if (mWifiBatchedScanTimer[csphBin] == null) {
7563 return 0;
7564 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007565 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007566 }
7567
7568 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007569 public int getWifiBatchedScanCount(int csphBin, int which) {
7570 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7571 if (mWifiBatchedScanTimer[csphBin] == null) {
7572 return 0;
7573 }
7574 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7575 }
7576
7577 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007578 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007579 if (mWifiMulticastTimer == null) {
7580 return 0;
7581 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007582 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007583 }
7584
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007585 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007586 public Timer getAudioTurnedOnTimer() {
7587 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007588 }
7589
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007590 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007591 public Timer getVideoTurnedOnTimer() {
7592 return mVideoTurnedOnTimer;
7593 }
7594
7595 @Override
7596 public Timer getFlashlightTurnedOnTimer() {
7597 return mFlashlightTurnedOnTimer;
7598 }
7599
7600 @Override
7601 public Timer getCameraTurnedOnTimer() {
7602 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007603 }
7604
Dianne Hackborn617f8772009-03-31 15:04:46 -07007605 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007606 public Timer getForegroundActivityTimer() {
7607 return mForegroundActivityTimer;
7608 }
7609
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007610 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007611 public Timer getForegroundServiceTimer() {
7612 return mForegroundServiceTimer;
7613 }
7614
7615 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007616 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007617 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007618 }
7619
7620 @Override
7621 public Timer getBluetoothScanBackgroundTimer() {
7622 if (mBluetoothScanTimer == null) {
7623 return null;
7624 }
7625 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007626 }
7627
Bookatz956f36bf2017-04-28 09:48:17 -07007628 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007629 public Timer getBluetoothUnoptimizedScanTimer() {
7630 return mBluetoothUnoptimizedScanTimer;
7631 }
7632
7633 @Override
7634 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7635 if (mBluetoothUnoptimizedScanTimer == null) {
7636 return null;
7637 }
7638 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7639 }
7640
7641 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007642 public Counter getBluetoothScanResultCounter() {
7643 return mBluetoothScanResultCounter;
7644 }
7645
Bookatzb1f04f32017-05-19 13:57:32 -07007646 @Override
7647 public Counter getBluetoothScanResultBgCounter() {
7648 return mBluetoothScanResultBgCounter;
7649 }
7650
Dianne Hackborn61659e52014-07-09 16:13:01 -07007651 void makeProcessState(int i, Parcel in) {
7652 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7653
7654 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007655 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7656 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007657 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007658 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7659 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007660 }
7661 }
7662
7663 @Override
7664 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7665 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7666 if (mProcessStateTimer[state] == null) {
7667 return 0;
7668 }
7669 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7670 }
7671
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007672 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007673 public Timer getProcessStateTimer(int state) {
7674 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7675 return mProcessStateTimer[state];
7676 }
7677
7678 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007679 public Timer getVibratorOnTimer() {
7680 return mVibratorOnTimer;
7681 }
7682
7683 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007684 public void noteUserActivityLocked(int type) {
7685 if (mUserActivityCounters == null) {
7686 initUserActivityLocked();
7687 }
Jeff Browndf693de2012-07-27 12:03:38 -07007688 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7689 mUserActivityCounters[type].stepAtomic();
7690 } else {
7691 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7692 new Throwable());
7693 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007694 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007695
Dianne Hackborn617f8772009-03-31 15:04:46 -07007696 @Override
7697 public boolean hasUserActivity() {
7698 return mUserActivityCounters != null;
7699 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007700
Dianne Hackborn617f8772009-03-31 15:04:46 -07007701 @Override
7702 public int getUserActivityCount(int type, int which) {
7703 if (mUserActivityCounters == null) {
7704 return 0;
7705 }
Evan Millarc64edde2009-04-18 12:26:32 -07007706 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007707 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007708
Robert Greenwalta029ea12013-09-25 16:38:12 -07007709 void makeWifiBatchedScanBin(int i, Parcel in) {
7710 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7711
Joe Onoratoabded112016-02-08 16:49:39 -08007712 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007713 if (collected == null) {
7714 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007715 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007716 }
7717 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007718 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7719 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007720 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007721 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7722 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007723 }
7724 }
7725
7726
Dianne Hackborn617f8772009-03-31 15:04:46 -07007727 void initUserActivityLocked() {
7728 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7729 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007730 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007731 }
7732 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007733
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007734 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7735 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007736 initNetworkActivityLocked();
7737 }
7738 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007739 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7740 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007741 } else {
7742 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7743 new Throwable());
7744 }
7745 }
7746
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007747 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7748 if (mNetworkByteActivityCounters == null) {
7749 initNetworkActivityLocked();
7750 }
7751 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7752 mMobileRadioActiveCount.addCountLocked(1);
7753 }
7754
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007755 @Override
7756 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007757 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007758 }
7759
7760 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007761 public long getNetworkActivityBytes(int type, int which) {
7762 if (mNetworkByteActivityCounters != null && type >= 0
7763 && type < mNetworkByteActivityCounters.length) {
7764 return mNetworkByteActivityCounters[type].getCountLocked(which);
7765 } else {
7766 return 0;
7767 }
7768 }
7769
7770 @Override
7771 public long getNetworkActivityPackets(int type, int which) {
7772 if (mNetworkPacketActivityCounters != null && type >= 0
7773 && type < mNetworkPacketActivityCounters.length) {
7774 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007775 } else {
7776 return 0;
7777 }
7778 }
7779
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007780 @Override
7781 public long getMobileRadioActiveTime(int which) {
7782 return mMobileRadioActiveTime != null
7783 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7784 }
7785
7786 @Override
7787 public int getMobileRadioActiveCount(int which) {
7788 return mMobileRadioActiveCount != null
7789 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7790 }
7791
Adam Lesinskie08af192015-03-25 16:42:59 -07007792 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007793 public long getUserCpuTimeUs(int which) {
7794 return mUserCpuTime.getCountLocked(which);
7795 }
7796
7797 @Override
7798 public long getSystemCpuTimeUs(int which) {
7799 return mSystemCpuTime.getCountLocked(which);
7800 }
7801
7802 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007803 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007804 if (mCpuClusterSpeedTimesUs != null) {
7805 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7806 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7807 if (cpuSpeedTimesUs != null) {
7808 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7809 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007810 if (c != null) {
7811 return c.getCountLocked(which);
7812 }
7813 }
7814 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007815 }
7816 }
7817 return 0;
7818 }
7819
Adam Lesinski5f056f62016-07-14 16:56:08 -07007820 public void noteMobileRadioApWakeupLocked() {
7821 if (mMobileRadioApWakeupCount == null) {
7822 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7823 }
7824 mMobileRadioApWakeupCount.addCountLocked(1);
7825 }
7826
7827 @Override
7828 public long getMobileRadioApWakeupCount(int which) {
7829 if (mMobileRadioApWakeupCount != null) {
7830 return mMobileRadioApWakeupCount.getCountLocked(which);
7831 }
7832 return 0;
7833 }
7834
7835 public void noteWifiRadioApWakeupLocked() {
7836 if (mWifiRadioApWakeupCount == null) {
7837 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7838 }
7839 mWifiRadioApWakeupCount.addCountLocked(1);
7840 }
7841
7842 @Override
7843 public long getWifiRadioApWakeupCount(int which) {
7844 if (mWifiRadioApWakeupCount != null) {
7845 return mWifiRadioApWakeupCount.getCountLocked(which);
7846 }
7847 return 0;
7848 }
7849
Amith Yamasani977e11f2018-02-16 11:29:54 -08007850 @Override
7851 public void getDeferredJobsCheckinLineLocked(StringBuilder sb, int which) {
7852 sb.setLength(0);
7853 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7854 if (deferredEventCount == 0) {
7855 return;
7856 }
7857 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
7858 final long averageLatency = deferredEventCount != 0
7859 ? mJobsFreshnessTimeMs.getCountLocked(which) / deferredEventCount
7860 : 0L;
7861 sb.append(deferredEventCount); sb.append(',');
7862 sb.append(deferredCount); sb.append(',');
7863 sb.append(averageLatency);
7864 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7865 if (mJobsFreshnessBuckets[i] == null) {
7866 sb.append(",0");
7867 } else {
7868 sb.append(",");
7869 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7870 }
7871 }
7872 }
7873
7874 @Override
7875 public void getDeferredJobsLineLocked(StringBuilder sb, int which) {
7876 sb.setLength(0);
7877 final int deferredEventCount = mJobsDeferredEventCount.getCountLocked(which);
7878 if (deferredEventCount == 0) {
7879 return;
7880 }
7881 final int deferredCount = mJobsDeferredCount.getCountLocked(which);
7882 final long averageLatency = deferredEventCount != 0
7883 ? mJobsFreshnessTimeMs.getCountLocked(which) / deferredEventCount
7884 : 0L;
7885 sb.append("times="); sb.append(deferredEventCount); sb.append(", ");
7886 sb.append("count="); sb.append(deferredCount); sb.append(", ");
7887 sb.append("avgLatency="); sb.append(averageLatency); sb.append(", ");
7888 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
7889 sb.append("<"); sb.append(JOB_FRESHNESS_BUCKETS[i]); sb.append("ms=");
7890 if (mJobsFreshnessBuckets[i] == null) {
7891 sb.append("0");
7892 } else {
7893 sb.append(mJobsFreshnessBuckets[i].getCountLocked(which));
7894 }
7895 sb.append(" ");
7896 }
7897 }
7898
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007899 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007900 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7901 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007902 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007903 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7904 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007905 }
Joe Onoratoabded112016-02-08 16:49:39 -08007906 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7907 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007908 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007909
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007910 /**
7911 * Clear all stats for this uid. Returns true if the uid is completely
7912 * inactive so can be dropped.
7913 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007914 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007915 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007916 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007917
Bookatz993a0be2017-07-21 09:03:23 -07007918 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7919 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7920
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007921 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007922 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007923 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007924 }
7925 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007926 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007927 active |= mFullWifiLockOut;
7928 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007929 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007930 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007931 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007932 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007933 if (mWifiBatchedScanTimer != null) {
7934 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7935 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007936 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007937 }
7938 }
7939 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7940 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007941 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007942 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007943 active |= mWifiMulticastEnabled;
7944 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007945
7946 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7947 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7948 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7949 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7950 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007951 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007952 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007953 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007954 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007955 if (mBluetoothScanResultCounter != null) {
7956 mBluetoothScanResultCounter.reset(false);
7957 }
Bookatzb1f04f32017-05-19 13:57:32 -07007958 if (mBluetoothScanResultBgCounter != null) {
7959 mBluetoothScanResultBgCounter.reset(false);
7960 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007961
Dianne Hackborn61659e52014-07-09 16:13:01 -07007962 if (mProcessStateTimer != null) {
7963 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7964 if (mProcessStateTimer[i] != null) {
7965 active |= !mProcessStateTimer[i].reset(false);
7966 }
7967 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007968 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007969 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007970 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007971 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007972 mVibratorOnTimer.detach();
7973 mVibratorOnTimer = null;
7974 } else {
7975 active = true;
7976 }
7977 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007978
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007979 if (mUserActivityCounters != null) {
7980 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7981 mUserActivityCounters[i].reset(false);
7982 }
7983 }
7984
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007985 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007986 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007987 mNetworkByteActivityCounters[i].reset(false);
7988 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007989 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007990 mMobileRadioActiveTime.reset(false);
7991 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007992 }
7993
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007994 if (mWifiControllerActivity != null) {
7995 mWifiControllerActivity.reset(false);
7996 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007997
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007998 if (mBluetoothControllerActivity != null) {
7999 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008000 }
8001
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07008002 if (mModemControllerActivity != null) {
8003 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07008004 }
8005
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008006 mUserCpuTime.reset(false);
8007 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07008008
Sudheer Shankaaf857412017-07-21 00:14:24 -07008009 if (mCpuClusterSpeedTimesUs != null) {
8010 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008011 if (speeds != null) {
8012 for (LongSamplingCounter speed : speeds) {
8013 if (speed != null) {
8014 speed.reset(false);
8015 }
8016 }
8017 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008018 }
8019 }
8020
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008021 if (mCpuFreqTimeMs != null) {
8022 mCpuFreqTimeMs.reset(false);
8023 }
8024 if (mScreenOffCpuFreqTimeMs != null) {
8025 mScreenOffCpuFreqTimeMs.reset(false);
8026 }
8027
Mike Ma3d422c32017-10-25 11:08:57 -07008028 mCpuActiveTimeMs.reset(false);
8029 mCpuClusterTimesMs.reset(false);
8030
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008031 if (mProcStateTimeMs != null) {
8032 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8033 if (counters != null) {
8034 counters.reset(false);
8035 }
8036 }
8037 }
8038 if (mProcStateScreenOffTimeMs != null) {
8039 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8040 if (counters != null) {
8041 counters.reset(false);
8042 }
8043 }
8044 }
8045
Adam Lesinski5f056f62016-07-14 16:56:08 -07008046 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
8047 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
8048
Dianne Hackbornd953c532014-08-16 18:17:38 -07008049 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8050 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
8051 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008052 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008053 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008054 } else {
8055 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008056 }
8057 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008058 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07008059 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008060 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008061 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008062 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008063 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008064 timer.detach();
8065 } else {
8066 active = true;
8067 }
8068 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008069 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07008070 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008071 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07008072 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008073 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008074 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008075 timer.detach();
8076 } else {
8077 active = true;
8078 }
8079 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008080 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008081 mJobCompletions.clear();
Amith Yamasani977e11f2018-02-16 11:29:54 -08008082
8083 mJobsDeferredEventCount.reset(false);
8084 mJobsDeferredCount.reset(false);
8085 mJobsFreshnessTimeMs.reset(false);
8086 for (int ij = 0; ij < JOB_FRESHNESS_BUCKETS.length; ij++) {
8087 if (mJobsFreshnessBuckets[ij] != null) {
8088 mJobsFreshnessBuckets[ij].reset(false);
8089 }
8090 }
8091
Dianne Hackborn61659e52014-07-09 16:13:01 -07008092 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
8093 Sensor s = mSensorStats.valueAt(ise);
8094 if (s.reset()) {
8095 mSensorStats.removeAt(ise);
8096 } else {
8097 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008098 }
8099 }
Amith Yamasani977e11f2018-02-16 11:29:54 -08008100
Dianne Hackborn61659e52014-07-09 16:13:01 -07008101 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
8102 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008103 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008104 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008105 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008106 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008107 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008108 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008109 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008110 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008111 } else {
8112 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008113 }
8114 }
8115 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008116 if (mPackageStats.size() > 0) {
8117 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
8118 while (it.hasNext()) {
8119 Map.Entry<String, Pkg> pkgEntry = it.next();
8120 Pkg p = pkgEntry.getValue();
8121 p.detach();
8122 if (p.mServiceStats.size() > 0) {
8123 Iterator<Map.Entry<String, Pkg.Serv>> it2
8124 = p.mServiceStats.entrySet().iterator();
8125 while (it2.hasNext()) {
8126 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
8127 servEntry.getValue().detach();
8128 }
8129 }
8130 }
8131 mPackageStats.clear();
8132 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008133
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08008134 mLastStepUserTime = mLastStepSystemTime = 0;
8135 mCurStepUserTime = mCurStepSystemTime = 0;
8136
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008137 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008138 if (mWifiRunningTimer != null) {
8139 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008140 }
8141 if (mFullWifiLockTimer != null) {
8142 mFullWifiLockTimer.detach();
8143 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008144 if (mWifiScanTimer != null) {
8145 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008146 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008147 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8148 if (mWifiBatchedScanTimer[i] != null) {
8149 mWifiBatchedScanTimer[i].detach();
8150 }
8151 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008152 if (mWifiMulticastTimer != null) {
8153 mWifiMulticastTimer.detach();
8154 }
8155 if (mAudioTurnedOnTimer != null) {
8156 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008157 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008158 }
8159 if (mVideoTurnedOnTimer != null) {
8160 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008161 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008162 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008163 if (mFlashlightTurnedOnTimer != null) {
8164 mFlashlightTurnedOnTimer.detach();
8165 mFlashlightTurnedOnTimer = null;
8166 }
8167 if (mCameraTurnedOnTimer != null) {
8168 mCameraTurnedOnTimer.detach();
8169 mCameraTurnedOnTimer = null;
8170 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008171 if (mForegroundActivityTimer != null) {
8172 mForegroundActivityTimer.detach();
8173 mForegroundActivityTimer = null;
8174 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008175 if (mForegroundServiceTimer != null) {
8176 mForegroundServiceTimer.detach();
8177 mForegroundServiceTimer = null;
8178 }
Bookatzc8c44962017-05-11 12:12:54 -07008179 if (mAggregatedPartialWakelockTimer != null) {
8180 mAggregatedPartialWakelockTimer.detach();
8181 mAggregatedPartialWakelockTimer = null;
8182 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008183 if (mBluetoothScanTimer != null) {
8184 mBluetoothScanTimer.detach();
8185 mBluetoothScanTimer = null;
8186 }
Bookatzb1f04f32017-05-19 13:57:32 -07008187 if (mBluetoothUnoptimizedScanTimer != null) {
8188 mBluetoothUnoptimizedScanTimer.detach();
8189 mBluetoothUnoptimizedScanTimer = null;
8190 }
Bookatz956f36bf2017-04-28 09:48:17 -07008191 if (mBluetoothScanResultCounter != null) {
8192 mBluetoothScanResultCounter.detach();
8193 mBluetoothScanResultCounter = null;
8194 }
Bookatzb1f04f32017-05-19 13:57:32 -07008195 if (mBluetoothScanResultBgCounter != null) {
8196 mBluetoothScanResultBgCounter.detach();
8197 mBluetoothScanResultBgCounter = null;
8198 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008199 if (mUserActivityCounters != null) {
8200 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8201 mUserActivityCounters[i].detach();
8202 }
8203 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008204 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008205 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008206 mNetworkByteActivityCounters[i].detach();
8207 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008208 }
8209 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008210
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008211 if (mWifiControllerActivity != null) {
8212 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008213 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008214
8215 if (mBluetoothControllerActivity != null) {
8216 mBluetoothControllerActivity.detach();
8217 }
8218
8219 if (mModemControllerActivity != null) {
8220 mModemControllerActivity.detach();
8221 }
8222
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008223 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008224
8225 mUserCpuTime.detach();
8226 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008227
Sudheer Shankaaf857412017-07-21 00:14:24 -07008228 if (mCpuClusterSpeedTimesUs != null) {
8229 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008230 if (cpuSpeeds != null) {
8231 for (LongSamplingCounter c : cpuSpeeds) {
8232 if (c != null) {
8233 c.detach();
8234 }
8235 }
8236 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008237 }
8238 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008239
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008240 if (mCpuFreqTimeMs != null) {
8241 mCpuFreqTimeMs.detach();
8242 }
8243 if (mScreenOffCpuFreqTimeMs != null) {
8244 mScreenOffCpuFreqTimeMs.detach();
8245 }
Mike Ma3d422c32017-10-25 11:08:57 -07008246 mCpuActiveTimeMs.detach();
8247 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008248
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008249 if (mProcStateTimeMs != null) {
8250 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8251 if (counters != null) {
8252 counters.detach();
8253 }
8254 }
8255 }
8256 if (mProcStateScreenOffTimeMs != null) {
8257 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8258 if (counters != null) {
8259 counters.detach();
8260 }
8261 }
8262 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008263 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8264 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008265 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008266
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008267 return !active;
8268 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008269
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008270 void writeJobCompletionsToParcelLocked(Parcel out) {
8271 int NJC = mJobCompletions.size();
8272 out.writeInt(NJC);
8273 for (int ijc=0; ijc<NJC; ijc++) {
8274 out.writeString(mJobCompletions.keyAt(ijc));
8275 SparseIntArray types = mJobCompletions.valueAt(ijc);
8276 int NT = types.size();
8277 out.writeInt(NT);
8278 for (int it=0; it<NT; it++) {
8279 out.writeInt(types.keyAt(it));
8280 out.writeInt(types.valueAt(it));
8281 }
8282 }
8283 }
8284
Bookatz867c0d72017-03-07 18:23:42 -08008285 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8286 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008287 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008288
Dianne Hackbornd953c532014-08-16 18:17:38 -07008289 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8290 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008291 out.writeInt(NW);
8292 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008293 out.writeString(wakeStats.keyAt(iw));
8294 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008295 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 }
8297
Bookatz2bffb5b2017-04-13 11:59:33 -07008298 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008299 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008300 out.writeInt(NS);
8301 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008302 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008303 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008304 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8305 }
8306
Bookatzaa4594a2017-03-24 12:39:56 -07008307 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008308 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008309 out.writeInt(NJ);
8310 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008311 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008312 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008313 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8314 }
8315
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008316 writeJobCompletionsToParcelLocked(out);
8317
Amith Yamasani977e11f2018-02-16 11:29:54 -08008318 mJobsDeferredEventCount.writeToParcel(out);
8319 mJobsDeferredCount.writeToParcel(out);
8320 mJobsFreshnessTimeMs.writeToParcel(out);
8321 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8322 Counter.writeCounterToParcel(out, mJobsFreshnessBuckets[i]);
8323 }
8324
Dianne Hackborn61659e52014-07-09 16:13:01 -07008325 int NSE = mSensorStats.size();
8326 out.writeInt(NSE);
8327 for (int ise=0; ise<NSE; ise++) {
8328 out.writeInt(mSensorStats.keyAt(ise));
8329 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008330 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008331 }
8332
Dianne Hackborn61659e52014-07-09 16:13:01 -07008333 int NP = mProcessStats.size();
8334 out.writeInt(NP);
8335 for (int ip=0; ip<NP; ip++) {
8336 out.writeString(mProcessStats.keyAt(ip));
8337 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 proc.writeToParcelLocked(out);
8339 }
8340
8341 out.writeInt(mPackageStats.size());
8342 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8343 out.writeString(pkgEntry.getKey());
8344 Uid.Pkg pkg = pkgEntry.getValue();
8345 pkg.writeToParcelLocked(out);
8346 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008347
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008348 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008349 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008350 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008351 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008352 out.writeInt(0);
8353 }
8354 if (mFullWifiLockTimer != null) {
8355 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008356 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008357 } else {
8358 out.writeInt(0);
8359 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008360 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008361 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008362 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008363 } else {
8364 out.writeInt(0);
8365 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008366 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8367 if (mWifiBatchedScanTimer[i] != null) {
8368 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008369 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008370 } else {
8371 out.writeInt(0);
8372 }
8373 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008374 if (mWifiMulticastTimer != null) {
8375 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008376 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008377 } else {
8378 out.writeInt(0);
8379 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008380
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008381 if (mAudioTurnedOnTimer != null) {
8382 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008383 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008384 } else {
8385 out.writeInt(0);
8386 }
8387 if (mVideoTurnedOnTimer != null) {
8388 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008389 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008390 } else {
8391 out.writeInt(0);
8392 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008393 if (mFlashlightTurnedOnTimer != null) {
8394 out.writeInt(1);
8395 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8396 } else {
8397 out.writeInt(0);
8398 }
8399 if (mCameraTurnedOnTimer != null) {
8400 out.writeInt(1);
8401 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8402 } else {
8403 out.writeInt(0);
8404 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008405 if (mForegroundActivityTimer != null) {
8406 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008407 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008408 } else {
8409 out.writeInt(0);
8410 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008411 if (mForegroundServiceTimer != null) {
8412 out.writeInt(1);
8413 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8414 } else {
8415 out.writeInt(0);
8416 }
Bookatzc8c44962017-05-11 12:12:54 -07008417 if (mAggregatedPartialWakelockTimer != null) {
8418 out.writeInt(1);
8419 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8420 } else {
8421 out.writeInt(0);
8422 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008423 if (mBluetoothScanTimer != null) {
8424 out.writeInt(1);
8425 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8426 } else {
8427 out.writeInt(0);
8428 }
Bookatzb1f04f32017-05-19 13:57:32 -07008429 if (mBluetoothUnoptimizedScanTimer != null) {
8430 out.writeInt(1);
8431 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8432 } else {
8433 out.writeInt(0);
8434 }
Bookatz956f36bf2017-04-28 09:48:17 -07008435 if (mBluetoothScanResultCounter != null) {
8436 out.writeInt(1);
8437 mBluetoothScanResultCounter.writeToParcel(out);
8438 } else {
8439 out.writeInt(0);
8440 }
Bookatzb1f04f32017-05-19 13:57:32 -07008441 if (mBluetoothScanResultBgCounter != null) {
8442 out.writeInt(1);
8443 mBluetoothScanResultBgCounter.writeToParcel(out);
8444 } else {
8445 out.writeInt(0);
8446 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008447 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8448 if (mProcessStateTimer[i] != null) {
8449 out.writeInt(1);
8450 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8451 } else {
8452 out.writeInt(0);
8453 }
8454 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008455 if (mVibratorOnTimer != null) {
8456 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008457 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008458 } else {
8459 out.writeInt(0);
8460 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008461 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008462 out.writeInt(1);
8463 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8464 mUserActivityCounters[i].writeToParcel(out);
8465 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008466 } else {
8467 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008468 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008469 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008470 out.writeInt(1);
8471 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008472 mNetworkByteActivityCounters[i].writeToParcel(out);
8473 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008474 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008475 mMobileRadioActiveTime.writeToParcel(out);
8476 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008477 } else {
8478 out.writeInt(0);
8479 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008480
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008481 if (mWifiControllerActivity != null) {
8482 out.writeInt(1);
8483 mWifiControllerActivity.writeToParcel(out, 0);
8484 } else {
8485 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008486 }
8487
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008488 if (mBluetoothControllerActivity != null) {
8489 out.writeInt(1);
8490 mBluetoothControllerActivity.writeToParcel(out, 0);
8491 } else {
8492 out.writeInt(0);
8493 }
8494
8495 if (mModemControllerActivity != null) {
8496 out.writeInt(1);
8497 mModemControllerActivity.writeToParcel(out, 0);
8498 } else {
8499 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008500 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008501
8502 mUserCpuTime.writeToParcel(out);
8503 mSystemCpuTime.writeToParcel(out);
8504
Sudheer Shankaaf857412017-07-21 00:14:24 -07008505 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008506 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008507 out.writeInt(mCpuClusterSpeedTimesUs.length);
8508 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008509 if (cpuSpeeds != null) {
8510 out.writeInt(1);
8511 out.writeInt(cpuSpeeds.length);
8512 for (LongSamplingCounter c : cpuSpeeds) {
8513 if (c != null) {
8514 out.writeInt(1);
8515 c.writeToParcel(out);
8516 } else {
8517 out.writeInt(0);
8518 }
8519 }
8520 } else {
8521 out.writeInt(0);
8522 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008523 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008524 } else {
8525 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008526 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008527
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008528 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8529 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008530
8531 mCpuActiveTimeMs.writeToParcel(out);
8532 mCpuClusterTimesMs.writeToParcel(out);
8533
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008534 if (mProcStateTimeMs != null) {
8535 out.writeInt(mProcStateTimeMs.length);
8536 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8537 LongSamplingCounterArray.writeToParcel(out, counters);
8538 }
8539 } else {
8540 out.writeInt(0);
8541 }
8542 if (mProcStateScreenOffTimeMs != null) {
8543 out.writeInt(mProcStateScreenOffTimeMs.length);
8544 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8545 LongSamplingCounterArray.writeToParcel(out, counters);
8546 }
8547 } else {
8548 out.writeInt(0);
8549 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008550
Adam Lesinski5f056f62016-07-14 16:56:08 -07008551 if (mMobileRadioApWakeupCount != null) {
8552 out.writeInt(1);
8553 mMobileRadioApWakeupCount.writeToParcel(out);
8554 } else {
8555 out.writeInt(0);
8556 }
8557
8558 if (mWifiRadioApWakeupCount != null) {
8559 out.writeInt(1);
8560 mWifiRadioApWakeupCount.writeToParcel(out);
8561 } else {
8562 out.writeInt(0);
8563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008564 }
8565
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008566 void readJobCompletionsFromParcelLocked(Parcel in) {
8567 int numJobCompletions = in.readInt();
8568 mJobCompletions.clear();
8569 for (int j = 0; j < numJobCompletions; j++) {
8570 String jobName = in.readString();
8571 int numTypes = in.readInt();
8572 if (numTypes > 0) {
8573 SparseIntArray types = new SparseIntArray();
8574 for (int k = 0; k < numTypes; k++) {
8575 int type = in.readInt();
8576 int count = in.readInt();
8577 types.put(type, count);
8578 }
8579 mJobCompletions.put(jobName, types);
8580 }
8581 }
8582 }
8583
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008584 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008585 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008586 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008588 int numWakelocks = in.readInt();
8589 mWakelockStats.clear();
8590 for (int j = 0; j < numWakelocks; j++) {
8591 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008592 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008593 wakelock.readFromParcelLocked(
8594 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008595 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 }
8597
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008598 int numSyncs = in.readInt();
8599 mSyncStats.clear();
8600 for (int j = 0; j < numSyncs; j++) {
8601 String syncName = in.readString();
8602 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008603 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8604 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008605 }
8606 }
8607
8608 int numJobs = in.readInt();
8609 mJobStats.clear();
8610 for (int j = 0; j < numJobs; j++) {
8611 String jobName = in.readString();
8612 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008613 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8614 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008615 }
8616 }
8617
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008618 readJobCompletionsFromParcelLocked(in);
8619
Amith Yamasani977e11f2018-02-16 11:29:54 -08008620 mJobsDeferredEventCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8621 mJobsDeferredCount = new Counter(mBsi.mOnBatteryTimeBase, in);
8622 mJobsFreshnessTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8623 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8624 mJobsFreshnessBuckets[i] = Counter.readCounterFromParcel(mBsi.mOnBatteryTimeBase,
8625 in);
8626 }
8627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628 int numSensors = in.readInt();
8629 mSensorStats.clear();
8630 for (int k = 0; k < numSensors; k++) {
8631 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008632 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008633 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8634 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008635 mSensorStats.put(sensorNumber, sensor);
8636 }
8637
8638 int numProcs = in.readInt();
8639 mProcessStats.clear();
8640 for (int k = 0; k < numProcs; k++) {
8641 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008642 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643 proc.readFromParcelLocked(in);
8644 mProcessStats.put(processName, proc);
8645 }
8646
8647 int numPkgs = in.readInt();
8648 mPackageStats.clear();
8649 for (int l = 0; l < numPkgs; l++) {
8650 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008651 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008652 pkg.readFromParcelLocked(in);
8653 mPackageStats.put(packageName, pkg);
8654 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008655
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008656 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008657 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008658 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8659 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008660 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008661 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008662 }
8663 mFullWifiLockOut = false;
8664 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008665 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8666 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008667 } else {
8668 mFullWifiLockTimer = null;
8669 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008670 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008671 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008672 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8673 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8674 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008675 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008676 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008677 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008678 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8679 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8680 if (in.readInt() != 0) {
8681 makeWifiBatchedScanBin(i, in);
8682 } else {
8683 mWifiBatchedScanTimer[i] = null;
8684 }
8685 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008686 mWifiMulticastEnabled = false;
8687 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008688 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8689 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008690 } else {
8691 mWifiMulticastTimer = null;
8692 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008693 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008694 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8695 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008696 } else {
8697 mAudioTurnedOnTimer = null;
8698 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008699 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008700 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8701 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008702 } else {
8703 mVideoTurnedOnTimer = null;
8704 }
8705 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008706 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8707 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008708 } else {
8709 mFlashlightTurnedOnTimer = null;
8710 }
8711 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008712 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8713 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008714 } else {
8715 mCameraTurnedOnTimer = null;
8716 }
8717 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008718 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8719 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008720 } else {
8721 mForegroundActivityTimer = null;
8722 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008723 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008724 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8725 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8726 } else {
8727 mForegroundServiceTimer = null;
8728 }
8729 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008730 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8731 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8732 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8733 in);
8734 } else {
8735 mAggregatedPartialWakelockTimer = null;
8736 }
8737 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008738 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8739 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8740 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008741 } else {
8742 mBluetoothScanTimer = null;
8743 }
Bookatz956f36bf2017-04-28 09:48:17 -07008744 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008745 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8746 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8747 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8748 } else {
8749 mBluetoothUnoptimizedScanTimer = null;
8750 }
8751 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008752 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8753 } else {
8754 mBluetoothScanResultCounter = null;
8755 }
Bookatzb1f04f32017-05-19 13:57:32 -07008756 if (in.readInt() != 0) {
8757 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8758 } else {
8759 mBluetoothScanResultBgCounter = null;
8760 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008761 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008762 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8763 if (in.readInt() != 0) {
8764 makeProcessState(i, in);
8765 } else {
8766 mProcessStateTimer[i] = null;
8767 }
8768 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008769 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008770 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8771 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008772 } else {
8773 mVibratorOnTimer = null;
8774 }
8775 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008776 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8777 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008778 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008779 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008780 } else {
8781 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008782 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008783 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008784 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8785 mNetworkPacketActivityCounters
8786 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008787 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008788 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008789 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008790 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008791 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008792 }
Joe Onoratoabded112016-02-08 16:49:39 -08008793 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8794 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008795 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008796 mNetworkByteActivityCounters = null;
8797 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008798 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008799
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008800 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008801 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008802 NUM_WIFI_TX_LEVELS, in);
8803 } else {
8804 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008805 }
8806
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008807 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008808 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008809 NUM_BT_TX_LEVELS, in);
8810 } else {
8811 mBluetoothControllerActivity = null;
8812 }
8813
8814 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008815 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008816 ModemActivityInfo.TX_POWER_LEVELS, in);
8817 } else {
8818 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008819 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008820
Joe Onoratoabded112016-02-08 16:49:39 -08008821 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8822 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008823
Adam Lesinski6832f392015-09-05 18:05:40 -07008824 if (in.readInt() != 0) {
8825 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008826 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008827 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008828 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008829
Sudheer Shankaaf857412017-07-21 00:14:24 -07008830 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008831 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8832 if (in.readInt() != 0) {
8833 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008834 if (mBsi.mPowerProfile != null &&
8835 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008836 throw new ParcelFormatException("Incompatible number of cpu speeds");
8837 }
8838
8839 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008840 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008841 for (int speed = 0; speed < numSpeeds; speed++) {
8842 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008843 cpuSpeeds[speed] = new LongSamplingCounter(
8844 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008845 }
8846 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008847 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008848 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008849 }
8850 }
8851 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008852 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008853 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008854
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008855 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8856 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8857 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008858
Mike Ma3d422c32017-10-25 11:08:57 -07008859 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8860 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8861
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008862 int length = in.readInt();
8863 if (length == NUM_PROCESS_STATE) {
8864 mProcStateTimeMs = new LongSamplingCounterArray[length];
8865 for (int procState = 0; procState < length; ++procState) {
8866 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8867 in, mBsi.mOnBatteryTimeBase);
8868 }
8869 } else {
8870 mProcStateTimeMs = null;
8871 }
8872 length = in.readInt();
8873 if (length == NUM_PROCESS_STATE) {
8874 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8875 for (int procState = 0; procState < length; ++procState) {
8876 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8877 in, mBsi.mOnBatteryScreenOffTimeBase);
8878 }
8879 } else {
8880 mProcStateScreenOffTimeMs = null;
8881 }
8882
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008883 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008884 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8885 } else {
8886 mMobileRadioApWakeupCount = null;
8887 }
8888
8889 if (in.readInt() != 0) {
8890 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8891 } else {
8892 mWifiRadioApWakeupCount = null;
8893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008894 }
8895
Amith Yamasani977e11f2018-02-16 11:29:54 -08008896 public void noteJobsDeferredLocked(int numDeferred, long sinceLast) {
8897 mJobsDeferredEventCount.addAtomic(1);
8898 mJobsDeferredCount.addAtomic(numDeferred);
8899 if (sinceLast != 0) {
8900 // Add the total time, which can be divided by the event count to get an average
8901 mJobsFreshnessTimeMs.addCountLocked(sinceLast);
8902 // Also keep track of how many times there were in these different buckets.
8903 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
8904 if (sinceLast < JOB_FRESHNESS_BUCKETS[i]) {
8905 if (mJobsFreshnessBuckets[i] == null) {
8906 mJobsFreshnessBuckets[i] = new Counter(
8907 mBsi.mOnBatteryTimeBase);
8908 }
8909 mJobsFreshnessBuckets[i].addAtomic(1);
8910 break;
8911 }
8912 }
8913 }
8914 }
8915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008916 /**
8917 * The statistics associated with a particular wake lock.
8918 */
Joe Onoratoabded112016-02-08 16:49:39 -08008919 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8920 /**
8921 * BatteryStatsImpl that we are associated with.
8922 */
8923 protected BatteryStatsImpl mBsi;
8924
8925 /**
8926 * BatteryStatsImpl that we are associated with.
8927 */
8928 protected Uid mUid;
8929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008930 /**
8931 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008932 * 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 -08008933 */
Bookatz5b5ec322017-05-26 09:40:38 -07008934 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935
8936 /**
8937 * How long (in ms) this uid has been keeping the device fully awake.
8938 */
Evan Millarc64edde2009-04-18 12:26:32 -07008939 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008940
8941 /**
8942 * How long (in ms) this uid has had a window keeping the device awake.
8943 */
Evan Millarc64edde2009-04-18 12:26:32 -07008944 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945
8946 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008947 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008948 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008949 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008950
Joe Onoratoabded112016-02-08 16:49:39 -08008951 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8952 mBsi = bsi;
8953 mUid = uid;
8954 }
8955
Adam Lesinski9425fe22015-06-19 12:02:13 -07008956 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8958 * proper timer pool from the given BatteryStatsImpl object.
8959 *
8960 * @param in the Parcel to be read from.
8961 * return a new Timer, or null.
8962 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008963 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8964 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 if (in.readInt() == 0) {
8966 return null;
8967 }
8968
Joe Onoratoabded112016-02-08 16:49:39 -08008969 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008970 }
8971
Joe Onorato92fd23f2016-07-25 11:18:42 -07008972 /**
8973 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8974 * proper timer pool from the given BatteryStatsImpl object.
8975 *
8976 * @param in the Parcel to be read from.
8977 * return a new Timer, or null.
8978 */
Bookatz5b5ec322017-05-26 09:40:38 -07008979 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8980 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008981 if (in.readInt() == 0) {
8982 return null;
8983 }
8984
Bookatz5b5ec322017-05-26 09:40:38 -07008985 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008986 }
8987
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008988 boolean reset() {
8989 boolean wlactive = false;
8990 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008991 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008992 }
8993 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008994 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008995 }
8996 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008997 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008998 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008999 if (mTimerDraw != null) {
9000 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009001 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009002 if (!wlactive) {
9003 if (mTimerFull != null) {
9004 mTimerFull.detach();
9005 mTimerFull = null;
9006 }
9007 if (mTimerPartial != null) {
9008 mTimerPartial.detach();
9009 mTimerPartial = null;
9010 }
9011 if (mTimerWindow != null) {
9012 mTimerWindow.detach();
9013 mTimerWindow = null;
9014 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009015 if (mTimerDraw != null) {
9016 mTimerDraw.detach();
9017 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07009018 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009019 }
9020 return !wlactive;
9021 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009022
Bookatz5b5ec322017-05-26 09:40:38 -07009023 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
9024 TimeBase screenOffBgTimeBase, Parcel in) {
9025 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
9026 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07009027 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
9028 mBsi.mFullTimers, timeBase, in);
9029 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
9030 mBsi.mWindowTimers, timeBase, in);
9031 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
9032 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009033 }
9034
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009035 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
9036 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
9037 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
9038 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009039 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009040 }
9041
9042 @Override
9043 public Timer getWakeTime(int type) {
9044 switch (type) {
9045 case WAKE_TYPE_FULL: return mTimerFull;
9046 case WAKE_TYPE_PARTIAL: return mTimerPartial;
9047 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07009048 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009049 default: throw new IllegalArgumentException("type = " + type);
9050 }
9051 }
9052 }
9053
Joe Onoratoabded112016-02-08 16:49:39 -08009054 public static class Sensor extends BatteryStats.Uid.Sensor {
9055 /**
9056 * BatteryStatsImpl that we are associated with.
9057 */
9058 protected BatteryStatsImpl mBsi;
9059
9060 /**
Bookatz867c0d72017-03-07 18:23:42 -08009061 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08009062 */
9063 protected Uid mUid;
9064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08009066 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009067
Joe Onoratoabded112016-02-08 16:49:39 -08009068 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
9069 mBsi = bsi;
9070 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009071 mHandle = handle;
9072 }
9073
Bookatz867c0d72017-03-07 18:23:42 -08009074 private DualTimer readTimersFromParcel(
9075 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009076 if (in.readInt() == 0) {
9077 return null;
9078 }
9079
Joe Onoratoabded112016-02-08 16:49:39 -08009080 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009081 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009082 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009083 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 }
Bookatz867c0d72017-03-07 18:23:42 -08009085 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009086 }
9087
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009088 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009089 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009090 mTimer = null;
9091 return true;
9092 }
9093 return false;
9094 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009095
Bookatz867c0d72017-03-07 18:23:42 -08009096 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
9097 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009098 }
9099
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009100 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009101 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009102 }
9103
9104 @Override
9105 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07009106 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009107 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009108
9109 @Override
Bookatz867c0d72017-03-07 18:23:42 -08009110 public Timer getSensorBackgroundTime() {
9111 if (mTimer == null) {
9112 return null;
9113 }
9114 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08009115 }
9116
9117 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009118 public int getHandle() {
9119 return mHandle;
9120 }
9121 }
9122
9123 /**
9124 * The statistics associated with a particular process.
9125 */
Joe Onoratoabded112016-02-08 16:49:39 -08009126 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
9127 /**
9128 * BatteryStatsImpl that we are associated with.
9129 */
9130 protected BatteryStatsImpl mBsi;
9131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009132 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009133 * The name of this process.
9134 */
9135 final String mName;
9136
9137 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08009138 * Remains true until removed from the stats.
9139 */
9140 boolean mActive = true;
9141
9142 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009143 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009144 */
9145 long mUserTime;
9146
9147 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009148 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 */
9150 long mSystemTime;
9151
9152 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07009153 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009154 */
9155 long mForegroundTime;
9156
9157 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009158 * Number of times the process has been started.
9159 */
9160 int mStarts;
9161
9162 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009163 * Number of times the process has crashed.
9164 */
9165 int mNumCrashes;
9166
9167 /**
9168 * Number of times the process has had an ANR.
9169 */
9170 int mNumAnrs;
9171
9172 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009173 * The amount of user time loaded from a previous save.
9174 */
9175 long mLoadedUserTime;
9176
9177 /**
9178 * The amount of system time loaded from a previous save.
9179 */
9180 long mLoadedSystemTime;
9181
9182 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009183 * The amount of foreground time loaded from a previous save.
9184 */
9185 long mLoadedForegroundTime;
9186
9187 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009188 * The number of times the process has started from a previous save.
9189 */
9190 int mLoadedStarts;
9191
9192 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009193 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009194 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009195 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009196
9197 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009198 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009199 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009200 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009201
9202 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009203 * The amount of user time when last unplugged.
9204 */
9205 long mUnpluggedUserTime;
9206
9207 /**
9208 * The amount of system time when last unplugged.
9209 */
9210 long mUnpluggedSystemTime;
9211
9212 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009213 * The amount of foreground time since unplugged.
9214 */
9215 long mUnpluggedForegroundTime;
9216
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009217 /**
9218 * The number of times the process has started before unplugged.
9219 */
9220 int mUnpluggedStarts;
9221
Dianne Hackborn61659e52014-07-09 16:13:01 -07009222 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009223 * Number of times the process has crashed before unplugged.
9224 */
9225 int mUnpluggedNumCrashes;
9226
9227 /**
9228 * Number of times the process has had an ANR before unplugged.
9229 */
9230 int mUnpluggedNumAnrs;
9231
Dianne Hackborn287952c2010-09-22 22:34:31 -07009232 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009233
Joe Onoratoabded112016-02-08 16:49:39 -08009234 public Proc(BatteryStatsImpl bsi, String name) {
9235 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009236 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08009237 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009238 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009239
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009240 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009241 mUnpluggedUserTime = mUserTime;
9242 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009243 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009244 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009245 mUnpluggedNumCrashes = mNumCrashes;
9246 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009247 }
9248
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009249 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009250 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009251
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009252 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009253 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009254 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009255 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009256
Dianne Hackborn287952c2010-09-22 22:34:31 -07009257 public int countExcessivePowers() {
9258 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009259 }
9260
Dianne Hackborn287952c2010-09-22 22:34:31 -07009261 public ExcessivePower getExcessivePower(int i) {
9262 if (mExcessivePower != null) {
9263 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009264 }
9265 return null;
9266 }
9267
Dianne Hackborn287952c2010-09-22 22:34:31 -07009268 public void addExcessiveCpu(long overTime, long usedTime) {
9269 if (mExcessivePower == null) {
9270 mExcessivePower = new ArrayList<ExcessivePower>();
9271 }
9272 ExcessivePower ew = new ExcessivePower();
9273 ew.type = ExcessivePower.TYPE_CPU;
9274 ew.overTime = overTime;
9275 ew.usedTime = usedTime;
9276 mExcessivePower.add(ew);
9277 }
9278
9279 void writeExcessivePowerToParcelLocked(Parcel out) {
9280 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009281 out.writeInt(0);
9282 return;
9283 }
9284
Dianne Hackborn287952c2010-09-22 22:34:31 -07009285 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009286 out.writeInt(N);
9287 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009288 ExcessivePower ew = mExcessivePower.get(i);
9289 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009290 out.writeLong(ew.overTime);
9291 out.writeLong(ew.usedTime);
9292 }
9293 }
9294
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009295 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009296 final int N = in.readInt();
9297 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009298 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009299 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009300 }
9301
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009302 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009303 throw new ParcelFormatException(
9304 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009305 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009306
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009307 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009308 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009309 ExcessivePower ew = new ExcessivePower();
9310 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009311 ew.overTime = in.readLong();
9312 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009313 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009314 }
9315 }
9316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 void writeToParcelLocked(Parcel out) {
9318 out.writeLong(mUserTime);
9319 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009320 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009321 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009322 out.writeInt(mNumCrashes);
9323 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009324 out.writeLong(mLoadedUserTime);
9325 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009326 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009327 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009328 out.writeInt(mLoadedNumCrashes);
9329 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009330 out.writeLong(mUnpluggedUserTime);
9331 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009332 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009333 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009334 out.writeInt(mUnpluggedNumCrashes);
9335 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009336 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337 }
9338
9339 void readFromParcelLocked(Parcel in) {
9340 mUserTime = in.readLong();
9341 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009342 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009343 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009344 mNumCrashes = in.readInt();
9345 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346 mLoadedUserTime = in.readLong();
9347 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009348 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009349 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009350 mLoadedNumCrashes = in.readInt();
9351 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 mUnpluggedUserTime = in.readLong();
9353 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009354 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009355 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009356 mUnpluggedNumCrashes = in.readInt();
9357 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009358 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009359 }
9360
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009361 public void addCpuTimeLocked(int utime, int stime) {
Sudheer Shankac57729a2018-02-09 15:44:42 -08009362 addCpuTimeLocked(utime, stime, mBsi.mOnBatteryTimeBase.isRunning());
9363 }
9364
9365 public void addCpuTimeLocked(int utime, int stime, boolean isRunning) {
9366 if (isRunning) {
9367 mUserTime += utime;
9368 mSystemTime += stime;
9369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009370 }
9371
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009372 public void addForegroundTimeLocked(long ttime) {
9373 mForegroundTime += ttime;
9374 }
9375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009376 public void incStartsLocked() {
9377 mStarts++;
9378 }
9379
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009380 public void incNumCrashesLocked() {
9381 mNumCrashes++;
9382 }
9383
9384 public void incNumAnrsLocked() {
9385 mNumAnrs++;
9386 }
9387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009388 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009389 public boolean isActive() {
9390 return mActive;
9391 }
9392
9393 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009394 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009395 long val = mUserTime;
9396 if (which == STATS_CURRENT) {
9397 val -= mLoadedUserTime;
9398 } else if (which == STATS_SINCE_UNPLUGGED) {
9399 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009400 }
9401 return val;
9402 }
9403
9404 @Override
9405 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009406 long val = mSystemTime;
9407 if (which == STATS_CURRENT) {
9408 val -= mLoadedSystemTime;
9409 } else if (which == STATS_SINCE_UNPLUGGED) {
9410 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009411 }
9412 return val;
9413 }
9414
9415 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009416 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009417 long val = mForegroundTime;
9418 if (which == STATS_CURRENT) {
9419 val -= mLoadedForegroundTime;
9420 } else if (which == STATS_SINCE_UNPLUGGED) {
9421 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009422 }
9423 return val;
9424 }
9425
9426 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009427 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009428 int val = mStarts;
9429 if (which == STATS_CURRENT) {
9430 val -= mLoadedStarts;
9431 } else if (which == STATS_SINCE_UNPLUGGED) {
9432 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009433 }
9434 return val;
9435 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009436
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009437 @Override
9438 public int getNumCrashes(int which) {
9439 int val = mNumCrashes;
9440 if (which == STATS_CURRENT) {
9441 val -= mLoadedNumCrashes;
9442 } else if (which == STATS_SINCE_UNPLUGGED) {
9443 val -= mUnpluggedNumCrashes;
9444 }
9445 return val;
9446 }
9447
9448 @Override
9449 public int getNumAnrs(int which) {
9450 int val = mNumAnrs;
9451 if (which == STATS_CURRENT) {
9452 val -= mLoadedNumAnrs;
9453 } else if (which == STATS_SINCE_UNPLUGGED) {
9454 val -= mUnpluggedNumAnrs;
9455 }
9456 return val;
9457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009458 }
9459
9460 /**
9461 * The statistics associated with a particular package.
9462 */
Joe Onoratoabded112016-02-08 16:49:39 -08009463 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9464 /**
9465 * BatteryStatsImpl that we are associated with.
9466 */
9467 protected BatteryStatsImpl mBsi;
9468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009469 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009470 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009471 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009472 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009473 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009474
9475 /**
9476 * The statics we have collected for this package's services.
9477 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009478 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009479
Joe Onoratoabded112016-02-08 16:49:39 -08009480 public Pkg(BatteryStatsImpl bsi) {
9481 mBsi = bsi;
9482 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009483 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009484
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009485 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486 }
9487
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009488 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009489 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009490
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009491 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009492 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009493 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009495 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009496 int numWA = in.readInt();
9497 mWakeupAlarms.clear();
9498 for (int i=0; i<numWA; i++) {
9499 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009500 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009502
9503 int numServs = in.readInt();
9504 mServiceStats.clear();
9505 for (int m = 0; m < numServs; m++) {
9506 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009507 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009508 mServiceStats.put(serviceName, serv);
9509
9510 serv.readFromParcelLocked(in);
9511 }
9512 }
9513
9514 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009515 int numWA = mWakeupAlarms.size();
9516 out.writeInt(numWA);
9517 for (int i=0; i<numWA; i++) {
9518 out.writeString(mWakeupAlarms.keyAt(i));
9519 mWakeupAlarms.valueAt(i).writeToParcel(out);
9520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009521
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009522 final int NS = mServiceStats.size();
9523 out.writeInt(NS);
9524 for (int i=0; i<NS; i++) {
9525 out.writeString(mServiceStats.keyAt(i));
9526 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009527 serv.writeToParcelLocked(out);
9528 }
9529 }
9530
9531 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009532 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9533 return mWakeupAlarms;
9534 }
9535
9536 public void noteWakeupAlarmLocked(String tag) {
9537 Counter c = mWakeupAlarms.get(tag);
9538 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009539 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009540 mWakeupAlarms.put(tag, c);
9541 }
9542 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009543 }
9544
9545 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009546 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9547 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009548 }
9549
9550 /**
9551 * The statistics associated with a particular service.
9552 */
Joe Onoratoabded112016-02-08 16:49:39 -08009553 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9554 /**
9555 * BatteryStatsImpl that we are associated with.
9556 */
9557 protected BatteryStatsImpl mBsi;
9558
9559 /**
9560 * The android package in which this service resides.
9561 */
9562 protected Pkg mPkg;
9563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009564 /**
9565 * Total time (ms in battery uptime) the service has been left started.
9566 */
Joe Onoratoabded112016-02-08 16:49:39 -08009567 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009568
9569 /**
9570 * If service has been started and not yet stopped, this is
9571 * when it was started.
9572 */
Joe Onoratoabded112016-02-08 16:49:39 -08009573 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574
9575 /**
9576 * True if we are currently running.
9577 */
Joe Onoratoabded112016-02-08 16:49:39 -08009578 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009579
9580 /**
9581 * Total number of times startService() has been called.
9582 */
Joe Onoratoabded112016-02-08 16:49:39 -08009583 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009584
9585 /**
9586 * Total time (ms in battery uptime) the service has been left launched.
9587 */
Joe Onoratoabded112016-02-08 16:49:39 -08009588 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009589
9590 /**
9591 * If service has been launched and not yet exited, this is
9592 * when it was launched (ms in battery uptime).
9593 */
Joe Onoratoabded112016-02-08 16:49:39 -08009594 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009595
9596 /**
9597 * True if we are currently launched.
9598 */
Joe Onoratoabded112016-02-08 16:49:39 -08009599 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009600
9601 /**
9602 * Total number times the service has been launched.
9603 */
Joe Onoratoabded112016-02-08 16:49:39 -08009604 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009605
9606 /**
9607 * The amount of time spent started loaded from a previous save
9608 * (ms in battery uptime).
9609 */
Joe Onoratoabded112016-02-08 16:49:39 -08009610 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009611
9612 /**
9613 * The number of starts loaded from a previous save.
9614 */
Joe Onoratoabded112016-02-08 16:49:39 -08009615 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009616
9617 /**
9618 * The number of launches loaded from a previous save.
9619 */
Joe Onoratoabded112016-02-08 16:49:39 -08009620 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009621
9622 /**
9623 * The amount of time spent started as of the last run (ms
9624 * in battery uptime).
9625 */
Joe Onoratoabded112016-02-08 16:49:39 -08009626 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009627
9628 /**
9629 * The number of starts as of the last run.
9630 */
Joe Onoratoabded112016-02-08 16:49:39 -08009631 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009632
9633 /**
9634 * The number of launches as of the last run.
9635 */
Joe Onoratoabded112016-02-08 16:49:39 -08009636 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009637
9638 /**
9639 * The amount of time spent started when last unplugged (ms
9640 * in battery uptime).
9641 */
Joe Onoratoabded112016-02-08 16:49:39 -08009642 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009643
9644 /**
9645 * The number of starts when last unplugged.
9646 */
Joe Onoratoabded112016-02-08 16:49:39 -08009647 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009648
9649 /**
9650 * The number of launches when last unplugged.
9651 */
Joe Onoratoabded112016-02-08 16:49:39 -08009652 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009653
Joe Onoratoabded112016-02-08 16:49:39 -08009654 /**
9655 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9656 */
9657 public Serv(BatteryStatsImpl bsi) {
9658 mBsi = bsi;
9659 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009660 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009661
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009662 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9663 long baseRealtime) {
9664 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009665 mUnpluggedStarts = mStarts;
9666 mUnpluggedLaunches = mLaunches;
9667 }
9668
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009669 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9670 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009671 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009672
Joe Onoratoabded112016-02-08 16:49:39 -08009673 /**
9674 * Remove this Serv as a listener from the time base.
9675 */
9676 public void detach() {
9677 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009678 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009679
Joe Onoratoabded112016-02-08 16:49:39 -08009680 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009681 mStartTime = in.readLong();
9682 mRunningSince = in.readLong();
9683 mRunning = in.readInt() != 0;
9684 mStarts = in.readInt();
9685 mLaunchedTime = in.readLong();
9686 mLaunchedSince = in.readLong();
9687 mLaunched = in.readInt() != 0;
9688 mLaunches = in.readInt();
9689 mLoadedStartTime = in.readLong();
9690 mLoadedStarts = in.readInt();
9691 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009692 mLastStartTime = 0;
9693 mLastStarts = 0;
9694 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009695 mUnpluggedStartTime = in.readLong();
9696 mUnpluggedStarts = in.readInt();
9697 mUnpluggedLaunches = in.readInt();
9698 }
9699
Joe Onoratoabded112016-02-08 16:49:39 -08009700 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009701 out.writeLong(mStartTime);
9702 out.writeLong(mRunningSince);
9703 out.writeInt(mRunning ? 1 : 0);
9704 out.writeInt(mStarts);
9705 out.writeLong(mLaunchedTime);
9706 out.writeLong(mLaunchedSince);
9707 out.writeInt(mLaunched ? 1 : 0);
9708 out.writeInt(mLaunches);
9709 out.writeLong(mLoadedStartTime);
9710 out.writeInt(mLoadedStarts);
9711 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009712 out.writeLong(mUnpluggedStartTime);
9713 out.writeInt(mUnpluggedStarts);
9714 out.writeInt(mUnpluggedLaunches);
9715 }
9716
Joe Onoratoabded112016-02-08 16:49:39 -08009717 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009718 if (!mLaunched) return mLaunchedTime;
9719 return mLaunchedTime + batteryUptime - mLaunchedSince;
9720 }
9721
Joe Onoratoabded112016-02-08 16:49:39 -08009722 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009723 if (!mRunning) return mStartTime;
9724 return mStartTime + batteryUptime - mRunningSince;
9725 }
9726
9727 public void startLaunchedLocked() {
9728 if (!mLaunched) {
9729 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009730 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009731 mLaunched = true;
9732 }
9733 }
9734
9735 public void stopLaunchedLocked() {
9736 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009737 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009738 if (time > 0) {
9739 mLaunchedTime += time;
9740 } else {
9741 mLaunches--;
9742 }
9743 mLaunched = false;
9744 }
9745 }
9746
9747 public void startRunningLocked() {
9748 if (!mRunning) {
9749 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009750 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009751 mRunning = true;
9752 }
9753 }
9754
9755 public void stopRunningLocked() {
9756 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009757 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009758 if (time > 0) {
9759 mStartTime += time;
9760 } else {
9761 mStarts--;
9762 }
9763 mRunning = false;
9764 }
9765 }
9766
9767 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009768 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009769 }
9770
9771 @Override
9772 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009773 int val = mLaunches;
9774 if (which == STATS_CURRENT) {
9775 val -= mLoadedLaunches;
9776 } else if (which == STATS_SINCE_UNPLUGGED) {
9777 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009779 return val;
9780 }
9781
9782 @Override
9783 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009784 long val = getStartTimeToNowLocked(now);
9785 if (which == STATS_CURRENT) {
9786 val -= mLoadedStartTime;
9787 } else if (which == STATS_SINCE_UNPLUGGED) {
9788 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009790 return val;
9791 }
9792
9793 @Override
9794 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009795 int val = mStarts;
9796 if (which == STATS_CURRENT) {
9797 val -= mLoadedStarts;
9798 } else if (which == STATS_SINCE_UNPLUGGED) {
9799 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009800 }
9801
9802 return val;
9803 }
9804 }
9805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009806 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009807 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009808 }
9809 }
9810
9811 /**
9812 * Retrieve the statistics object for a particular process, creating
9813 * if needed.
9814 */
9815 public Proc getProcessStatsLocked(String name) {
9816 Proc ps = mProcessStats.get(name);
9817 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009818 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009819 mProcessStats.put(name, ps);
9820 }
9821
9822 return ps;
9823 }
9824
Andreas Gampe3f24e692018-02-05 13:24:28 -08009825 @GuardedBy("mBsi")
Dianne Hackborna8d10942015-11-19 17:55:19 -08009826 public void updateUidProcessStateLocked(int procState) {
9827 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009828 // Make special note of Foreground Services
9829 final boolean userAwareService =
9830 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009831 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009832
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009833 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9834 return;
9835 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009836
Bookatz867c0d72017-03-07 18:23:42 -08009837 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009838 if (mProcessState != uidRunningState) {
9839 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009840
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009841 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9842 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009843
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009844 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009845 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009846 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9847 mBsi.mOnBatteryTimeBase.isRunning(),
Sudheer Shankac20379e2018-02-15 00:06:21 -08009848 mBsi.mOnBatteryScreenOffTimeBase.isRunning(),
9849 mBsi.mConstants.PROC_STATE_CPU_TIMES_READ_DELAY_MS);
9850 mBsi.mNumCpuTimeReads++;
9851 } else {
9852 mBsi.mNumBatchedCpuTimeReads++;
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009853 }
9854 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9855 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9856 mBsi.mPendingUids.put(mUid, mProcessState);
9857 }
9858 } else {
9859 mBsi.mPendingUids.clear();
9860 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009861 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009862 mProcessState = uidRunningState;
9863 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9864 if (mProcessStateTimer[uidRunningState] == null) {
9865 makeProcessState(uidRunningState, null);
9866 }
9867 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9868 }
9869
9870 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9871 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009872 }
Bookatz867c0d72017-03-07 18:23:42 -08009873
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009874 if (userAwareService != mInForegroundService) {
9875 if (userAwareService) {
9876 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9877 } else {
9878 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9879 }
9880 mInForegroundService = userAwareService;
9881 }
Bookatz867c0d72017-03-07 18:23:42 -08009882 }
9883
Bookatzc8c44962017-05-11 12:12:54 -07009884 /** Whether to consider Uid to be in the background for background timebase purposes. */
9885 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009886 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9887 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009888 return mProcessState >= PROCESS_STATE_BACKGROUND;
9889 }
9890
9891 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9892 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9893 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9894 }
9895
9896 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9897 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9898 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009899 }
9900
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009901 public SparseArray<? extends Pid> getPidStats() {
9902 return mPids;
9903 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009904
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009905 public Pid getPidStatsLocked(int pid) {
9906 Pid p = mPids.get(pid);
9907 if (p == null) {
9908 p = new Pid();
9909 mPids.put(pid, p);
9910 }
9911 return p;
9912 }
9913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009914 /**
9915 * Retrieve the statistics object for a particular service, creating
9916 * if needed.
9917 */
9918 public Pkg getPackageStatsLocked(String name) {
9919 Pkg ps = mPackageStats.get(name);
9920 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009921 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009922 mPackageStats.put(name, ps);
9923 }
9924
9925 return ps;
9926 }
9927
9928 /**
9929 * Retrieve the statistics object for a particular service, creating
9930 * if needed.
9931 */
9932 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9933 Pkg ps = getPackageStatsLocked(pkg);
9934 Pkg.Serv ss = ps.mServiceStats.get(serv);
9935 if (ss == null) {
9936 ss = ps.newServiceStatsLocked();
9937 ps.mServiceStats.put(serv, ss);
9938 }
9939
9940 return ss;
9941 }
9942
Dianne Hackbornd953c532014-08-16 18:17:38 -07009943 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009944 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009945 timer.readSummaryFromParcelLocked(in);
9946 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009947 }
9948
Dianne Hackbornd953c532014-08-16 18:17:38 -07009949 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009950 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009951 timer.readSummaryFromParcelLocked(in);
9952 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009953 }
9954
Dianne Hackbornd953c532014-08-16 18:17:38 -07009955 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009956 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009957 mWakelockStats.add(wlName, wl);
9958 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009959 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009960 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009961 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009962 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009963 }
9964 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009965 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009966 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009967 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009968 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009970 }
9971
Bookatz867c0d72017-03-07 18:23:42 -08009972 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009973 Sensor se = mSensorStats.get(sensor);
9974 if (se == null) {
9975 if (!create) {
9976 return null;
9977 }
Joe Onoratoabded112016-02-08 16:49:39 -08009978 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009979 mSensorStats.put(sensor, se);
9980 }
Bookatz867c0d72017-03-07 18:23:42 -08009981 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009982 if (t != null) {
9983 return t;
9984 }
Joe Onoratoabded112016-02-08 16:49:39 -08009985 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009986 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009987 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009988 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009989 }
Bookatz867c0d72017-03-07 18:23:42 -08009990 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9991 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009992 se.mTimer = t;
9993 return t;
9994 }
9995
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009996 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009997 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009998 if (t != null) {
9999 t.startRunningLocked(elapsedRealtimeMs);
Bookatz90867622018-01-31 15:05:57 -080010000 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name,
10001 StatsLog.SYNC_STATE_CHANGED__STATE__ON);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010002 }
10003 }
10004
10005 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -070010006 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010007 if (t != null) {
10008 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -070010009 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Bookatz90867622018-01-31 15:05:57 -080010010 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name,
10011 StatsLog.SYNC_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -070010012 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010013 }
10014 }
10015
10016 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -070010017 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010018 if (t != null) {
10019 t.startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -080010020 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -080010021 name, StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__STARTED);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010022 }
10023 }
10024
Dianne Hackborn94326cb2017-06-28 16:17:20 -070010025 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -070010026 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010027 if (t != null) {
10028 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -070010029 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -080010030 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -080010031 name, StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__FINISHED);
Bookatzc1a050a2017-10-10 15:49:28 -070010032 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010033 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -070010034 if (mBsi.mOnBatteryTimeBase.isRunning()) {
10035 SparseIntArray types = mJobCompletions.get(name);
10036 if (types == null) {
10037 types = new SparseIntArray();
10038 mJobCompletions.put(name, types);
10039 }
10040 int last = types.get(stopReason, 0);
10041 types.put(stopReason, last + 1);
10042 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070010043 }
10044
Bookatz5b5ec322017-05-26 09:40:38 -070010045 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
10046 if (wl == null) {
10047 return null;
10048 }
10049 switch (type) {
10050 case WAKE_TYPE_PARTIAL: {
10051 DualTimer t = wl.mTimerPartial;
10052 if (t == null) {
10053 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
10054 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
10055 mOnBatteryScreenOffBackgroundTimeBase);
10056 wl.mTimerPartial = t;
10057 }
10058 return t;
10059 }
10060 case WAKE_TYPE_FULL: {
10061 StopwatchTimer t = wl.mTimerFull;
10062 if (t == null) {
10063 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
10064 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
10065 wl.mTimerFull = t;
10066 }
10067 return t;
10068 }
10069 case WAKE_TYPE_WINDOW: {
10070 StopwatchTimer t = wl.mTimerWindow;
10071 if (t == null) {
10072 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
10073 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
10074 wl.mTimerWindow = t;
10075 }
10076 return t;
10077 }
10078 case WAKE_TYPE_DRAW: {
10079 StopwatchTimer t = wl.mTimerDraw;
10080 if (t == null) {
10081 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
10082 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
10083 wl.mTimerDraw = t;
10084 }
10085 return t;
10086 }
10087 default:
10088 throw new IllegalArgumentException("type=" + type);
10089 }
10090 }
10091
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010092 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010093 Wakelock wl = mWakelockStats.startObject(name);
10094 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -070010095 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010096 }
Bookatzc8c44962017-05-11 12:12:54 -070010097 if (type == WAKE_TYPE_PARTIAL) {
10098 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
10099 if (pid >= 0) {
10100 Pid p = getPidStatsLocked(pid);
10101 if (p.mWakeNesting++ == 0) {
10102 p.mWakeStartMs = elapsedRealtimeMs;
10103 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -070010104 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010106 }
10107
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010108 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070010109 Wakelock wl = mWakelockStats.stopObject(name);
10110 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -070010111 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
10112 wlt.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010113 }
Bookatzc8c44962017-05-11 12:12:54 -070010114 if (type == WAKE_TYPE_PARTIAL) {
10115 if (mAggregatedPartialWakelockTimer != null) {
10116 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
10117 }
10118 if (pid >= 0) {
10119 Pid p = mPids.get(pid);
10120 if (p != null && p.mWakeNesting > 0) {
10121 if (p.mWakeNesting-- == 1) {
10122 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
10123 p.mWakeStartMs = 0;
10124 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -080010125 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010126 }
10127 }
10128 }
10129
Dianne Hackborn287952c2010-09-22 22:34:31 -070010130 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
10131 Proc p = getProcessStatsLocked(proc);
10132 if (p != null) {
10133 p.addExcessiveCpu(overTime, usedTime);
10134 }
10135 }
10136
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010137 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010138 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -080010139 t.startRunningLocked(elapsedRealtimeMs);
Narayan Kamath32684dd2018-01-08 17:32:51 +000010140 if (sensor != Sensor.GPS) {
Yangster-mac2f5daec2018-01-16 10:23:15 -080010141 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null, sensor,
Bookatz90867622018-01-31 15:05:57 -080010142 StatsLog.SENSOR_STATE_CHANGED__STATE__ON);
Bookatzc1a050a2017-10-10 15:49:28 -070010143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010144 }
10145
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010146 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010147 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -080010148 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010149 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010150 t.stopRunningLocked(elapsedRealtimeMs);
Narayan Kamath32684dd2018-01-08 17:32:51 +000010151 if (sensor != Sensor.GPS) {
10152 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null,
Bookatz90867622018-01-31 15:05:57 -080010153 sensor, StatsLog.SENSOR_STATE_CHANGED__STATE__OFF);
Bookatzc1a050a2017-10-10 15:49:28 -070010154 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010156 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010157
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010158 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010159 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010160 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010161
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010162 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -080010163 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010164 }
10165
10166 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -080010167 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010168 }
10169 }
10170
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010171 public long[] getCpuFreqs() {
10172 return mCpuFreqs;
10173 }
10174
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010175 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
10176 UserInfoProvider userInfoProvider) {
10177 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010178 }
10179
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010180 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
10181 PlatformIdleStateCallback cb,
10182 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -080010183 init(clocks);
10184
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010185 if (systemDir != null) {
10186 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
10187 new File(systemDir, "batterystats.bin.tmp"));
10188 } else {
10189 mFile = null;
10190 }
10191 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010192 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -080010193 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010194 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010195 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -080010196 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010197 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -070010198 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010199 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010200 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010201 }
Joe Onoratoabded112016-02-08 16:49:39 -080010202 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
10203 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
10204 mOnBatteryTimeBase);
10205 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
10206 mOnBatteryTimeBase);
10207 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
10208 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
10209 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
10210 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
10211 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
10212 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
10213 mOnBatteryTimeBase);
10214 }
10215 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
10216 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010217 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010218 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010219 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -070010220 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010221 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010222 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
10223 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010224 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010225 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
10226 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10227 NUM_BT_TX_LEVELS);
10228 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
10229 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -080010230 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
10231 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
10232 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010233 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010234 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
10235 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010236 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
10237 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -080010238 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
10239 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010240 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080010241 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -070010242 mOnBatteryTimeBase);
10243 }
Joe Onoratoabded112016-02-08 16:49:39 -080010244 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10245 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
10246 mOnBatteryTimeBase);
10247 }
10248 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10249 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
10250 mOnBatteryTimeBase);
10251 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010252 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010253 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10254 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10255 mOnBatteryTimeBase);
10256 }
Joe Onoratoabded112016-02-08 16:49:39 -080010257 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10258 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10259 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10260 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10261 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010262 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010263 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010264 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10265 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010266 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010267 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010268 long uptime = mClocks.uptimeMillis() * 1000;
10269 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010270 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010271 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010272 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010273 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010274 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010275 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010276 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010277 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010278 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010279 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010280 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010281 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010282 }
10283
10284 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010285 this(new SystemClocks(), p);
10286 }
10287
10288 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10289 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010290 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010291 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010292 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010293 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010294 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010295 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010296 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010297 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010298 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010299 }
10300
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010301 public void setPowerProfileLocked(PowerProfile profile) {
10302 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010303
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010304 // We need to initialize the KernelCpuSpeedReaders to read from
10305 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10306 // information.
10307 final int numClusters = mPowerProfile.getNumCpuClusters();
10308 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10309 int firstCpuOfCluster = 0;
10310 for (int i = 0; i < numClusters; i++) {
10311 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10312 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10313 numSpeedSteps);
10314 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10315 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010316
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010317 if (mEstimatedBatteryCapacity == -1) {
10318 // Initialize the estimated battery capacity to a known preset one.
10319 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010320 }
10321 }
10322
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010323 public void setCallback(BatteryCallback cb) {
10324 mCallback = cb;
10325 }
10326
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010327 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010328 if (mPhoneSignalScanningTimer != null) {
10329 mPhoneSignalScanningTimer.setTimeout(timeout);
10330 }
10331 }
10332
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010333 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10334 mExternalSync = sync;
10335 }
10336
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010337 public void updateDailyDeadlineLocked() {
10338 // Get the current time.
10339 long currentTime = mDailyStartTime = System.currentTimeMillis();
10340 Calendar calDeadline = Calendar.getInstance();
10341 calDeadline.setTimeInMillis(currentTime);
10342
10343 // Move time up to the next day, ranging from 1am to 3pm.
10344 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10345 calDeadline.set(Calendar.MILLISECOND, 0);
10346 calDeadline.set(Calendar.SECOND, 0);
10347 calDeadline.set(Calendar.MINUTE, 0);
10348 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10349 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10350 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10351 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10352 }
10353
10354 public void recordDailyStatsIfNeededLocked(boolean settled) {
10355 long currentTime = System.currentTimeMillis();
10356 if (currentTime >= mNextMaxDailyDeadline) {
10357 recordDailyStatsLocked();
10358 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10359 recordDailyStatsLocked();
10360 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10361 recordDailyStatsLocked();
10362 }
10363 }
10364
10365 public void recordDailyStatsLocked() {
10366 DailyItem item = new DailyItem();
10367 item.mStartTime = mDailyStartTime;
10368 item.mEndTime = System.currentTimeMillis();
10369 boolean hasData = false;
10370 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10371 hasData = true;
10372 item.mDischargeSteps = new LevelStepTracker(
10373 mDailyDischargeStepTracker.mNumStepDurations,
10374 mDailyDischargeStepTracker.mStepDurations);
10375 }
10376 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10377 hasData = true;
10378 item.mChargeSteps = new LevelStepTracker(
10379 mDailyChargeStepTracker.mNumStepDurations,
10380 mDailyChargeStepTracker.mStepDurations);
10381 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010382 if (mDailyPackageChanges != null) {
10383 hasData = true;
10384 item.mPackageChanges = mDailyPackageChanges;
10385 mDailyPackageChanges = null;
10386 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010387 mDailyDischargeStepTracker.init();
10388 mDailyChargeStepTracker.init();
10389 updateDailyDeadlineLocked();
10390
10391 if (hasData) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010392 final long startTime = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010393 mDailyItems.add(item);
10394 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10395 mDailyItems.remove(0);
10396 }
10397 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10398 try {
10399 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010400 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010401 writeDailyItemsLocked(out);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010402 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010403 BackgroundThread.getHandler().post(new Runnable() {
10404 @Override
10405 public void run() {
10406 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080010407 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010408 FileOutputStream stream = null;
10409 try {
10410 stream = mDailyFile.startWrite();
10411 memStream.writeTo(stream);
10412 stream.flush();
10413 FileUtils.sync(stream);
10414 stream.close();
10415 mDailyFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080010416 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
10417 "batterystats-daily",
10418 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010419 } catch (IOException e) {
10420 Slog.w("BatteryStats",
10421 "Error writing battery daily items", e);
10422 mDailyFile.failWrite(stream);
10423 }
10424 }
10425 }
10426 });
10427 } catch (IOException e) {
10428 }
10429 }
10430 }
10431
10432 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10433 StringBuilder sb = new StringBuilder(64);
10434 out.startDocument(null, true);
10435 out.startTag(null, "daily-items");
10436 for (int i=0; i<mDailyItems.size(); i++) {
10437 final DailyItem dit = mDailyItems.get(i);
10438 out.startTag(null, "item");
10439 out.attribute(null, "start", Long.toString(dit.mStartTime));
10440 out.attribute(null, "end", Long.toString(dit.mEndTime));
10441 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10442 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010443 if (dit.mPackageChanges != null) {
10444 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10445 PackageChange pc = dit.mPackageChanges.get(j);
10446 if (pc.mUpdate) {
10447 out.startTag(null, "upd");
10448 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010449 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010450 out.endTag(null, "upd");
10451 } else {
10452 out.startTag(null, "rem");
10453 out.attribute(null, "pkg", pc.mPackageName);
10454 out.endTag(null, "rem");
10455 }
10456 }
10457 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010458 out.endTag(null, "item");
10459 }
10460 out.endTag(null, "daily-items");
10461 out.endDocument();
10462 }
10463
10464 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10465 StringBuilder tmpBuilder) throws IOException {
10466 if (steps != null) {
10467 out.startTag(null, tag);
10468 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10469 for (int i=0; i<steps.mNumStepDurations; i++) {
10470 out.startTag(null, "s");
10471 tmpBuilder.setLength(0);
10472 steps.encodeEntryAt(i, tmpBuilder);
10473 out.attribute(null, "v", tmpBuilder.toString());
10474 out.endTag(null, "s");
10475 }
10476 out.endTag(null, tag);
10477 }
10478 }
10479
10480 public void readDailyStatsLocked() {
10481 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10482 mDailyItems.clear();
10483 FileInputStream stream;
10484 try {
10485 stream = mDailyFile.openRead();
10486 } catch (FileNotFoundException e) {
10487 return;
10488 }
10489 try {
10490 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010491 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010492 readDailyItemsLocked(parser);
10493 } catch (XmlPullParserException e) {
10494 } finally {
10495 try {
10496 stream.close();
10497 } catch (IOException e) {
10498 }
10499 }
10500 }
10501
10502 private void readDailyItemsLocked(XmlPullParser parser) {
10503 try {
10504 int type;
10505 while ((type = parser.next()) != XmlPullParser.START_TAG
10506 && type != XmlPullParser.END_DOCUMENT) {
10507 ;
10508 }
10509
10510 if (type != XmlPullParser.START_TAG) {
10511 throw new IllegalStateException("no start tag found");
10512 }
10513
10514 int outerDepth = parser.getDepth();
10515 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10516 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10517 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10518 continue;
10519 }
10520
10521 String tagName = parser.getName();
10522 if (tagName.equals("item")) {
10523 readDailyItemTagLocked(parser);
10524 } else {
10525 Slog.w(TAG, "Unknown element under <daily-items>: "
10526 + parser.getName());
10527 XmlUtils.skipCurrentTag(parser);
10528 }
10529 }
10530
10531 } catch (IllegalStateException e) {
10532 Slog.w(TAG, "Failed parsing daily " + e);
10533 } catch (NullPointerException e) {
10534 Slog.w(TAG, "Failed parsing daily " + e);
10535 } catch (NumberFormatException e) {
10536 Slog.w(TAG, "Failed parsing daily " + e);
10537 } catch (XmlPullParserException e) {
10538 Slog.w(TAG, "Failed parsing daily " + e);
10539 } catch (IOException e) {
10540 Slog.w(TAG, "Failed parsing daily " + e);
10541 } catch (IndexOutOfBoundsException e) {
10542 Slog.w(TAG, "Failed parsing daily " + e);
10543 }
10544 }
10545
10546 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10547 XmlPullParserException, IOException {
10548 DailyItem dit = new DailyItem();
10549 String attr = parser.getAttributeValue(null, "start");
10550 if (attr != null) {
10551 dit.mStartTime = Long.parseLong(attr);
10552 }
10553 attr = parser.getAttributeValue(null, "end");
10554 if (attr != null) {
10555 dit.mEndTime = Long.parseLong(attr);
10556 }
10557 int outerDepth = parser.getDepth();
10558 int type;
10559 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10560 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10561 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10562 continue;
10563 }
10564
10565 String tagName = parser.getName();
10566 if (tagName.equals("dis")) {
10567 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10568 } else if (tagName.equals("chg")) {
10569 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010570 } else if (tagName.equals("upd")) {
10571 if (dit.mPackageChanges == null) {
10572 dit.mPackageChanges = new ArrayList<>();
10573 }
10574 PackageChange pc = new PackageChange();
10575 pc.mUpdate = true;
10576 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10577 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010578 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010579 dit.mPackageChanges.add(pc);
10580 XmlUtils.skipCurrentTag(parser);
10581 } else if (tagName.equals("rem")) {
10582 if (dit.mPackageChanges == null) {
10583 dit.mPackageChanges = new ArrayList<>();
10584 }
10585 PackageChange pc = new PackageChange();
10586 pc.mUpdate = false;
10587 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10588 dit.mPackageChanges.add(pc);
10589 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010590 } else {
10591 Slog.w(TAG, "Unknown element under <item>: "
10592 + parser.getName());
10593 XmlUtils.skipCurrentTag(parser);
10594 }
10595 }
10596 mDailyItems.add(dit);
10597 }
10598
10599 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10600 String tag)
10601 throws NumberFormatException, XmlPullParserException, IOException {
10602 final String numAttr = parser.getAttributeValue(null, "n");
10603 if (numAttr == null) {
10604 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10605 XmlUtils.skipCurrentTag(parser);
10606 return;
10607 }
10608 final int num = Integer.parseInt(numAttr);
10609 LevelStepTracker steps = new LevelStepTracker(num);
10610 if (isCharge) {
10611 dit.mChargeSteps = steps;
10612 } else {
10613 dit.mDischargeSteps = steps;
10614 }
10615 int i = 0;
10616 int outerDepth = parser.getDepth();
10617 int type;
10618 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10619 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10620 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10621 continue;
10622 }
10623
10624 String tagName = parser.getName();
10625 if ("s".equals(tagName)) {
10626 if (i < num) {
10627 String valueAttr = parser.getAttributeValue(null, "v");
10628 if (valueAttr != null) {
10629 steps.decodeEntryAt(i, valueAttr);
10630 i++;
10631 }
10632 }
10633 } else {
10634 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10635 + parser.getName());
10636 XmlUtils.skipCurrentTag(parser);
10637 }
10638 }
10639 steps.mNumStepDurations = i;
10640 }
10641
10642 @Override
10643 public DailyItem getDailyItemLocked(int daysAgo) {
10644 int index = mDailyItems.size()-1-daysAgo;
10645 return index >= 0 ? mDailyItems.get(index) : null;
10646 }
10647
10648 @Override
10649 public long getCurrentDailyStartTime() {
10650 return mDailyStartTime;
10651 }
10652
10653 @Override
10654 public long getNextMinDailyDeadline() {
10655 return mNextMinDailyDeadline;
10656 }
10657
10658 @Override
10659 public long getNextMaxDailyDeadline() {
10660 return mNextMaxDailyDeadline;
10661 }
10662
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010663 @Override
10664 public boolean startIteratingOldHistoryLocked() {
10665 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10666 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010667 if ((mHistoryIterator = mHistory) == null) {
10668 return false;
10669 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010670 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010671 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010672 mReadOverflow = false;
10673 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010674 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010675 }
10676
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010677 @Override
10678 public boolean getNextOldHistoryLocked(HistoryItem out) {
10679 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10680 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010681 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010682 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010683 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010684 HistoryItem cur = mHistoryIterator;
10685 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010686 if (!mReadOverflow && !end) {
10687 Slog.w(TAG, "Old history ends before new history!");
10688 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010689 return false;
10690 }
10691 out.setTo(cur);
10692 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010693 if (!mReadOverflow) {
10694 if (end) {
10695 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010696 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010697 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010698 pw.println("Histories differ!");
10699 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010700 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010701 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010702 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10703 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010704 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010705 }
10706 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010707 return true;
10708 }
10709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010710 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010711 public void finishIteratingOldHistoryLocked() {
10712 mIteratingHistory = false;
10713 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010714 mHistoryIterator = null;
10715 }
10716
10717 public int getHistoryTotalSize() {
10718 return MAX_HISTORY_BUFFER;
10719 }
10720
10721 public int getHistoryUsedSize() {
10722 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010723 }
10724
10725 @Override
10726 public boolean startIteratingHistoryLocked() {
10727 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10728 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010729 if (mHistoryBuffer.dataSize() <= 0) {
10730 return false;
10731 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010732 mHistoryBuffer.setDataPosition(0);
10733 mReadOverflow = false;
10734 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010735 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10736 mReadHistoryUids = new int[mHistoryTagPool.size()];
10737 mReadHistoryChars = 0;
10738 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10739 final HistoryTag tag = ent.getKey();
10740 final int idx = ent.getValue();
10741 mReadHistoryStrings[idx] = tag.string;
10742 mReadHistoryUids[idx] = tag.uid;
10743 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010744 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010745 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010746 }
10747
10748 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010749 public int getHistoryStringPoolSize() {
10750 return mReadHistoryStrings.length;
10751 }
10752
10753 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010754 public int getHistoryStringPoolBytes() {
10755 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10756 // Each string character is 2 bytes.
10757 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10758 }
10759
10760 @Override
10761 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010762 return mReadHistoryStrings[index];
10763 }
10764
10765 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010766 public int getHistoryTagPoolUid(int index) {
10767 return mReadHistoryUids[index];
10768 }
10769
10770 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010771 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010772 final int pos = mHistoryBuffer.dataPosition();
10773 if (pos == 0) {
10774 out.clear();
10775 }
10776 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010777 if (end) {
10778 return false;
10779 }
10780
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010781 final long lastRealtime = out.time;
10782 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010783 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010784 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10785 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010786 out.currentTime = lastWalltime + (out.time - lastRealtime);
10787 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010788 return true;
10789 }
10790
10791 @Override
10792 public void finishIteratingHistoryLocked() {
10793 mIteratingHistory = false;
10794 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010795 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010796 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010797
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010798 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010799 public long getHistoryBaseTime() {
10800 return mHistoryBaseTime;
10801 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010802
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010803 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010804 public int getStartCount() {
10805 return mStartCount;
10806 }
10807
10808 public boolean isOnBattery() {
10809 return mOnBattery;
10810 }
10811
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010812 public boolean isCharging() {
10813 return mCharging;
10814 }
10815
Mike Mac2f518a2017-09-19 16:06:03 -070010816 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010817 return state == Display.STATE_ON || state == Display.STATE_VR
10818 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010819 }
10820
10821 public boolean isScreenOff(int state) {
10822 return state == Display.STATE_OFF;
10823 }
10824
10825 public boolean isScreenDoze(int state) {
10826 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010827 }
10828
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010829 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010830 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010831 mOnBatteryTimeBase.init(uptime, realtime);
10832 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010833 mRealtime = 0;
10834 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010835 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010836 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010837 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010838
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010839 void initDischarge() {
10840 mLowDischargeAmountSinceCharge = 0;
10841 mHighDischargeAmountSinceCharge = 0;
10842 mDischargeAmountScreenOn = 0;
10843 mDischargeAmountScreenOnSinceCharge = 0;
10844 mDischargeAmountScreenOff = 0;
10845 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010846 mDischargeAmountScreenDoze = 0;
10847 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010848 mDischargeStepTracker.init();
10849 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010850 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010851 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010852 mDischargeLightDozeCounter.reset(false);
10853 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010854 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010855 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010856
10857 public void resetAllStatsCmdLocked() {
10858 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010859 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010860 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010861 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010862 long realtime = mSecRealtime * 1000;
10863 mDischargeStartLevel = mHistoryCur.batteryLevel;
10864 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010865 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010866 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10867 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010868 mOnBatteryTimeBase.reset(uptime, realtime);
10869 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10870 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010871 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010872 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010873 mDischargeScreenDozeUnplugLevel = 0;
10874 mDischargeScreenOffUnplugLevel = 0;
10875 } else if (isScreenDoze(mScreenState)) {
10876 mDischargeScreenOnUnplugLevel = 0;
10877 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010878 mDischargeScreenOffUnplugLevel = 0;
10879 } else {
10880 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010881 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010882 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10883 }
10884 mDischargeAmountScreenOn = 0;
10885 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010886 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010887 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010888 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010889 }
10890
10891 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010892 final long uptimeMillis = mClocks.uptimeMillis();
10893 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010894 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010895 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010896 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010897 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010898 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010899 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010900 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010901
10902 if (mPowerProfile != null) {
10903 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10904 } else {
10905 mEstimatedBatteryCapacity = -1;
10906 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010907 mMinLearnedBatteryCapacity = -1;
10908 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010909 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010910 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010911 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010912 mLongestLightIdleTime = 0;
10913 mLongestFullIdleTime = 0;
10914 mDeviceIdleModeLightTimer.reset(false);
10915 mDeviceIdleModeFullTimer.reset(false);
10916 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010917 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010918 mPhoneOnTimer.reset(false);
10919 mAudioOnTimer.reset(false);
10920 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010921 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010922 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010923 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010924 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010925 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010926 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010927 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010928 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010929 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010930 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010931 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010932 mNetworkByteActivityCounters[i].reset(false);
10933 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010934 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010935 mMobileRadioActiveTimer.reset(false);
10936 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010937 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010938 mMobileRadioActiveUnknownTime.reset(false);
10939 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010940 mWifiOnTimer.reset(false);
10941 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010942 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010943 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010944 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010945 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10946 mWifiSupplStateTimer[i].reset(false);
10947 }
10948 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10949 mWifiSignalStrengthsTimer[i].reset(false);
10950 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010951 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010952 mWifiActiveTimer.reset(false);
10953 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010954 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10955 mGpsSignalQualityTimer[i].reset(false);
10956 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010957 mBluetoothActivity.reset(false);
10958 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010959 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010960
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010961 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010962 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010963 mUidStats.remove(mUidStats.keyAt(i));
10964 i--;
10965 }
10966 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010967
Bookatz50df7112017-08-04 14:53:26 -070010968 if (mRpmStats.size() > 0) {
10969 for (SamplingTimer timer : mRpmStats.values()) {
10970 mOnBatteryTimeBase.remove(timer);
10971 }
10972 mRpmStats.clear();
10973 }
10974 if (mScreenOffRpmStats.size() > 0) {
10975 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10976 mOnBatteryScreenOffTimeBase.remove(timer);
10977 }
10978 mScreenOffRpmStats.clear();
10979 }
10980
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010981 if (mKernelWakelockStats.size() > 0) {
10982 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010983 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010984 }
10985 mKernelWakelockStats.clear();
10986 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010987
James Carr3a226052016-07-01 14:49:52 -070010988 if (mKernelMemoryStats.size() > 0) {
10989 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10990 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10991 }
10992 mKernelMemoryStats.clear();
10993 }
10994
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010995 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010996 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10997 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010998 }
10999 mWakeupReasonStats.clear();
11000 }
11001
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080011002 mLastHistoryStepDetails = null;
11003 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
11004 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
11005 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
11006 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
11007 mLastStepStatUserTime = mCurStepStatUserTime = 0;
11008 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
11009 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
11010 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
11011 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
11012 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
11013
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011014 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011015
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011016 clearHistoryLocked();
11017 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011018
Dianne Hackborn40c87252014-03-19 16:55:40 -070011019 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011020 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011021 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
11022 // Not recording process starts/stops.
11023 continue;
11024 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070011025 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011026 if (active == null) {
11027 continue;
11028 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070011029 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
11030 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011031 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070011032 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
11033 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011034 }
11035 }
11036 }
11037 }
11038
Mike Mac2f518a2017-09-19 16:06:03 -070011039 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
11040 updateOldDischargeScreenLevelLocked(oldState);
11041 updateNewDischargeScreenLevelLocked(newState);
11042 }
11043
11044 private void updateOldDischargeScreenLevelLocked(int state) {
11045 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011046 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
11047 if (diff > 0) {
11048 mDischargeAmountScreenOn += diff;
11049 mDischargeAmountScreenOnSinceCharge += diff;
11050 }
Mike Mac2f518a2017-09-19 16:06:03 -070011051 } else if (isScreenDoze(state)) {
11052 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
11053 if (diff > 0) {
11054 mDischargeAmountScreenDoze += diff;
11055 mDischargeAmountScreenDozeSinceCharge += diff;
11056 }
11057 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011058 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
11059 if (diff > 0) {
11060 mDischargeAmountScreenOff += diff;
11061 mDischargeAmountScreenOffSinceCharge += diff;
11062 }
11063 }
Mike Mac2f518a2017-09-19 16:06:03 -070011064 }
11065
11066 private void updateNewDischargeScreenLevelLocked(int state) {
11067 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011068 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
11069 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011070 mDischargeScreenDozeUnplugLevel = 0;
11071 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011072 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011073 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
11074 mDischargeScreenOffUnplugLevel = 0;
11075 } else if (isScreenOff(state)) {
11076 mDischargeScreenOnUnplugLevel = 0;
11077 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011078 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
11079 }
11080 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011081
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011082 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011083 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070011084 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011085 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011086 }
11087
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011088 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
11089 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
11090
11091 private final Object mWifiNetworkLock = new Object();
11092
11093 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011094 private String[] mWifiIfaces = EmptyArray.STRING;
11095
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011096 @GuardedBy("mWifiNetworkLock")
11097 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011098
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011099 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011100
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011101 @GuardedBy("mModemNetworkLock")
11102 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011103
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011104 @GuardedBy("mModemNetworkLock")
11105 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
11106
11107 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
11108 try {
11109 if (!ArrayUtils.isEmpty(ifaces)) {
11110 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
11111 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
11112 }
11113 } catch (IOException e) {
11114 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011115 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011116 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011117 }
11118
Chenjie Yu89083392018-01-11 14:53:31 -080011119 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011120 * Distribute WiFi energy info and network traffic to apps.
11121 * @param info The energy information from the WiFi controller.
11122 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011123 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011124 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011125 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011126 }
11127
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011128 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011129 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011130 synchronized (mWifiNetworkLock) {
11131 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
11132 if (latestStats != null) {
11133 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
11134 mNetworkStatsPool.acquire());
11135 mNetworkStatsPool.release(mLastWifiNetworkStats);
11136 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011137 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011138 }
11139
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011140 synchronized (this) {
11141 if (!mOnBatteryInternal) {
11142 if (delta != null) {
11143 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011144 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011145 return;
11146 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011147
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011148 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
11149 SparseLongArray rxPackets = new SparseLongArray();
11150 SparseLongArray txPackets = new SparseLongArray();
11151 long totalTxPackets = 0;
11152 long totalRxPackets = 0;
11153 if (delta != null) {
11154 NetworkStats.Entry entry = new NetworkStats.Entry();
11155 final int size = delta.size();
11156 for (int i = 0; i < size; i++) {
11157 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011158
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011159 if (DEBUG_ENERGY) {
11160 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
11161 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11162 + " txPackets=" + entry.txPackets);
11163 }
11164
11165 if (entry.rxBytes == 0 && entry.txBytes == 0) {
11166 // Skip the lookup below since there is no work to do.
11167 continue;
11168 }
11169
11170 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11171 if (entry.rxBytes != 0) {
11172 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011173 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011174 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11175 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
11176 entry.rxPackets);
11177 }
11178 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11179 entry.rxBytes);
11180 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
11181 entry.rxPackets);
11182
11183 rxPackets.put(u.getUid(), entry.rxPackets);
11184
11185 // Sum the total number of packets so that the Rx Power can
11186 // be evenly distributed amongst the apps.
11187 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011188 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011189
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011190 if (entry.txBytes != 0) {
11191 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080011192 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011193 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11194 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
11195 entry.txPackets);
11196 }
11197 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11198 entry.txBytes);
11199 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
11200 entry.txPackets);
11201
11202 txPackets.put(u.getUid(), entry.txPackets);
11203
11204 // Sum the total number of packets so that the Tx Power can
11205 // be evenly distributed amongst the apps.
11206 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080011207 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080011208 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011209 mNetworkStatsPool.release(delta);
11210 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070011211 }
11212
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011213 if (info != null) {
11214 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070011215
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011216 // Measured in mAms
11217 final long txTimeMs = info.getControllerTxTimeMillis();
11218 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080011219 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011220 final long idleTimeMs = info.getControllerIdleTimeMillis();
11221 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011222
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011223 long leftOverRxTimeMs = rxTimeMs;
11224 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070011225
Adam Lesinskie08af192015-03-25 16:42:59 -070011226 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011227 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
11228 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11229 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11230 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
11231 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080011232 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011233 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011234
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011235 long totalWifiLockTimeMs = 0;
11236 long totalScanTimeMs = 0;
11237
11238 // On the first pass, collect some totals so that we can normalize power
11239 // calculations if we need to.
11240 final int uidStatsSize = mUidStats.size();
11241 for (int i = 0; i < uidStatsSize; i++) {
11242 final Uid uid = mUidStats.valueAt(i);
11243
11244 // Sum the total scan power for all apps.
11245 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
11246 elapsedRealtimeMs * 1000) / 1000;
11247
11248 // Sum the total time holding wifi lock for all apps.
11249 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11250 elapsedRealtimeMs * 1000) / 1000;
11251 }
11252
11253 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
11254 Slog.d(TAG,
11255 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
11256 + rxTimeMs + " ms). Normalizing scan time.");
11257 }
11258 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11259 Slog.d(TAG,
11260 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11261 + txTimeMs + " ms). Normalizing scan time.");
11262 }
11263
11264 // Actually assign and distribute power usage to apps.
11265 for (int i = 0; i < uidStatsSize; i++) {
11266 final Uid uid = mUidStats.valueAt(i);
11267
11268 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11269 elapsedRealtimeMs * 1000) / 1000;
11270 if (scanTimeSinceMarkMs > 0) {
11271 // Set the new mark so that next time we get new data since this point.
11272 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11273
11274 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11275 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11276
11277 // Our total scan time is more than the reported Tx/Rx time.
11278 // This is possible because the cost of a scan is approximate.
11279 // Let's normalize the result so that we evenly blame each app
11280 // scanning.
11281 //
11282 // This means that we may have apps that transmitted/received packets not be
11283 // blamed for this, but this is fine as scans are relatively more expensive.
11284 if (totalScanTimeMs > rxTimeMs) {
11285 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11286 totalScanTimeMs;
11287 }
11288 if (totalScanTimeMs > txTimeMs) {
11289 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11290 totalScanTimeMs;
11291 }
11292
11293 if (DEBUG_ENERGY) {
11294 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11295 + scanRxTimeSinceMarkMs + " ms Tx:"
11296 + scanTxTimeSinceMarkMs + " ms)");
11297 }
11298
11299 ControllerActivityCounterImpl activityCounter =
11300 uid.getOrCreateWifiControllerActivityLocked();
11301 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11302 activityCounter.getTxTimeCounters()[0].addCountLocked(
11303 scanTxTimeSinceMarkMs);
11304 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11305 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11306 }
11307
11308 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11309 // lock.
11310 final long wifiLockTimeSinceMarkMs =
11311 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11312 elapsedRealtimeMs * 1000) / 1000;
11313 if (wifiLockTimeSinceMarkMs > 0) {
11314 // Set the new mark so that next time we get new data since this point.
11315 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11316
11317 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11318 / totalWifiLockTimeMs;
11319 if (DEBUG_ENERGY) {
11320 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11321 + myIdleTimeMs + " ms");
11322 }
11323 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11324 .addCountLocked(myIdleTimeMs);
11325 }
11326 }
11327
Adam Lesinskie08af192015-03-25 16:42:59 -070011328 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011329 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11330 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011331 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011332
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011333 // Distribute the remaining Tx power appropriately between all apps that transmitted
11334 // packets.
11335 for (int i = 0; i < txPackets.size(); i++) {
11336 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11337 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11338 / totalTxPackets;
11339 if (DEBUG_ENERGY) {
11340 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11341 }
11342 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11343 .addCountLocked(myTxTimeMs);
11344 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011345
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011346 // Distribute the remaining Rx power appropriately between all apps that received
11347 // packets.
11348 for (int i = 0; i < rxPackets.size(); i++) {
11349 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11350 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11351 / totalRxPackets;
11352 if (DEBUG_ENERGY) {
11353 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11354 }
11355 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11356 .addCountLocked(myRxTimeMs);
11357 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011358
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011359 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11360
11361
11362 // Update WiFi controller stats.
11363 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11364 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11365 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011366 mWifiActivity.getScanTimeCounter().addCountLocked(
11367 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011368 mWifiActivity.getIdleTimeCounter().addCountLocked(
11369 info.getControllerIdleTimeMillis());
11370
11371 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11372 final double opVolt = mPowerProfile.getAveragePower(
11373 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11374 if (opVolt != 0) {
11375 // We store the power drain as mAms.
11376 mWifiActivity.getPowerCounter().addCountLocked(
11377 (long) (info.getControllerEnergyUsed() / opVolt));
11378 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011379 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011380 }
11381 }
11382
Chenjie Yu89083392018-01-11 14:53:31 -080011383 private ModemActivityInfo mLastModemActivityInfo =
11384 new ModemActivityInfo(0, 0, 0, new int[0], 0, 0);
11385
Chenjie Yua54e54d2018-02-14 20:12:52 -080011386 private ModemActivityInfo getDeltaModemActivityInfo(ModemActivityInfo activityInfo) {
11387 if (activityInfo == null) {
11388 return null;
11389 }
11390 int[] txTimeMs = new int[ModemActivityInfo.TX_POWER_LEVELS];
11391 for (int i = 0; i < ModemActivityInfo.TX_POWER_LEVELS; i++) {
11392 txTimeMs[i] = activityInfo.getTxTimeMillis()[i]
11393 - mLastModemActivityInfo.getTxTimeMillis()[i];
11394 }
11395 ModemActivityInfo deltaInfo = new ModemActivityInfo(activityInfo.getTimestamp(),
11396 activityInfo.getSleepTimeMillis() - mLastModemActivityInfo.getSleepTimeMillis(),
11397 activityInfo.getIdleTimeMillis() - mLastModemActivityInfo.getIdleTimeMillis(),
11398 txTimeMs,
11399 activityInfo.getRxTimeMillis() - mLastModemActivityInfo.getRxTimeMillis(),
11400 activityInfo.getEnergyUsed() - mLastModemActivityInfo.getEnergyUsed());
11401 mLastModemActivityInfo = activityInfo;
11402 return deltaInfo;
11403 }
11404
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011405 /**
11406 * Distribute Cell radio energy info and network traffic to apps.
11407 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011408 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011409 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011410 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011411 }
Chenjie Yua54e54d2018-02-14 20:12:52 -080011412 ModemActivityInfo deltaInfo = getDeltaModemActivityInfo(activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011413
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011414 // Add modem tx power to history.
Chenjie Yua54e54d2018-02-14 20:12:52 -080011415 addModemTxPowerToHistory(deltaInfo);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011416
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011417 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011418 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011419 synchronized (mModemNetworkLock) {
11420 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11421 if (latestStats != null) {
11422 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11423 mNetworkStatsPool.acquire());
11424 mNetworkStatsPool.release(mLastModemNetworkStats);
11425 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011426 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011427 }
11428
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011429 synchronized (this) {
11430 if (!mOnBatteryInternal) {
11431 if (delta != null) {
11432 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011433 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011434 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011435 }
11436
Chenjie Yua54e54d2018-02-14 20:12:52 -080011437 if (deltaInfo != null) {
Siddharth Ray2038af82018-01-17 17:40:26 -080011438 mHasModemReporting = true;
11439 mModemActivity.getIdleTimeCounter().addCountLocked(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011440 deltaInfo.getIdleTimeMillis());
11441 mModemActivity.getRxTimeCounter().addCountLocked(deltaInfo.getRxTimeMillis());
Siddharth Ray2038af82018-01-17 17:40:26 -080011442 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11443 mModemActivity.getTxTimeCounters()[lvl]
Chenjie Yua54e54d2018-02-14 20:12:52 -080011444 .addCountLocked(deltaInfo.getTxTimeMillis()[lvl]);
Siddharth Ray2038af82018-01-17 17:40:26 -080011445 }
11446
11447 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11448 final double opVolt = mPowerProfile.getAveragePower(
11449 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11450 if (opVolt != 0) {
11451 double energyUsed =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011452 deltaInfo.getSleepTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011453 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011454 + deltaInfo.getIdleTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011455 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
Chenjie Yua54e54d2018-02-14 20:12:52 -080011456 + deltaInfo.getRxTimeMillis() *
Siddharth Ray2038af82018-01-17 17:40:26 -080011457 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
Chenjie Yua54e54d2018-02-14 20:12:52 -080011458 int[] txTimeMs = deltaInfo.getTxTimeMillis();
Chenjie Yu89083392018-01-11 14:53:31 -080011459 for (int i = 0; i < Math.min(txTimeMs.length,
Chenjie Yua54e54d2018-02-14 20:12:52 -080011460 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
Chenjie Yu89083392018-01-11 14:53:31 -080011461 energyUsed += txTimeMs[i] * mPowerProfile.getAveragePower(
Chenjie Yua54e54d2018-02-14 20:12:52 -080011462 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
Siddharth Ray2038af82018-01-17 17:40:26 -080011463 }
11464
11465 // We store the power drain as mAms.
11466 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11467 }
11468 }
11469
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011470 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011471 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11472 elapsedRealtimeMs * 1000);
11473 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11474
11475 long totalRxPackets = 0;
11476 long totalTxPackets = 0;
11477 if (delta != null) {
11478 NetworkStats.Entry entry = new NetworkStats.Entry();
11479 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011480 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011481 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011482 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11483 continue;
11484 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011485
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011486 if (DEBUG_ENERGY) {
11487 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11488 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11489 + " txPackets=" + entry.txPackets);
11490 }
11491
11492 totalRxPackets += entry.rxPackets;
11493 totalTxPackets += entry.txPackets;
11494
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011495 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011496 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11497 entry.rxPackets);
11498 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11499 entry.txPackets);
11500 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11501 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11502 entry.rxBytes, entry.rxPackets);
11503 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11504 entry.txBytes, entry.txPackets);
11505 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011506
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011507 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11508 entry.rxBytes);
11509 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11510 entry.txBytes);
11511 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11512 entry.rxPackets);
11513 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11514 entry.txPackets);
11515 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011516
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011517 // Now distribute proportional blame to the apps that did networking.
11518 long totalPackets = totalRxPackets + totalTxPackets;
11519 if (totalPackets > 0) {
11520 for (int i = 0; i < size; i++) {
11521 entry = delta.getValues(i, entry);
11522 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11523 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011524 }
11525
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011526 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11527
11528 // Distribute total radio active time in to this app.
11529 final long appPackets = entry.rxPackets + entry.txPackets;
11530 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11531 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11532
11533 // Remove this app from the totals, so that we don't lose any time
11534 // due to rounding.
11535 radioTime -= appRadioTime;
11536 totalPackets -= appPackets;
11537
Chenjie Yua54e54d2018-02-14 20:12:52 -080011538 if (deltaInfo != null) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011539 ControllerActivityCounterImpl activityCounter =
11540 u.getOrCreateModemControllerActivityLocked();
11541 if (totalRxPackets > 0 && entry.rxPackets > 0) {
Chenjie Yua54e54d2018-02-14 20:12:52 -080011542 final long rxMs = (entry.rxPackets * deltaInfo.getRxTimeMillis())
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011543 / totalRxPackets;
11544 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11545 }
11546
11547 if (totalTxPackets > 0 && entry.txPackets > 0) {
11548 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11549 long txMs =
Chenjie Yua54e54d2018-02-14 20:12:52 -080011550 entry.txPackets * deltaInfo.getTxTimeMillis()[lvl];
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011551 txMs /= totalTxPackets;
11552 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11553 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011554 }
11555 }
11556 }
11557 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011558
11559 if (radioTime > 0) {
11560 // Whoops, there is some radio time we can't blame on an app!
11561 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11562 mMobileRadioActiveUnknownCount.addCountLocked(1);
11563 }
11564
11565 mNetworkStatsPool.release(delta);
11566 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011567 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011568 }
11569 }
11570
Chenjie Yu89083392018-01-11 14:53:31 -080011571 // Cache last value for comparison.
11572 private BluetoothActivityEnergyInfo mLastBluetoothActivityEnergyInfo =
11573 new BluetoothActivityEnergyInfo(0, 0, 0, 0, 0, 0);
11574
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011575 /**
Siddharth Rayf5e796a2018-01-22 18:18:17 -080011576 * Add modem tx power to history
11577 * Device is said to be in high cellular transmit power when it has spent most of the transmit
11578 * time at the highest power level.
11579 * @param activityInfo
11580 */
11581 private void addModemTxPowerToHistory(final ModemActivityInfo activityInfo) {
11582 if (activityInfo == null) {
11583 return;
11584 }
11585 int[] txTimeMs = activityInfo.getTxTimeMillis();
11586 if (txTimeMs == null || txTimeMs.length != ModemActivityInfo.TX_POWER_LEVELS) {
11587 return;
11588 }
11589 final long elapsedRealtime = mClocks.elapsedRealtime();
11590 final long uptime = mClocks.uptimeMillis();
11591 int levelMaxTimeSpent = 0;
11592 for (int i = 1; i < txTimeMs.length; i++) {
11593 if (txTimeMs[i] > txTimeMs[levelMaxTimeSpent]) {
11594 levelMaxTimeSpent = i;
11595 }
11596 }
11597 if (levelMaxTimeSpent == ModemActivityInfo.TX_POWER_LEVELS - 1) {
11598 if (!mIsCellularTxPowerHigh) {
11599 mHistoryCur.states2 |= HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11600 addHistoryRecordLocked(elapsedRealtime, uptime);
11601 mIsCellularTxPowerHigh = true;
11602 }
11603 return;
11604 }
11605 if (mIsCellularTxPowerHigh) {
11606 mHistoryCur.states2 &= ~HistoryItem.STATE2_CELLULAR_HIGH_TX_POWER_FLAG;
11607 addHistoryRecordLocked(elapsedRealtime, uptime);
11608 mIsCellularTxPowerHigh = false;
11609 }
11610 return;
11611 }
11612
11613 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011614 * Distribute Bluetooth energy info and network traffic to apps.
11615 * @param info The energy information from the bluetooth controller.
11616 */
11617 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011618 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011619 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011620 }
11621
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011622 if (info == null || !mOnBatteryInternal) {
11623 return;
11624 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011625
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011626 mHasBluetoothReporting = true;
11627
Bookatz867c0d72017-03-07 18:23:42 -080011628 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Chenjie Yu89083392018-01-11 14:53:31 -080011629 final long rxTimeMs = info.getControllerRxTimeMillis() -
11630 mLastBluetoothActivityEnergyInfo.getControllerRxTimeMillis();
11631 final long txTimeMs = info.getControllerTxTimeMillis() -
11632 mLastBluetoothActivityEnergyInfo.getControllerTxTimeMillis();
11633 final long idleTimeMs = info.getControllerIdleTimeMillis() -
11634 mLastBluetoothActivityEnergyInfo.getControllerIdleTimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011635 if (DEBUG_ENERGY) {
11636 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11637 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11638 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
Chenjie Yu89083392018-01-11 14:53:31 -080011639 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011640 }
11641
11642 long totalScanTimeMs = 0;
11643
11644 final int uidCount = mUidStats.size();
11645 for (int i = 0; i < uidCount; i++) {
11646 final Uid u = mUidStats.valueAt(i);
11647 if (u.mBluetoothScanTimer == null) {
11648 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011649 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011650
Bookatzaa4594a2017-03-24 12:39:56 -070011651 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011652 elapsedRealtimeMs * 1000) / 1000;
11653 }
11654
11655 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11656 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11657
11658 if (DEBUG_ENERGY) {
11659 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11660 + " TX=" + normalizeScanTxTime);
11661 }
11662
11663 long leftOverRxTimeMs = rxTimeMs;
11664 long leftOverTxTimeMs = txTimeMs;
11665
11666 for (int i = 0; i < uidCount; i++) {
11667 final Uid u = mUidStats.valueAt(i);
11668 if (u.mBluetoothScanTimer == null) {
11669 continue;
11670 }
11671
Bookatzaa4594a2017-03-24 12:39:56 -070011672 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011673 elapsedRealtimeMs * 1000) / 1000;
11674 if (scanTimeSinceMarkMs > 0) {
11675 // Set the new mark so that next time we get new data since this point.
11676 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11677
11678 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11679 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11680
11681 if (normalizeScanRxTime) {
11682 // Scan time is longer than the total rx time in the controller,
11683 // so distribute the scan time proportionately. This means regular traffic
11684 // will not blamed, but scans are more expensive anyways.
11685 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11686 }
11687
11688 if (normalizeScanTxTime) {
11689 // Scan time is longer than the total tx time in the controller,
11690 // so distribute the scan time proportionately. This means regular traffic
11691 // will not blamed, but scans are more expensive anyways.
11692 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11693 }
11694
11695 final ControllerActivityCounterImpl counter =
11696 u.getOrCreateBluetoothControllerActivityLocked();
11697 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11698 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11699
11700 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11701 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11702 }
11703 }
11704
11705 if (DEBUG_ENERGY) {
11706 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs
11707 + " TX=" + leftOverTxTimeMs);
11708 }
11709
11710 //
11711 // Now distribute blame to apps that did bluetooth traffic.
11712 //
11713
11714 long totalTxBytes = 0;
11715 long totalRxBytes = 0;
11716
11717 final UidTraffic[] uidTraffic = info.getUidTraffic();
Chenjie Yu89083392018-01-11 14:53:31 -080011718 final UidTraffic[] lastUidTraffic = mLastBluetoothActivityEnergyInfo.getUidTraffic();
11719 final ArrayList<UidTraffic> deltaTraffic = new ArrayList<>();
11720 int m = 0, n = 0;
11721 for (; m < uidTraffic.length && n < lastUidTraffic.length; m++) {
11722 final UidTraffic traffic = uidTraffic[m];
11723 final UidTraffic lastTraffic = lastUidTraffic[n];
11724 if (traffic.getUid() == lastTraffic.getUid()) {
11725 deltaTraffic.add(new UidTraffic(traffic.getUid(),
11726 traffic.getRxBytes() - lastTraffic.getRxBytes(),
11727 traffic.getTxBytes() - lastTraffic.getTxBytes()));
11728 n++;
11729 }
11730 }
11731 for (; m < uidTraffic.length; m ++) {
11732 deltaTraffic.add(uidTraffic[m]);
11733 }
11734
11735 for (int i = 0, j = 0; i < deltaTraffic.size(); i++) {
11736 final UidTraffic traffic = deltaTraffic.get(i);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011737
11738 // Add to the global counters.
11739 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(
11740 traffic.getRxBytes());
11741 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(
11742 traffic.getTxBytes());
11743
11744 // Add to the UID counters.
11745 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
11746 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, traffic.getRxBytes(), 0);
11747 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, traffic.getTxBytes(), 0);
11748
11749 // Calculate the total traffic.
11750 totalTxBytes += traffic.getTxBytes();
11751 totalRxBytes += traffic.getRxBytes();
11752 }
11753
11754 if ((totalTxBytes != 0 || totalRxBytes != 0) &&
11755 (leftOverRxTimeMs != 0 || leftOverTxTimeMs != 0)) {
Chenjie Yu89083392018-01-11 14:53:31 -080011756 for (int i = 0; i < deltaTraffic.size(); i++) {
11757 final UidTraffic traffic = deltaTraffic.get(i);
Adam Lesinski50e47602015-12-04 17:04:54 -080011758
Adam Lesinski50e47602015-12-04 17:04:54 -080011759 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011760 final ControllerActivityCounterImpl counter =
11761 u.getOrCreateBluetoothControllerActivityLocked();
11762
11763 if (totalRxBytes > 0 && traffic.getRxBytes() > 0) {
11764 final long timeRxMs = (leftOverRxTimeMs * traffic.getRxBytes()) / totalRxBytes;
11765
11766 if (DEBUG_ENERGY) {
11767 Slog.d(TAG, "UID=" + traffic.getUid() + " rx_bytes=" + traffic.getRxBytes()
11768 + " rx_time=" + timeRxMs);
11769 }
11770 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11771 leftOverRxTimeMs -= timeRxMs;
11772 }
11773
11774 if (totalTxBytes > 0 && traffic.getTxBytes() > 0) {
11775 final long timeTxMs = (leftOverTxTimeMs * traffic.getTxBytes()) / totalTxBytes;
11776
11777 if (DEBUG_ENERGY) {
11778 Slog.d(TAG, "UID=" + traffic.getUid() + " tx_bytes=" + traffic.getTxBytes()
11779 + " tx_time=" + timeTxMs);
11780 }
11781
11782 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11783 leftOverTxTimeMs -= timeTxMs;
11784 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011785 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011786 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011787
Chenjie Yu89083392018-01-11 14:53:31 -080011788 mBluetoothActivity.getRxTimeCounter().addCountLocked(rxTimeMs);
11789 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(txTimeMs);
11790 mBluetoothActivity.getIdleTimeCounter().addCountLocked(idleTimeMs);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011791
11792 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11793 final double opVolt = mPowerProfile.getAveragePower(
11794 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11795 if (opVolt != 0) {
11796 // We store the power drain as mAms.
11797 mBluetoothActivity.getPowerCounter().addCountLocked(
Chenjie Yu89083392018-01-11 14:53:31 -080011798 (long) ((info.getControllerEnergyUsed() -
11799 mLastBluetoothActivityEnergyInfo.getControllerEnergyUsed() )/ opVolt));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011800 }
Chenjie Yu89083392018-01-11 14:53:31 -080011801 mLastBluetoothActivityEnergyInfo = info;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011802 }
11803
11804 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011805 * Read and record Resource Power Manager (RPM) state and voter times.
11806 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11807 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011808 */
11809 public void updateRpmStatsLocked() {
11810 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011811 long now = SystemClock.elapsedRealtime();
11812 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11813 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11814 mLastRpmStatsUpdateTimeMs = now;
11815 }
Bookatz50df7112017-08-04 14:53:26 -070011816
11817 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11818 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11819
11820 // Update values for this platform state.
11821 final String pName = pstate.getKey();
11822 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11823 final int pCount = pstate.getValue().mCount;
11824 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011825 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11826 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11827 }
Bookatz50df7112017-08-04 14:53:26 -070011828
11829 // Update values for each voter of this platform state.
11830 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11831 : pstate.getValue().mVoters.entrySet()) {
11832 final String vName = pName + "." + voter.getKey();
11833 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11834 final int vCount = voter.getValue().mCount;
11835 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011836 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11837 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11838 }
Bookatz50df7112017-08-04 14:53:26 -070011839 }
11840 }
11841
11842 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11843 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11844
11845 final String subsysName = subsys.getKey();
11846 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11847 : subsys.getValue().mStates.entrySet()) {
11848 final String name = subsysName + "." + sstate.getKey();
11849 final long timeUs = sstate.getValue().mTimeMs * 1000;
11850 final int count = sstate.getValue().mCount;
11851 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011852 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11853 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11854 }
Bookatz50df7112017-08-04 14:53:26 -070011855 }
11856 }
11857 }
11858
11859 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011860 * Read and distribute kernel wake lock use across apps.
11861 */
11862 public void updateKernelWakelocksLocked() {
11863 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11864 mTmpWakelockStats);
11865 if (wakelockStats == null) {
11866 // Not crashing might make board bringup easier.
11867 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11868 return;
11869 }
11870
11871 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11872 String name = ent.getKey();
11873 KernelWakelockStats.Entry kws = ent.getValue();
11874
11875 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11876 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011877 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011878 mKernelWakelockStats.put(name, kwlt);
11879 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011880
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011881 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011882 kwlt.setUpdateVersion(kws.mVersion);
11883 }
11884
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011885 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011886 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11887 // this time.
11888 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11889 SamplingTimer st = ent.getValue();
11890 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11891 st.endSample();
11892 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011893 }
11894 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011895
Adam Lesinskid84ad302016-05-17 18:31:02 -070011896 // Record whether we've seen a non-zero time (for debugging b/22716723).
11897 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011898 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11899 }
11900
11901 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11902 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11903 wakelockStats.kernelWakelockVersion);
11904 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011905 }
11906
Adam Lesinski72478f02015-06-17 15:39:43 -070011907 // We use an anonymous class to access these variables,
11908 // so they can't live on the stack or they'd have to be
11909 // final MutableLong objects (more allocations).
11910 // Used in updateCpuTimeLocked().
11911 long mTempTotalCpuUserTimeUs;
11912 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011913 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011914
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011915 /**
James Carr3a226052016-07-01 14:49:52 -070011916 * Reads the newest memory stats from the kernel.
11917 */
11918 public void updateKernelMemoryBandwidthLocked() {
11919 mKernelMemoryBandwidthStats.updateStats();
11920 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11921 final int bandwidthEntryCount = bandwidthEntries.size();
11922 int index;
11923 for (int i = 0; i < bandwidthEntryCount; i++) {
11924 SamplingTimer timer;
11925 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11926 timer = mKernelMemoryStats.valueAt(index);
11927 } else {
11928 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11929 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11930 }
11931 timer.update(bandwidthEntries.valueAt(i), 1);
11932 if (DEBUG_MEMORY) {
11933 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11934 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11935 mKernelMemoryStats.get(
11936 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11937 mKernelMemoryStats.size()));
11938 }
11939 }
11940 }
11941
Sudheer Shankac57729a2018-02-09 15:44:42 -080011942 public boolean isOnBatteryLocked() {
11943 return mOnBatteryTimeBase.isRunning();
11944 }
11945
11946 public boolean isOnBatteryScreenOffLocked() {
11947 return mOnBatteryScreenOffTimeBase.isRunning();
11948 }
11949
James Carr3a226052016-07-01 14:49:52 -070011950 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011951 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11952 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11953 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011954 * It's possible this will be invoked after the internal battery/screen states are updated, so
11955 * passing the appropriate battery/screen states to try attribute the cpu times to correct
11956 * buckets.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011957 */
Andreas Gampe3f24e692018-02-05 13:24:28 -080011958 @GuardedBy("this")
Sudheer Shankac57729a2018-02-09 15:44:42 -080011959 public void updateCpuTimeLocked(boolean onBattery, boolean onBatteryScreenOff) {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011960 if (mPowerProfile == null) {
11961 return;
11962 }
11963
Adam Lesinski72478f02015-06-17 15:39:43 -070011964 if (DEBUG_ENERGY_CPU) {
11965 Slog.d(TAG, "!Cpu updating!");
11966 }
11967
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011968 if (mCpuFreqs == null) {
11969 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11970 }
11971
Sudheer Shanka38383232017-07-25 09:55:03 -070011972 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11973 // usually holding the wakelock on behalf of an app.
11974 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11975 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Sudheer Shankac57729a2018-02-09 15:44:42 -080011976 if (onBatteryScreenOff) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011977 partialTimersToConsider = new ArrayList<>();
11978 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011979 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011980 // Since the collection and blaming of wakelocks can be scheduled to run after
11981 // some delay, the mPartialTimers list may have new entries. We can't blame
11982 // the newly added timer for past cpu time, so we only consider timers that
11983 // were present for one round of collection. Once a timer has gone through
11984 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011985 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011986 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011987 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011988 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011989 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011990 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011991
Sudheer Shanka38383232017-07-25 09:55:03 -070011992 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11993 // need to take the snapshots.
Sudheer Shankac57729a2018-02-09 15:44:42 -080011994 if (!onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011995 mKernelUidCpuTimeReader.readDelta(null);
11996 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Mafae87da2018-01-19 20:07:20 -080011997 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11998 mKernelUidCpuActiveTimeReader.readDelta(null);
11999 mKernelUidCpuClusterTimeReader.readDelta(null);
12000 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012001 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
12002 mKernelCpuSpeedReaders[cluster].readDelta();
12003 }
12004 return;
12005 }
Adam Lesinski72478f02015-06-17 15:39:43 -070012006
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012007 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012008 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
12009 ? null : new SparseLongArray();
Sudheer Shankac57729a2018-02-09 15:44:42 -080012010 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012011 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
12012 // freqs, so no need to approximate these values.
12013 if (updatedUids != null) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080012014 updateClusterSpeedTimes(updatedUids, onBattery);
Sudheer Shanka671985f2017-05-19 11:33:42 -070012015 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012016 readKernelUidCpuFreqTimesLocked(partialTimersToConsider, onBattery, onBatteryScreenOff);
Mike Mafae87da2018-01-19 20:07:20 -080012017 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
Sudheer Shankac57729a2018-02-09 15:44:42 -080012018 readKernelUidCpuActiveTimesLocked(onBattery);
12019 readKernelUidCpuClusterTimesLocked(onBattery);
Mike Mafae87da2018-01-19 20:07:20 -080012020 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012021 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012022
Sudheer Shanka38383232017-07-25 09:55:03 -070012023 /**
12024 * Mark the current partial timers as gone through a collection so that they will be
12025 * considered in the next cpu times distribution to wakelock holders.
12026 */
12027 @VisibleForTesting
12028 public void markPartialTimersAsEligible() {
12029 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
12030 // No difference, so each timer is now considered for the next collection.
12031 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
12032 mPartialTimers.get(i).mInList = true;
12033 }
12034 } else {
12035 // The lists are different, meaning we added (or removed a timer) since the last
12036 // collection.
12037 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
12038 mLastPartialTimers.get(i).mInList = false;
12039 }
12040 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070012041
Sudheer Shanka38383232017-07-25 09:55:03 -070012042 // Mark the current timers as gone through a collection.
12043 final int numPartialTimers = mPartialTimers.size();
12044 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070012045 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070012046 timer.mInList = true;
12047 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070012048 }
12049 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012050 }
Adam Lesinski72478f02015-06-17 15:39:43 -070012051
Sudheer Shanka38383232017-07-25 09:55:03 -070012052 /**
12053 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
12054 * calculate cpu times spent by each uid at different frequencies.
12055 *
12056 * @param updatedUids The uids for which times spent at different frequencies are calculated.
12057 */
12058 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012059 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012060 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012061 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070012062 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012063 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012064 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
12065 if (clusterSpeedTimesMs[cluster] != null) {
12066 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
12067 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012068 }
12069 }
12070 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012071 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012072 // We have cpu times per freq aggregated over all uids but we need the times per uid.
12073 // So, we distribute total time spent by an uid to different cpu freqs based on the
12074 // amount of time cpu was running at that freq.
12075 final int updatedUidsCount = updatedUids.size();
12076 for (int i = 0; i < updatedUidsCount; ++i) {
12077 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070012078 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012079 // Add the cpu speeds to this UID.
12080 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070012081 if (u.mCpuClusterSpeedTimesUs == null ||
12082 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070012083 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012084 }
12085
Sudheer Shankaaf857412017-07-21 00:14:24 -070012086 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
12087 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
12088 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
12089 u.mCpuClusterSpeedTimesUs[cluster].length) {
12090 u.mCpuClusterSpeedTimesUs[cluster]
12091 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012092 }
12093
Sudheer Shankaaf857412017-07-21 00:14:24 -070012094 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012095 for (int speed = 0; speed < speedsInCluster; speed++) {
12096 if (cpuSpeeds[speed] == null) {
12097 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12098 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070012099 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
12100 * clusterSpeedTimesMs[cluster][speed]
Sudheer Shankac57729a2018-02-09 15:44:42 -080012101 / totalCpuClustersTimeMs, onBattery);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012102 }
12103 }
12104 }
12105 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012106 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070012107
Sudheer Shanka38383232017-07-25 09:55:03 -070012108 /**
12109 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
12110 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
12111 * wakelock holders.
12112 *
12113 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
12114 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
12115 */
12116 @VisibleForTesting
12117 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
Sudheer Shankac57729a2018-02-09 15:44:42 -080012118 @Nullable SparseLongArray updatedUids, boolean onBattery) {
Sudheer Shanka38383232017-07-25 09:55:03 -070012119 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
12120 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12121 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070012122
Sudheer Shanka38383232017-07-25 09:55:03 -070012123 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
12124 uid = mapUid(uid);
12125 if (Process.isIsolated(uid)) {
12126 // This could happen if the isolated uid mapping was removed before that process
12127 // was actually killed.
12128 mKernelUidCpuTimeReader.removeUid(uid);
12129 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
12130 return;
12131 }
12132 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12133 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
12134 mKernelUidCpuTimeReader.removeUid(uid);
12135 return;
12136 }
12137 final Uid u = getUidStatsLocked(uid);
12138
12139 // Accumulate the total system and user time.
12140 mTempTotalCpuUserTimeUs += userTimeUs;
12141 mTempTotalCpuSystemTimeUs += systemTimeUs;
12142
12143 StringBuilder sb = null;
12144 if (DEBUG_ENERGY_CPU) {
12145 sb = new StringBuilder();
12146 sb.append(" got time for uid=").append(u.mUid).append(": u=");
12147 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12148 sb.append(" s=");
12149 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12150 sb.append("\n");
12151 }
12152
12153 if (numWakelocks > 0) {
12154 // We have wakelocks being held, so only give a portion of the
12155 // time to the process. The rest will be distributed among wakelock
12156 // holders.
12157 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
12158 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
12159 }
12160
12161 if (sb != null) {
12162 sb.append(" adding to uid=").append(u.mUid).append(": u=");
12163 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12164 sb.append(" s=");
12165 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12166 Slog.d(TAG, sb.toString());
12167 }
12168
Sudheer Shankac57729a2018-02-09 15:44:42 -080012169 u.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12170 u.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012171 if (updatedUids != null) {
12172 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
12173 }
12174 });
12175
12176 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12177 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12178 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
12179 }
12180
12181 if (numWakelocks > 0) {
12182 // Distribute a portion of the total cpu time to wakelock holders.
12183 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12184 mTempTotalCpuSystemTimeUs =
12185 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
12186
12187 for (int i = 0; i < numWakelocks; ++i) {
12188 final StopwatchTimer timer = partialTimers.get(i);
12189 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
12190 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
12191
12192 if (DEBUG_ENERGY_CPU) {
12193 final StringBuilder sb = new StringBuilder();
12194 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
12195 .append(": u=");
12196 TimeUtils.formatDuration(userTimeUs / 1000, sb);
12197 sb.append(" s=");
12198 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
12199 Slog.d(TAG, sb.toString());
12200 }
12201
Sudheer Shankac57729a2018-02-09 15:44:42 -080012202 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs, onBattery);
12203 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012204 if (updatedUids != null) {
12205 final int uid = timer.mUid.getUid();
12206 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
12207 }
12208
12209 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
Sudheer Shankac57729a2018-02-09 15:44:42 -080012210 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000, onBattery);
Sudheer Shanka38383232017-07-25 09:55:03 -070012211
12212 mTempTotalCpuUserTimeUs -= userTimeUs;
12213 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070012214 }
12215 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012216 }
12217
Sudheer Shanka38383232017-07-25 09:55:03 -070012218 /**
12219 * Take a snapshot of the cpu times spent by each uid in each freq and update the
12220 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012221 *
12222 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070012223 */
12224 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012225 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
12226 boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012227 final boolean perClusterTimesAvailable =
12228 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
12229 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
12230 final int numClusters = mPowerProfile.getNumCpuClusters();
12231 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012232 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012233 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
12234 uid = mapUid(uid);
12235 if (Process.isIsolated(uid)) {
12236 mKernelUidCpuFreqTimeReader.removeUid(uid);
12237 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
12238 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070012239 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012240 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12241 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
12242 mKernelUidCpuFreqTimeReader.removeUid(uid);
12243 return;
12244 }
12245 final Uid u = getUidStatsLocked(uid);
12246 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12247 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
12248 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012249 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012250 if (u.mScreenOffCpuFreqTimeMs == null ||
12251 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
12252 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
12253 mOnBatteryScreenOffTimeBase);
12254 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012255 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012256
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012257 if (perClusterTimesAvailable) {
12258 if (u.mCpuClusterSpeedTimesUs == null ||
12259 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12260 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012261 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012262 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
12263 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070012264 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012265
12266 int freqIndex = 0;
12267 for (int cluster = 0; cluster < numClusters; ++cluster) {
12268 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12269 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12270 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12271 u.mCpuClusterSpeedTimesUs[cluster]
12272 = new LongSamplingCounter[speedsInCluster];
12273 }
12274 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
12275 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
12276 }
12277 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
12278 for (int speed = 0; speed < speedsInCluster; ++speed) {
12279 if (cpuTimesUs[speed] == null) {
12280 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12281 }
12282 final long appAllocationUs;
12283 if (mWakeLockAllocationsUs != null) {
12284 appAllocationUs =
12285 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
12286 mWakeLockAllocationsUs[cluster][speed] +=
12287 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
12288 } else {
12289 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
12290 }
Sudheer Shankac57729a2018-02-09 15:44:42 -080012291 cpuTimesUs[speed].addCountLocked(appAllocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012292 freqIndex++;
12293 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012294 }
Sudheer Shanka38383232017-07-25 09:55:03 -070012295 }
12296 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012297
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080012298 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12299 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12300 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
12301 }
12302
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012303 if (mWakeLockAllocationsUs != null) {
12304 for (int i = 0; i < numWakelocks; ++i) {
12305 final Uid u = partialTimers.get(i).mUid;
12306 if (u.mCpuClusterSpeedTimesUs == null ||
12307 u.mCpuClusterSpeedTimesUs.length != numClusters) {
12308 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
12309 }
12310
12311 for (int cluster = 0; cluster < numClusters; ++cluster) {
12312 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
12313 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
12314 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
12315 u.mCpuClusterSpeedTimesUs[cluster]
12316 = new LongSamplingCounter[speedsInCluster];
12317 }
12318 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
12319 for (int speed = 0; speed < speedsInCluster; ++speed) {
12320 if (cpuTimeUs[speed] == null) {
12321 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
12322 }
12323 final long allocationUs =
12324 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
Sudheer Shankac57729a2018-02-09 15:44:42 -080012325 cpuTimeUs[speed].addCountLocked(allocationUs, onBattery);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070012326 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
12327 }
12328 }
12329 }
12330 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012331 }
12332
Mike Ma3d422c32017-10-25 11:08:57 -070012333 /**
12334 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
12335 * counters.
12336 */
12337 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012338 public void readKernelUidCpuActiveTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012339 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012340 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012341 uid = mapUid(uid);
12342 if (Process.isIsolated(uid)) {
12343 mKernelUidCpuActiveTimeReader.removeUid(uid);
12344 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
12345 return;
12346 }
12347 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12348 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
12349 mKernelUidCpuActiveTimeReader.removeUid(uid);
12350 return;
12351 }
12352 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012353 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012354 });
12355
12356 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12357 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12358 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12359 }
12360 }
12361
12362 /**
12363 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12364 * counters.
12365 */
12366 @VisibleForTesting
Sudheer Shankac57729a2018-02-09 15:44:42 -080012367 public void readKernelUidCpuClusterTimesLocked(boolean onBattery) {
Mike Ma3d422c32017-10-25 11:08:57 -070012368 final long startTimeMs = mClocks.uptimeMillis();
Mike Ma2ab01442018-02-13 14:22:47 -080012369 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesMs) -> {
Mike Ma3d422c32017-10-25 11:08:57 -070012370 uid = mapUid(uid);
12371 if (Process.isIsolated(uid)) {
12372 mKernelUidCpuClusterTimeReader.removeUid(uid);
12373 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12374 return;
12375 }
12376 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12377 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12378 mKernelUidCpuClusterTimeReader.removeUid(uid);
12379 return;
12380 }
12381 final Uid u = getUidStatsLocked(uid);
Mike Ma2ab01442018-02-13 14:22:47 -080012382 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesMs, onBattery);
Mike Ma3d422c32017-10-25 11:08:57 -070012383 });
12384
12385 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12386 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12387 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12388 }
12389 }
12390
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012391 boolean setChargingLocked(boolean charging) {
12392 if (mCharging != charging) {
12393 mCharging = charging;
12394 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012395 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012396 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012397 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012398 }
12399 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12400 return true;
12401 }
12402 return false;
12403 }
12404
Andreas Gampe3f24e692018-02-05 13:24:28 -080012405 @GuardedBy("this")
Mike Mac2f518a2017-09-19 16:06:03 -070012406 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12407 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012408 boolean doWrite = false;
12409 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12410 m.arg1 = onBattery ? 1 : 0;
12411 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012412
Dianne Hackborn40c87252014-03-19 16:55:40 -070012413 final long uptime = mSecUptime * 1000;
12414 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012415 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012416 if (onBattery) {
12417 // We will reset our status if we are unplugging after the
12418 // battery was last full, or the level is at 100, or
12419 // we have gone through a significant charge (from a very low
12420 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012421 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012422 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012423 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012424 || (mDischargeCurrentLevel < 20 && level >= 80)
12425 || (getHighDischargeAmountSinceCharge() >= 200
12426 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012427 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012428 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012429 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12430 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012431 // Before we write, collect a snapshot of the final aggregated
12432 // stats to be reported in the next checkin. Only do this if we have
12433 // a sufficient amount of data to make it interesting.
12434 if (getLowDischargeAmountSinceCharge() >= 20) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012435 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012436 final Parcel parcel = Parcel.obtain();
12437 writeSummaryToParcel(parcel, true);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012438 final long initialTime = SystemClock.uptimeMillis() - startTime;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012439 BackgroundThread.getHandler().post(new Runnable() {
12440 @Override public void run() {
12441 synchronized (mCheckinFile) {
Dianne Hackborne17b4452018-01-10 13:15:40 -080012442 final long startTime2 = SystemClock.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012443 FileOutputStream stream = null;
12444 try {
12445 stream = mCheckinFile.startWrite();
12446 stream.write(parcel.marshall());
12447 stream.flush();
12448 FileUtils.sync(stream);
12449 stream.close();
12450 mCheckinFile.finishWrite(stream);
Dianne Hackborne17b4452018-01-10 13:15:40 -080012451 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
12452 "batterystats-checkin",
12453 initialTime + SystemClock.uptimeMillis() - startTime2);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012454 } catch (IOException e) {
12455 Slog.w("BatteryStats",
12456 "Error writing checkin battery statistics", e);
12457 mCheckinFile.failWrite(stream);
12458 } finally {
12459 parcel.recycle();
12460 }
12461 }
12462 }
12463 });
12464 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012465 doWrite = true;
12466 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012467 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012468 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012469 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012470 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012471 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012472 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012473 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012474 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012475 if (mCharging) {
12476 setChargingLocked(false);
12477 }
12478 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012479 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012480 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012481 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012482 mDischargeStepTracker.clearTime();
12483 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012484 mInitStepMode = mCurStepMode;
12485 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012486 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012487 mHistoryCur.batteryLevel = (byte)level;
12488 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12489 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12490 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012491 if (reset) {
12492 mRecordingHistory = true;
12493 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12494 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012495 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012496 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012497 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012498 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012499 mDischargeScreenDozeUnplugLevel = 0;
12500 mDischargeScreenOffUnplugLevel = 0;
12501 } else if (isScreenDoze(screenState)) {
12502 mDischargeScreenOnUnplugLevel = 0;
12503 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012504 mDischargeScreenOffUnplugLevel = 0;
12505 } else {
12506 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012507 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012508 mDischargeScreenOffUnplugLevel = level;
12509 }
12510 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012511 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012512 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012513 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012514 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012515 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012516 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012517 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012518 mHistoryCur.batteryLevel = (byte)level;
12519 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12520 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12521 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012522 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012523 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012524 if (level < mDischargeUnplugLevel) {
12525 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12526 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12527 }
Mike Mac2f518a2017-09-19 16:06:03 -070012528 updateDischargeScreenLevelsLocked(screenState, screenState);
12529 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012530 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012531 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012532 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012533 mInitStepMode = mCurStepMode;
12534 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012535 }
12536 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12537 if (mFile != null) {
12538 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012539 }
12540 }
12541 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012542
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012543 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12544 boolean reset) {
12545 mRecordingHistory = true;
12546 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012547 addHistoryBufferLocked(elapsedRealtimeMs,
Dianne Hackborn37de0982014-05-09 09:32:18 -070012548 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012549 mHistoryCur);
12550 mHistoryCur.currentTime = 0;
12551 if (reset) {
12552 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12553 }
12554 }
12555
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012556 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12557 final long uptimeMs) {
12558 if (mRecordingHistory) {
12559 mHistoryCur.currentTime = currentTime;
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012560 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_CURRENT_TIME, mHistoryCur);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012561 mHistoryCur.currentTime = 0;
12562 }
12563 }
12564
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012565 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12566 if (mRecordingHistory) {
12567 mHistoryCur.currentTime = System.currentTimeMillis();
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000012568 addHistoryBufferLocked(elapsedRealtimeMs, HistoryItem.CMD_SHUTDOWN, mHistoryCur);
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012569 mHistoryCur.currentTime = 0;
12570 }
12571 }
12572
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012573 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012574 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012575 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012576 }
12577 }
12578
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012579 // This should probably be exposed in the API, though it's not critical
Bookatz1a1b0462018-01-12 11:47:03 -080012580 public static final int BATTERY_PLUGGED_NONE = OsProtoEnums.BATTERY_PLUGGED_NONE; // = 0
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012581
Andreas Gampe3f24e692018-02-05 13:24:28 -080012582 @GuardedBy("this")
Bookatz8c6571b2017-10-24 15:04:41 -070012583 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12584 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12585 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012586 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12587 temp = Math.max(0, temp);
12588
Bookatz8c6571b2017-10-24 15:04:41 -070012589 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
12590 status, plugType, level, temp);
12591
Sudheer Shankac57729a2018-02-09 15:44:42 -080012592 final boolean onBattery = isOnBattery(plugType, status);
Joe Onoratoabded112016-02-08 16:49:39 -080012593 final long uptime = mClocks.uptimeMillis();
12594 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012595 if (!mHaveBatteryLevel) {
12596 mHaveBatteryLevel = true;
12597 // We start out assuming that the device is plugged in (not
12598 // on battery). If our first report is now that we are indeed
12599 // plugged in, then twiddle our state to correctly reflect that
12600 // since we won't be going through the full setOnBattery().
12601 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012602 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012603 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012604 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012605 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012606 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012607 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012608 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012609 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012610 mHistoryCur.batteryStatus = (byte)status;
12611 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012612 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012613 mMaxChargeStepLevel = mMinDischargeStepLevel =
12614 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012615 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012616 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12617 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12618 }
12619 int oldStatus = mHistoryCur.batteryStatus;
12620 if (onBattery) {
12621 mDischargeCurrentLevel = level;
12622 if (!mRecordingHistory) {
12623 mRecordingHistory = true;
12624 startRecordingHistory(elapsedRealtime, uptime, true);
12625 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012626 } else if (level < 96 &&
12627 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012628 if (!mRecordingHistory) {
12629 mRecordingHistory = true;
12630 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012631 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012632 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012633 mCurrentBatteryLevel = level;
12634 if (mDischargePlugLevel < 0) {
12635 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012636 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012637
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012638 if (onBattery != mOnBattery) {
12639 mHistoryCur.batteryLevel = (byte)level;
12640 mHistoryCur.batteryStatus = (byte)status;
12641 mHistoryCur.batteryHealth = (byte)health;
12642 mHistoryCur.batteryPlugType = (byte)plugType;
12643 mHistoryCur.batteryTemperature = (short)temp;
12644 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012645 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12646 // Only record discharges
12647 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12648 mDischargeCounter.addCountLocked(chargeDiff);
12649 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012650 if (isScreenDoze(mScreenState)) {
12651 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12652 }
Mike Ma15313c92017-11-15 17:58:21 -080012653 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12654 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12655 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12656 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12657 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012658 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012659 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012660 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012661 } else {
12662 boolean changed = false;
12663 if (mHistoryCur.batteryLevel != level) {
12664 mHistoryCur.batteryLevel = (byte)level;
12665 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012666
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012667 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12668 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012669 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070012670 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012671 if (mHistoryCur.batteryStatus != status) {
12672 mHistoryCur.batteryStatus = (byte)status;
12673 changed = true;
12674 }
12675 if (mHistoryCur.batteryHealth != health) {
12676 mHistoryCur.batteryHealth = (byte)health;
12677 changed = true;
12678 }
12679 if (mHistoryCur.batteryPlugType != plugType) {
12680 mHistoryCur.batteryPlugType = (byte)plugType;
12681 changed = true;
12682 }
12683 if (temp >= (mHistoryCur.batteryTemperature+10)
12684 || temp <= (mHistoryCur.batteryTemperature-10)) {
12685 mHistoryCur.batteryTemperature = (short)temp;
12686 changed = true;
12687 }
12688 if (volt > (mHistoryCur.batteryVoltage+20)
12689 || volt < (mHistoryCur.batteryVoltage-20)) {
12690 mHistoryCur.batteryVoltage = (char)volt;
12691 changed = true;
12692 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012693 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12694 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012695 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12696 // Only record discharges
12697 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12698 mDischargeCounter.addCountLocked(chargeDiff);
12699 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012700 if (isScreenDoze(mScreenState)) {
12701 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12702 }
Mike Ma15313c92017-11-15 17:58:21 -080012703 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12704 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12705 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12706 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12707 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012708 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012709 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012710 changed = true;
12711 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012712 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12713 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12714 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12715 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012716 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012717 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12718 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12719 modeBits, elapsedRealtime);
12720 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12721 modeBits, elapsedRealtime);
12722 mLastDischargeStepLevel = level;
12723 mMinDischargeStepLevel = level;
12724 mInitStepMode = mCurStepMode;
12725 mModStepMode = 0;
12726 }
12727 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012728 if (level >= 90) {
12729 // If the battery level is at least 90%, always consider the device to be
12730 // charging even if it happens to go down a level.
12731 changed |= setChargingLocked(true);
12732 mLastChargeStepLevel = level;
12733 } if (!mCharging) {
12734 if (mLastChargeStepLevel < level) {
12735 // We have not reporting that we are charging, but the level has now
12736 // gone up, so consider the state to be charging.
12737 changed |= setChargingLocked(true);
12738 mLastChargeStepLevel = level;
12739 }
12740 } else {
12741 if (mLastChargeStepLevel > level) {
12742 // We had reported that the device was charging, but here we are with
12743 // power connected and the level going down. Looks like the current
12744 // power supplied isn't enough, so consider the device to now be
12745 // discharging.
12746 changed |= setChargingLocked(false);
12747 mLastChargeStepLevel = level;
12748 }
12749 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012750 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12751 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12752 modeBits, elapsedRealtime);
12753 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12754 modeBits, elapsedRealtime);
12755 mLastChargeStepLevel = level;
12756 mMaxChargeStepLevel = level;
12757 mInitStepMode = mCurStepMode;
12758 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012759 }
12760 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012761 if (changed) {
12762 addHistoryRecordLocked(elapsedRealtime, uptime);
12763 }
Evan Millarc64edde2009-04-18 12:26:32 -070012764 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012765 if (!onBattery &&
12766 (status == BatteryManager.BATTERY_STATUS_FULL ||
12767 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12768 // We don't record history while we are plugged in and fully charged
12769 // (or when battery is not present). The next time we are
12770 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012771 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012772 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012773
Jocelyn Dangc627d102017-04-14 13:15:14 -070012774 if (mMinLearnedBatteryCapacity == -1) {
12775 mMinLearnedBatteryCapacity = chargeFullUAh;
12776 } else {
12777 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012778 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012779 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012780 }
12781
Sudheer Shankac57729a2018-02-09 15:44:42 -080012782 public static boolean isOnBattery(int plugType, int status) {
12783 return plugType == BATTERY_PLUGGED_NONE && status != BatteryManager.BATTERY_STATUS_UNKNOWN;
12784 }
12785
Bookatz8c6571b2017-10-24 15:04:41 -070012786 // Inform StatsLog of setBatteryState changes.
12787 // If this is the first reporting, pass in recentPast == null.
12788 private void reportChangesToStatsLog(HistoryItem recentPast,
12789 final int status, final int plugType, final int level, final int temp) {
12790
12791 if (recentPast == null || recentPast.batteryStatus != status) {
12792 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12793 }
12794 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12795 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12796 }
12797 if (recentPast == null || recentPast.batteryLevel != level) {
12798 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12799 }
12800 // Let's just always print the temperature, regardless of whether it changed.
12801 StatsLog.write(StatsLog.DEVICE_TEMPERATURE_REPORTED, temp);
12802 }
12803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012804 public long getAwakeTimeBattery() {
12805 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12806 }
12807
12808 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012809 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012810 }
12811
12812 @Override
12813 public long computeUptime(long curTime, int which) {
12814 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012815 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012816 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012817 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012818 }
12819 return 0;
12820 }
12821
12822 @Override
12823 public long computeRealtime(long curTime, int which) {
12824 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012825 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012826 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012827 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012828 }
12829 return 0;
12830 }
12831
12832 @Override
12833 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012834 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012835 }
12836
12837 @Override
12838 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012839 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012840 }
12841
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012842 @Override
12843 public long computeBatteryScreenOffUptime(long curTime, int which) {
12844 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12845 }
12846
12847 @Override
12848 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12849 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012850 }
12851
Dianne Hackborn260c5022014-04-29 11:23:16 -070012852 private long computeTimePerLevel(long[] steps, int numSteps) {
12853 // For now we'll do a simple average across all steps.
12854 if (numSteps <= 0) {
12855 return -1;
12856 }
12857 long total = 0;
12858 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012859 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012860 }
12861 return total / numSteps;
12862 /*
12863 long[] buckets = new long[numSteps];
12864 int numBuckets = 0;
12865 int numToAverage = 4;
12866 int i = 0;
12867 while (i < numSteps) {
12868 long totalTime = 0;
12869 int num = 0;
12870 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012871 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012872 num++;
12873 }
12874 buckets[numBuckets] = totalTime / num;
12875 numBuckets++;
12876 numToAverage *= 2;
12877 i += num;
12878 }
12879 if (numBuckets < 1) {
12880 return -1;
12881 }
12882 long averageTime = buckets[numBuckets-1];
12883 for (i=numBuckets-2; i>=0; i--) {
12884 averageTime = (averageTime + buckets[i]) / 2;
12885 }
12886 return averageTime;
12887 */
12888 }
12889
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012890 @Override
12891 public long computeBatteryTimeRemaining(long curTime) {
12892 if (!mOnBattery) {
12893 return -1;
12894 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012895 /* Simple implementation just looks at the average discharge per level across the
12896 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012897 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12898 if (discharge < 2) {
12899 return -1;
12900 }
12901 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12902 if (duration < 1000*1000) {
12903 return -1;
12904 }
12905 long usPerLevel = duration/discharge;
12906 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012907 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012908 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012909 return -1;
12910 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012911 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012912 if (msPerLevel <= 0) {
12913 return -1;
12914 }
12915 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012916 }
12917
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012918 @Override
12919 public LevelStepTracker getDischargeLevelStepTracker() {
12920 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012921 }
12922
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012923 @Override
12924 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12925 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012926 }
12927
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012928 @Override
12929 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012930 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012931 // Not yet working.
12932 return -1;
12933 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012934 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012935 int curLevel = mCurrentBatteryLevel;
12936 int plugLevel = mDischargePlugLevel;
12937 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12938 return -1;
12939 }
12940 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12941 if (duration < 1000*1000) {
12942 return -1;
12943 }
12944 long usPerLevel = duration/(curLevel-plugLevel);
12945 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012946 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012947 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012948 return -1;
12949 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012950 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012951 if (msPerLevel <= 0) {
12952 return -1;
12953 }
12954 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012955 }
12956
Siddharth Raya1fd0572017-11-13 14:20:47 -080012957 /*@hide */
12958 public CellularBatteryStats getCellularBatteryStats() {
12959 CellularBatteryStats s = new CellularBatteryStats();
12960 final int which = STATS_SINCE_CHARGED;
12961 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12962 final ControllerActivityCounter counter = getModemControllerActivity();
12963 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12964 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12965 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12966 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12967 for (int i = 0; i < timeInRatMs.length; i++) {
12968 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12969 }
12970 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12971 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12972 timeInRxSignalStrengthLevelMs[i]
12973 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12974 }
12975 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12976 counter.getTxTimeCounters().length)];
12977 long totalTxTimeMs = 0;
12978 for (int i = 0; i < txTimeMs.length; i++) {
12979 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12980 totalTxTimeMs += txTimeMs[i];
12981 }
12982 final long totalControllerActivityTimeMs
12983 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12984 final long sleepTimeMs
12985 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + totalTxTimeMs);
12986 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12987 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12988 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12989 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12990 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12991 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
12992 s.setSleepTimeMs(sleepTimeMs);
12993 s.setIdleTimeMs(idleTimeMs);
12994 s.setRxTimeMs(rxTimeMs);
12995 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12996 s.setTimeInRatMs(timeInRatMs);
12997 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
12998 s.setTxTimeMs(txTimeMs);
12999 return s;
13000 }
13001
Siddharth Rayb50a6842017-12-14 15:15:28 -080013002 /*@hide */
13003 public WifiBatteryStats getWifiBatteryStats() {
13004 WifiBatteryStats s = new WifiBatteryStats();
13005 final int which = STATS_SINCE_CHARGED;
13006 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13007 final ControllerActivityCounter counter = getWifiControllerActivity();
13008 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
13009 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
13010 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
13011 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
13012 final long totalControllerActivityTimeMs
13013 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
13014 final long sleepTimeMs
13015 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
13016 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
13017 long numAppScanRequest = 0;
13018 for (int i = 0; i < mUidStats.size(); i++) {
13019 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
13020 }
13021 long[] timeInStateMs = new long[NUM_WIFI_STATES];
13022 for (int i=0; i<NUM_WIFI_STATES; i++) {
13023 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
13024 }
13025 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
13026 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13027 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
13028 }
13029 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
13030 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13031 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
13032 }
13033 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13034 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
13035 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
13036 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
13037 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
13038 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
13039 s.setSleepTimeMs(sleepTimeMs);
13040 s.setIdleTimeMs(idleTimeMs);
13041 s.setRxTimeMs(rxTimeMs);
13042 s.setTxTimeMs(txTimeMs);
13043 s.setScanTimeMs(scanTimeMs);
13044 s.setEnergyConsumedMaMs(energyConsumedMaMs);
13045 s.setNumAppScanRequest(numAppScanRequest);
13046 s.setTimeInStateMs(timeInStateMs);
13047 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
13048 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
13049 return s;
13050 }
13051
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013052 /*@hide */
13053 public GpsBatteryStats getGpsBatteryStats() {
13054 GpsBatteryStats s = new GpsBatteryStats();
13055 final int which = STATS_SINCE_CHARGED;
13056 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
13057 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
13058 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
13059 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
13060 for (int i=0; i<time.length; i++) {
13061 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
13062 }
13063 s.setTimeInGpsSignalQualityLevel(time);
13064 return s;
13065 }
13066
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013067 @Override
13068 public LevelStepTracker getChargeLevelStepTracker() {
13069 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013070 }
13071
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013072 @Override
13073 public LevelStepTracker getDailyChargeLevelStepTracker() {
13074 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070013075 }
13076
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013077 @Override
13078 public ArrayList<PackageChange> getDailyPackageChanges() {
13079 return mDailyPackageChanges;
13080 }
13081
Joe Onoratoe1acd632016-02-23 13:25:10 -080013082 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013083 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013084 }
13085
13086 @Override
13087 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013088 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013089 }
13090
13091 @Override
13092 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013093 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013094 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070013095
The Android Open Source Project10592532009-03-18 17:39:46 -070013096 @Override
Evan Millar633a1742009-04-02 16:36:33 -070013097 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013098 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013099 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013100 }
13101 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013102
Evan Millar633a1742009-04-02 16:36:33 -070013103 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013104 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013105 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013106
The Android Open Source Project10592532009-03-18 17:39:46 -070013107 @Override
Evan Millar633a1742009-04-02 16:36:33 -070013108 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070013109 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070013110 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070013111 }
13112 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013113
Evan Millar633a1742009-04-02 16:36:33 -070013114 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013115 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070013116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013117
Amith Yamasanie43530a2009-08-21 13:11:37 -070013118 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013119 public int getLowDischargeAmountSinceCharge() {
13120 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013121 int val = mLowDischargeAmountSinceCharge;
13122 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13123 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
13124 }
13125 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013126 }
13127 }
13128
13129 @Override
13130 public int getHighDischargeAmountSinceCharge() {
13131 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080013132 int val = mHighDischargeAmountSinceCharge;
13133 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
13134 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
13135 }
13136 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013137 }
13138 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013139
13140 @Override
13141 public int getDischargeAmount(int which) {
13142 int dischargeAmount = which == STATS_SINCE_CHARGED
13143 ? getHighDischargeAmountSinceCharge()
13144 : (getDischargeStartLevel() - getDischargeCurrentLevel());
13145 if (dischargeAmount < 0) {
13146 dischargeAmount = 0;
13147 }
13148 return dischargeAmount;
13149 }
13150
Mike Mac2f518a2017-09-19 16:06:03 -070013151 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013152 public int getDischargeAmountScreenOn() {
13153 synchronized(this) {
13154 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070013155 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013156 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13157 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13158 }
13159 return val;
13160 }
13161 }
13162
Mike Mac2f518a2017-09-19 16:06:03 -070013163 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013164 public int getDischargeAmountScreenOnSinceCharge() {
13165 synchronized(this) {
13166 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070013167 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013168 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
13169 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
13170 }
13171 return val;
13172 }
13173 }
13174
Mike Mac2f518a2017-09-19 16:06:03 -070013175 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013176 public int getDischargeAmountScreenOff() {
13177 synchronized(this) {
13178 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070013179 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013180 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13181 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13182 }
Mike Mac2f518a2017-09-19 16:06:03 -070013183 // For backward compatibility, doze discharge is counted into screen off.
13184 return val + getDischargeAmountScreenDoze();
13185 }
13186 }
13187
13188 @Override
13189 public int getDischargeAmountScreenOffSinceCharge() {
13190 synchronized(this) {
13191 int val = mDischargeAmountScreenOffSinceCharge;
13192 if (mOnBattery && isScreenOff(mScreenState)
13193 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
13194 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
13195 }
13196 // For backward compatibility, doze discharge is counted into screen off.
13197 return val + getDischargeAmountScreenDozeSinceCharge();
13198 }
13199 }
13200
13201 @Override
13202 public int getDischargeAmountScreenDoze() {
13203 synchronized(this) {
13204 int val = mDischargeAmountScreenDoze;
13205 if (mOnBattery && isScreenDoze(mScreenState)
13206 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13207 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
13208 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013209 return val;
13210 }
13211 }
13212
Mike Mac2f518a2017-09-19 16:06:03 -070013213 @Override
13214 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013215 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070013216 int val = mDischargeAmountScreenDozeSinceCharge;
13217 if (mOnBattery && isScreenDoze(mScreenState)
13218 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
13219 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013220 }
13221 return val;
13222 }
13223 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013225 /**
13226 * Retrieve the statistics object for a particular uid, creating if needed.
13227 */
13228 public Uid getUidStatsLocked(int uid) {
13229 Uid u = mUidStats.get(uid);
13230 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080013231 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013232 mUidStats.put(uid, u);
13233 }
13234 return u;
13235 }
13236
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013237 /**
13238 * Retrieve the statistics object for a particular uid. Returns null if the object is not
13239 * available.
13240 */
13241 public Uid getAvailableUidStatsLocked(int uid) {
13242 Uid u = mUidStats.get(uid);
13243 return u;
13244 }
13245
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013246 public void onCleanupUserLocked(int userId) {
13247 final int firstUidForUser = UserHandle.getUid(userId, 0);
13248 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13249 mKernelUidCpuFreqTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
13250 mKernelUidCpuTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013251 if (mKernelSingleUidTimeReader != null) {
13252 mKernelSingleUidTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
13253 }
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070013254 }
13255
13256 public void onUserRemovedLocked(int userId) {
13257 final int firstUidForUser = UserHandle.getUid(userId, 0);
13258 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
13259 mUidStats.put(firstUidForUser, null);
13260 mUidStats.put(lastUidForUser, null);
13261 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
13262 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
13263 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
13264 }
13265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013266 /**
13267 * Remove the statistics object for a particular uid.
13268 */
13269 public void removeUidStatsLocked(int uid) {
Adam Lesinskib83ffee2015-05-12 14:43:47 -070013270 mKernelUidCpuTimeReader.removeUid(uid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -070013271 mKernelUidCpuFreqTimeReader.removeUid(uid);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013272 if (mKernelSingleUidTimeReader != null) {
13273 mKernelSingleUidTimeReader.removeUid(uid);
13274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013275 mUidStats.remove(uid);
13276 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070013277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013278 /**
13279 * Retrieve the statistics object for a particular process, creating
13280 * if needed.
13281 */
13282 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013283 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013284 Uid u = getUidStatsLocked(uid);
13285 return u.getProcessStatsLocked(name);
13286 }
13287
13288 /**
13289 * Retrieve the statistics object for a particular process, creating
13290 * if needed.
13291 */
13292 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013293 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013294 Uid u = getUidStatsLocked(uid);
13295 return u.getPackageStatsLocked(pkg);
13296 }
13297
13298 /**
13299 * Retrieve the statistics object for a particular service, creating
13300 * if needed.
13301 */
13302 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070013303 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013304 Uid u = getUidStatsLocked(uid);
13305 return u.getServiceStatsLocked(pkg, name);
13306 }
13307
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013308 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080013309 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013310 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013311 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013312 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013313
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013314 public boolean trackPerProcStateCpuTimes() {
13315 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
13316 }
13317
13318 public void systemServicesReady(Context context) {
13319 mConstants.startObserving(context.getContentResolver());
13320 }
13321
13322 @VisibleForTesting
13323 public final class Constants extends ContentObserver {
13324 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
13325 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080013326 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
13327 = "track_cpu_active_cluster_time";
13328 public static final String KEY_READ_BINARY_CPU_TIME
13329 = "read_binary_cpu_time";
Sudheer Shankac20379e2018-02-15 00:06:21 -080013330 public static final String KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS
13331 = "proc_state_cpu_times_read_delay_ms";
Mike Ma2ab01442018-02-13 14:22:47 -080013332 public static final String KEY_KERNEL_UID_READERS_THROTTLE_TIME
13333 = "kernel_uid_readers_throttle_time";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013334
13335 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080013336 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
13337 private static final boolean DEFAULT_READ_BINARY_CPU_TIME = false;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013338 private static final long DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS = 5_000;
Mike Ma2ab01442018-02-13 14:22:47 -080013339 private static final long DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME = 10_000;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013340
13341 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080013342 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
Mike Mafae87da2018-01-19 20:07:20 -080013343 public boolean READ_BINARY_CPU_TIME = DEFAULT_READ_BINARY_CPU_TIME;
Sudheer Shankac20379e2018-02-15 00:06:21 -080013344 public long PROC_STATE_CPU_TIMES_READ_DELAY_MS = DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS;
Mike Ma2ab01442018-02-13 14:22:47 -080013345 public long KERNEL_UID_READERS_THROTTLE_TIME = DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013346
13347 private ContentResolver mResolver;
13348 private final KeyValueListParser mParser = new KeyValueListParser(',');
13349
13350 public Constants(Handler handler) {
13351 super(handler);
13352 }
13353
13354 public void startObserving(ContentResolver resolver) {
13355 mResolver = resolver;
13356 mResolver.registerContentObserver(
13357 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
13358 false /* notifyForDescendants */, this);
13359 updateConstants();
13360 }
13361
13362 @Override
13363 public void onChange(boolean selfChange, Uri uri) {
13364 updateConstants();
13365 }
13366
13367 private void updateConstants() {
13368 synchronized (BatteryStatsImpl.this) {
13369 try {
13370 mParser.setString(Settings.Global.getString(mResolver,
13371 Settings.Global.BATTERY_STATS_CONSTANTS));
13372 } catch (IllegalArgumentException e) {
13373 // Failed to parse the settings string, log this and move on
13374 // with defaults.
13375 Slog.e(TAG, "Bad batterystats settings", e);
13376 }
13377
13378 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13379 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13380 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013381 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13382 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
Mike Ma2ab01442018-02-13 14:22:47 -080013383 updateReadBinaryCpuTime(READ_BINARY_CPU_TIME,
13384 mParser.getBoolean(KEY_READ_BINARY_CPU_TIME, DEFAULT_READ_BINARY_CPU_TIME));
Sudheer Shankac20379e2018-02-15 00:06:21 -080013385 updateProcStateCpuTimesReadDelayMs(PROC_STATE_CPU_TIMES_READ_DELAY_MS,
13386 mParser.getLong(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS,
Mike Ma2ab01442018-02-13 14:22:47 -080013387 DEFAULT_PROC_STATE_CPU_TIMES_READ_DELAY_MS));
13388 updateKernelUidReadersThrottleTime(KERNEL_UID_READERS_THROTTLE_TIME,
13389 mParser.getLong(KEY_KERNEL_UID_READERS_THROTTLE_TIME,
13390 DEFAULT_KERNEL_UID_READERS_THROTTLE_TIME));
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013391 }
13392 }
13393
13394 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13395 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13396 if (isEnabled && !wasEnabled) {
13397 mKernelSingleUidTimeReader.markDataAsStale(true);
13398 mExternalSync.scheduleCpuSyncDueToSettingChange();
Sudheer Shankac20379e2018-02-15 00:06:21 -080013399
13400 mNumCpuTimeReads = 0;
13401 mNumBatchedCpuTimeReads = 0;
13402 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
13403 }
13404 }
13405
Mike Ma2ab01442018-02-13 14:22:47 -080013406 private void updateReadBinaryCpuTime(boolean oldEnabled, boolean isEnabled) {
13407 READ_BINARY_CPU_TIME = isEnabled;
13408 if (oldEnabled != isEnabled) {
13409 mKernelUidCpuFreqTimeReader.setReadBinary(isEnabled);
13410 }
13411 }
13412
Sudheer Shankac20379e2018-02-15 00:06:21 -080013413 private void updateProcStateCpuTimesReadDelayMs(long oldDelayMillis, long newDelayMillis) {
13414 PROC_STATE_CPU_TIMES_READ_DELAY_MS = newDelayMillis;
13415 if (oldDelayMillis != newDelayMillis) {
13416 mNumCpuTimeReads = 0;
13417 mNumBatchedCpuTimeReads = 0;
13418 mCpuTimeReadsTrackingStartTime = mClocks.uptimeMillis();
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013419 }
13420 }
13421
Mike Ma2ab01442018-02-13 14:22:47 -080013422 private void updateKernelUidReadersThrottleTime(long oldTimeMs, long newTimeMs) {
13423 KERNEL_UID_READERS_THROTTLE_TIME = newTimeMs;
13424 if (oldTimeMs != newTimeMs) {
13425 mKernelUidCpuFreqTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13426 mKernelUidCpuActiveTimeReader.setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13427 mKernelUidCpuClusterTimeReader
13428 .setThrottleInterval(KERNEL_UID_READERS_THROTTLE_TIME);
13429 }
13430 }
13431
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013432 public void dumpLocked(PrintWriter pw) {
13433 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13434 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013435 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13436 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
13437 pw.print(KEY_READ_BINARY_CPU_TIME); pw.print("=");
13438 pw.println(READ_BINARY_CPU_TIME);
Sudheer Shankac20379e2018-02-15 00:06:21 -080013439 pw.print(KEY_PROC_STATE_CPU_TIMES_READ_DELAY_MS); pw.print("=");
13440 pw.println(PROC_STATE_CPU_TIMES_READ_DELAY_MS);
Mike Ma2ab01442018-02-13 14:22:47 -080013441 pw.print(KEY_KERNEL_UID_READERS_THROTTLE_TIME); pw.print("=");
13442 pw.println(KERNEL_UID_READERS_THROTTLE_TIME);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013443 }
13444 }
13445
Andreas Gampe3f24e692018-02-05 13:24:28 -080013446 @GuardedBy("this")
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013447 public void dumpConstantsLocked(PrintWriter pw) {
13448 mConstants.dumpLocked(pw);
13449 }
13450
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013451 Parcel mPendingWrite = null;
13452 final ReentrantLock mWriteLock = new ReentrantLock();
13453
13454 public void writeAsyncLocked() {
13455 writeLocked(false);
13456 }
13457
13458 public void writeSyncLocked() {
13459 writeLocked(true);
13460 }
13461
13462 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013463 if (mFile == null) {
13464 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013465 return;
13466 }
13467
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013468 if (mShuttingDown) {
13469 return;
13470 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013471
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013472 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013473 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013474 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013475
13476 if (mPendingWrite != null) {
13477 mPendingWrite.recycle();
13478 }
13479 mPendingWrite = out;
13480
13481 if (sync) {
13482 commitPendingDataToDisk();
13483 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013484 BackgroundThread.getHandler().post(new Runnable() {
13485 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013486 commitPendingDataToDisk();
13487 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013488 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013489 }
13490 }
13491
13492 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013493 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013494 synchronized (this) {
13495 next = mPendingWrite;
13496 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013497 if (next == null) {
13498 return;
13499 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013500 }
13501
Amith Yamasanid2450862017-02-07 15:58:24 -080013502 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013503 try {
Dianne Hackborne17b4452018-01-10 13:15:40 -080013504 final long startTime = SystemClock.uptimeMillis();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013505 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013506 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013507 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013508 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013509 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013510 mFile.commit();
Dianne Hackborne17b4452018-01-10 13:15:40 -080013511 com.android.internal.logging.EventLogTags.writeCommitSysConfigFile(
13512 "batterystats", SystemClock.uptimeMillis() - startTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013513 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013514 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013515 mFile.rollback();
13516 } finally {
13517 next.recycle();
13518 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013520 }
13521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013522 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013523 if (mDailyFile != null) {
13524 readDailyStatsLocked();
13525 }
13526
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013527 if (mFile == null) {
13528 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013529 return;
13530 }
13531
13532 mUidStats.clear();
13533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013534 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013535 File file = mFile.chooseForRead();
13536 if (!file.exists()) {
13537 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013538 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013539 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013540
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013541 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013542 Parcel in = Parcel.obtain();
13543 in.unmarshall(raw, 0, raw.length);
13544 in.setDataPosition(0);
13545 stream.close();
13546
13547 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013548 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013549 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013550 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013551 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013552
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013553 mEndPlatformVersion = Build.ID;
13554
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013555 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013556 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013557 final long elapsedRealtime = mClocks.elapsedRealtime();
13558 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013559 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013560 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013561 }
Narayan Kamath5a5a7fe2018-02-05 17:30:06 +000013562 addHistoryBufferLocked(elapsedRealtime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013563 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013564 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013565
13566 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013567 }
13568
13569 public int describeContents() {
13570 return 0;
13571 }
13572
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013573 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013574 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013575
13576 mHistoryBuffer.setDataSize(0);
13577 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013578 mHistoryTagPool.clear();
13579 mNextHistoryTagIdx = 0;
13580 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013581
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013582 int numTags = in.readInt();
13583 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013584 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013585 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013586 if (str == null) {
13587 throw new ParcelFormatException("null history tag string");
13588 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013589 int uid = in.readInt();
13590 HistoryTag tag = new HistoryTag();
13591 tag.string = str;
13592 tag.uid = uid;
13593 tag.poolIdx = idx;
13594 mHistoryTagPool.put(tag, idx);
13595 if (idx >= mNextHistoryTagIdx) {
13596 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013597 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013598 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013599 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013600
13601 int bufSize = in.readInt();
13602 int curPos = in.dataPosition();
13603 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013604 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13605 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013606 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013607 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13608 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013609 } else {
13610 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13611 + " bytes at " + curPos);
13612 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13613 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013614 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013615
Dianne Hackbornae384452011-06-28 12:33:48 -070013616 if (andOldHistory) {
13617 readOldHistory(in);
13618 }
13619
13620 if (DEBUG_HISTORY) {
13621 StringBuilder sb = new StringBuilder(128);
13622 sb.append("****************** OLD mHistoryBaseTime: ");
13623 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13624 Slog.i(TAG, sb.toString());
13625 }
13626 mHistoryBaseTime = historyBaseTime;
13627 if (DEBUG_HISTORY) {
13628 StringBuilder sb = new StringBuilder(128);
13629 sb.append("****************** NEW mHistoryBaseTime: ");
13630 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13631 Slog.i(TAG, sb.toString());
13632 }
13633
13634 // We are just arbitrarily going to insert 1 minute from the sample of
13635 // the last run until samples in this run.
13636 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013637 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013638 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013639 if (DEBUG_HISTORY) {
13640 StringBuilder sb = new StringBuilder(128);
13641 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13642 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13643 Slog.i(TAG, sb.toString());
13644 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013645 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013646 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013647
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013648 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013649 if (!USE_OLD_HISTORY) {
13650 return;
13651 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013652 mHistory = mHistoryEnd = mHistoryCache = null;
13653 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013654 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013655 HistoryItem rec = new HistoryItem(time, in);
13656 addHistoryRecordLocked(rec);
13657 }
13658 }
13659
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013660 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013661 if (DEBUG_HISTORY) {
13662 StringBuilder sb = new StringBuilder(128);
13663 sb.append("****************** WRITING mHistoryBaseTime: ");
13664 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013665 sb.append(" mLastHistoryElapsedRealtime: ");
13666 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013667 Slog.i(TAG, sb.toString());
13668 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013669 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013670 if (!inclData) {
13671 out.writeInt(0);
13672 out.writeInt(0);
13673 return;
13674 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013675 out.writeInt(mHistoryTagPool.size());
13676 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13677 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013678 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013679 out.writeString(tag.string);
13680 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013681 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013682 out.writeInt(mHistoryBuffer.dataSize());
13683 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13684 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13685 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013686
13687 if (andOldHistory) {
13688 writeOldHistory(out);
13689 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013690 }
13691
13692 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013693 if (!USE_OLD_HISTORY) {
13694 return;
13695 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013696 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013697 while (rec != null) {
13698 if (rec.time >= 0) rec.writeToParcel(out, 0);
13699 rec = rec.next;
13700 }
13701 out.writeLong(-1);
13702 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013703
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013704 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013705 final int version = in.readInt();
13706 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013707 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013708 + ", expected " + VERSION + "; erasing old stats");
13709 return;
13710 }
13711
Dianne Hackbornae384452011-06-28 12:33:48 -070013712 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013714 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013715 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013716 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013717 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013718 mStartPlatformVersion = in.readString();
13719 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013720 mOnBatteryTimeBase.readSummaryFromParcel(in);
13721 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013722 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013723 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013724 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013725 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013726 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013727 mMinLearnedBatteryCapacity = in.readInt();
13728 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013729 mLowDischargeAmountSinceCharge = in.readInt();
13730 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013731 mDischargeAmountScreenOnSinceCharge = in.readInt();
13732 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013733 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013734 mDischargeStepTracker.readFromParcel(in);
13735 mChargeStepTracker.readFromParcel(in);
13736 mDailyDischargeStepTracker.readFromParcel(in);
13737 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013738 mDischargeCounter.readSummaryFromParcelLocked(in);
13739 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013740 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013741 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13742 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013743 int NPKG = in.readInt();
13744 if (NPKG > 0) {
13745 mDailyPackageChanges = new ArrayList<>(NPKG);
13746 while (NPKG > 0) {
13747 NPKG--;
13748 PackageChange pc = new PackageChange();
13749 pc.mPackageName = in.readString();
13750 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013751 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013752 mDailyPackageChanges.add(pc);
13753 }
13754 } else {
13755 mDailyPackageChanges = null;
13756 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013757 mDailyStartTime = in.readLong();
13758 mNextMinDailyDeadline = in.readLong();
13759 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013761 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013762
Jeff Browne95c3cd2014-05-02 16:59:26 -070013763 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013764 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013765 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013766 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13767 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13768 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013769 mInteractive = false;
13770 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013771 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013772 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013773 mLongestLightIdleTime = in.readLong();
13774 mLongestFullIdleTime = in.readLong();
13775 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13776 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13777 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013778 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013779 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013780 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013781 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13782 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013783 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013784 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13785 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13786 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013787 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013788 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13789 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013790 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013791 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013792 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013793 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013794 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013795 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13796 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013797 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013798 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013799 mWifiOn = false;
13800 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013801 mGlobalWifiRunning = false;
13802 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013803 for (int i=0; i<NUM_WIFI_STATES; i++) {
13804 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13805 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013806 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13807 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13808 }
13809 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13810 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13811 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013812 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13813 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013814 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13815 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13816 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013817 mBluetoothActivity.readSummaryFromParcel(in);
13818 mModemActivity.readSummaryFromParcel(in);
13819 mHasWifiReporting = in.readInt() != 0;
13820 mHasBluetoothReporting = in.readInt() != 0;
13821 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013822
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013823 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013824 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013825 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013826 mCameraOnNesting = 0;
13827 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013828 mBluetoothScanNesting = 0;
13829 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080013830 mIsCellularTxPowerHigh = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013831
Bookatz50df7112017-08-04 14:53:26 -070013832 int NRPMS = in.readInt();
13833 if (NRPMS > 10000) {
13834 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13835 }
13836 for (int irpm = 0; irpm < NRPMS; irpm++) {
13837 if (in.readInt() != 0) {
13838 String rpmName = in.readString();
13839 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13840 }
13841 }
13842 int NSORPMS = in.readInt();
13843 if (NSORPMS > 10000) {
13844 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13845 }
13846 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13847 if (in.readInt() != 0) {
13848 String rpmName = in.readString();
13849 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13850 }
13851 }
13852
Evan Millarc64edde2009-04-18 12:26:32 -070013853 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013854 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013855 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013856 }
Evan Millarc64edde2009-04-18 12:26:32 -070013857 for (int ikw = 0; ikw < NKW; ikw++) {
13858 if (in.readInt() != 0) {
13859 String kwltName = in.readString();
13860 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13861 }
13862 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013863
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013864 int NWR = in.readInt();
13865 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013866 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013867 }
13868 for (int iwr = 0; iwr < NWR; iwr++) {
13869 if (in.readInt() != 0) {
13870 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013871 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013872 }
13873 }
13874
James Carr3a226052016-07-01 14:49:52 -070013875 int NMS = in.readInt();
13876 for (int ims = 0; ims < NMS; ims++) {
13877 if (in.readInt() != 0) {
13878 long kmstName = in.readLong();
13879 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13880 }
13881 }
13882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013883 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013884 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013885 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013887 for (int iu = 0; iu < NU; iu++) {
13888 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013889 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013890 mUidStats.put(uid, u);
13891
Bookatz867c0d72017-03-07 18:23:42 -080013892 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013893 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013894
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013895 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013896 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013897 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013898 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013899 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013900 if (in.readInt() != 0) {
13901 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13902 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013903 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013904 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013905 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013906 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013907 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13908 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13909 if (in.readInt() != 0) {
13910 u.makeWifiBatchedScanBin(i, null);
13911 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13912 }
13913 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013914 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013915 if (in.readInt() != 0) {
13916 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13917 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013918 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013919 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013920 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013921 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013922 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13923 }
13924 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013925 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13926 }
13927 if (in.readInt() != 0) {
13928 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13929 }
13930 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013931 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13932 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013933 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013934 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13935 }
13936 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013937 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13938 }
13939 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013940 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13941 }
Bookatz956f36bf2017-04-28 09:48:17 -070013942 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013943 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13944 }
13945 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013946 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13947 }
Bookatzb1f04f32017-05-19 13:57:32 -070013948 if (in.readInt() != 0) {
13949 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13950 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013951 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013952 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13953 if (in.readInt() != 0) {
13954 u.makeProcessState(i, null);
13955 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13956 }
13957 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013958 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013959 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013960 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013961
Dianne Hackborn617f8772009-03-31 15:04:46 -070013962 if (in.readInt() != 0) {
13963 if (u.mUserActivityCounters == null) {
13964 u.initUserActivityLocked();
13965 }
13966 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13967 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13968 }
13969 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013970
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013971 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013972 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013973 u.initNetworkActivityLocked();
13974 }
13975 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013976 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13977 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013978 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013979 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13980 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013981 }
13982
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013983 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13984 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13985
Adam Lesinski6832f392015-09-05 18:05:40 -070013986 if (in.readInt() != 0) {
13987 final int numClusters = in.readInt();
13988 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13989 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013990 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013991
Sudheer Shankaaf857412017-07-21 00:14:24 -070013992 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013993 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013994 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013995 final int NSB = in.readInt();
13996 if (mPowerProfile != null &&
13997 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13998 throw new ParcelFormatException("File corrupt: too many speed bins " +
13999 NSB);
14000 }
14001
Sudheer Shankaaf857412017-07-21 00:14:24 -070014002 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070014003 for (int speed = 0; speed < NSB; speed++) {
14004 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014005 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070014006 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014007 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070014008 }
14009 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070014010 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014011 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070014012 }
14013 }
14014 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070014015 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014016 }
14017
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014018 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14019 in, mOnBatteryTimeBase);
14020 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
14021 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070014022
14023 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
14024 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
14025
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014026 int length = in.readInt();
14027 if (length == Uid.NUM_PROCESS_STATE) {
14028 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
14029 for (int procState = 0; procState < length; ++procState) {
14030 u.mProcStateTimeMs[procState]
14031 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14032 in, mOnBatteryTimeBase);
14033 }
14034 } else {
14035 u.mProcStateTimeMs = null;
14036 }
14037 length = in.readInt();
14038 if (length == Uid.NUM_PROCESS_STATE) {
14039 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
14040 for (int procState = 0; procState < length; ++procState) {
14041 u.mProcStateScreenOffTimeMs[procState]
14042 = LongSamplingCounterArray.readSummaryFromParcelLocked(
14043 in, mOnBatteryScreenOffTimeBase);
14044 }
14045 } else {
14046 u.mProcStateScreenOffTimeMs = null;
14047 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014048
14049 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070014050 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14051 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
14052 } else {
14053 u.mMobileRadioApWakeupCount = null;
14054 }
14055
14056 if (in.readInt() != 0) {
14057 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
14058 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
14059 } else {
14060 u.mWifiRadioApWakeupCount = null;
14061 }
14062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014063 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014064 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014065 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014067 for (int iw = 0; iw < NW; iw++) {
14068 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014069 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014070 }
14071
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014072 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014073 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014074 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014075 }
14076 for (int is = 0; is < NS; is++) {
14077 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014078 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014079 }
14080
14081 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070014082 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014083 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014084 }
14085 for (int ij = 0; ij < NJ; ij++) {
14086 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014087 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014088 }
14089
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014090 u.readJobCompletionsFromParcelLocked(in);
14091
Amith Yamasani977e11f2018-02-16 11:29:54 -080014092 u.mJobsDeferredEventCount.readSummaryFromParcelLocked(in);
14093 u.mJobsDeferredCount.readSummaryFromParcelLocked(in);
14094 u.mJobsFreshnessTimeMs.readSummaryFromParcelLocked(in);
14095 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14096 if (in.readInt() != 0) {
14097 u.mJobsFreshnessBuckets[i] = new Counter(u.mBsi.mOnBatteryTimeBase);
14098 u.mJobsFreshnessBuckets[i].readSummaryFromParcelLocked(in);
14099 }
14100 }
14101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014102 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014103 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014104 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014106 for (int is = 0; is < NP; is++) {
14107 int seNumber = in.readInt();
14108 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080014109 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014110 }
14111 }
14112
14113 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014114 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014115 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014117 for (int ip = 0; ip < NP; ip++) {
14118 String procName = in.readString();
14119 Uid.Proc p = u.getProcessStatsLocked(procName);
14120 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014121 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014122 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014123 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014124 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
14125 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014126 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014127 }
14128
14129 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014130 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014131 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070014132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014133 for (int ip = 0; ip < NP; ip++) {
14134 String pkgName = in.readString();
14135 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014136 final int NWA = in.readInt();
14137 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014138 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014139 }
14140 p.mWakeupAlarms.clear();
14141 for (int iwa=0; iwa<NWA; iwa++) {
14142 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070014143 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014144 c.readSummaryFromParcelLocked(in);
14145 p.mWakeupAlarms.put(tag, c);
14146 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014147 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014148 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070014149 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080014150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014151 for (int is = 0; is < NS; is++) {
14152 String servName = in.readString();
14153 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
14154 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014155 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014156 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014157 }
14158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014159 }
14160 }
14161
14162 /**
14163 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
14164 * disk. This format does not allow a lossless round-trip.
14165 *
14166 * @param out the Parcel to be written to.
14167 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014168 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014169 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014170
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014171 // Pull the clock time. This may update the time and make a new history entry
14172 // if we had originally pulled a time before the RTC was set.
14173 long startClockTime = getStartClockTime();
14174
Joe Onoratoabded112016-02-08 16:49:39 -080014175 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
14176 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014177
14178 out.writeInt(VERSION);
14179
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014180 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014182 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014183 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014184 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014185 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014186 out.writeString(mStartPlatformVersion);
14187 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014188 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
14189 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014190 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014191 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014192 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014193 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014194 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014195 out.writeInt(mMinLearnedBatteryCapacity);
14196 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080014197 out.writeInt(getLowDischargeAmountSinceCharge());
14198 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014199 out.writeInt(getDischargeAmountScreenOnSinceCharge());
14200 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070014201 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014202 mDischargeStepTracker.writeToParcel(out);
14203 mChargeStepTracker.writeToParcel(out);
14204 mDailyDischargeStepTracker.writeToParcel(out);
14205 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070014206 mDischargeCounter.writeSummaryFromParcelLocked(out);
14207 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014208 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080014209 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
14210 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014211 if (mDailyPackageChanges != null) {
14212 final int NPKG = mDailyPackageChanges.size();
14213 out.writeInt(NPKG);
14214 for (int i=0; i<NPKG; i++) {
14215 PackageChange pc = mDailyPackageChanges.get(i);
14216 out.writeString(pc.mPackageName);
14217 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070014218 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014219 }
14220 } else {
14221 out.writeInt(0);
14222 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014223 out.writeLong(mDailyStartTime);
14224 out.writeLong(mNextMinDailyDeadline);
14225 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014226
14227 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070014228 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014229 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014230 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070014231 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014232 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014233 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014234 out.writeLong(mLongestLightIdleTime);
14235 out.writeLong(mLongestFullIdleTime);
14236 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14237 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14238 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014239 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014240 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080014241 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014242 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014243 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014244 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014245 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014246 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070014247 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014248 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014249 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14250 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014251 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014252 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14253 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014254 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014255 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
14256 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014257 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014258 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14259 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014260 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014261 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014262 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014263 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14264 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14265 }
14266 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14267 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14268 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014269 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14270 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014271 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14272 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14273 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014274 mBluetoothActivity.writeSummaryToParcel(out);
14275 mModemActivity.writeSummaryToParcel(out);
14276 out.writeInt(mHasWifiReporting ? 1 : 0);
14277 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14278 out.writeInt(mHasModemReporting ? 1 : 0);
14279
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014280 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014281 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014282 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014283 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014284
Bookatz50df7112017-08-04 14:53:26 -070014285 out.writeInt(mRpmStats.size());
14286 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14287 Timer rpmt = ent.getValue();
14288 if (rpmt != null) {
14289 out.writeInt(1);
14290 out.writeString(ent.getKey());
14291 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14292 } else {
14293 out.writeInt(0);
14294 }
14295 }
14296 out.writeInt(mScreenOffRpmStats.size());
14297 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14298 Timer rpmt = ent.getValue();
14299 if (rpmt != null) {
14300 out.writeInt(1);
14301 out.writeString(ent.getKey());
14302 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14303 } else {
14304 out.writeInt(0);
14305 }
14306 }
14307
Evan Millarc64edde2009-04-18 12:26:32 -070014308 out.writeInt(mKernelWakelockStats.size());
14309 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14310 Timer kwlt = ent.getValue();
14311 if (kwlt != null) {
14312 out.writeInt(1);
14313 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014314 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14315 } else {
14316 out.writeInt(0);
14317 }
14318 }
14319
14320 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014321 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14322 SamplingTimer timer = ent.getValue();
14323 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014324 out.writeInt(1);
14325 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014326 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070014327 } else {
14328 out.writeInt(0);
14329 }
14330 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014331
James Carr3a226052016-07-01 14:49:52 -070014332 out.writeInt(mKernelMemoryStats.size());
14333 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14334 Timer kmt = mKernelMemoryStats.valueAt(i);
14335 if (kmt != null) {
14336 out.writeInt(1);
14337 out.writeLong(mKernelMemoryStats.keyAt(i));
14338 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14339 } else {
14340 out.writeInt(0);
14341 }
14342 }
14343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014344 final int NU = mUidStats.size();
14345 out.writeInt(NU);
14346 for (int iu = 0; iu < NU; iu++) {
14347 out.writeInt(mUidStats.keyAt(iu));
14348 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014349
Bookatz867c0d72017-03-07 18:23:42 -080014350 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070014351 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080014352
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014353 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014354 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014355 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014356 } else {
14357 out.writeInt(0);
14358 }
14359 if (u.mFullWifiLockTimer != null) {
14360 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014361 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014362 } else {
14363 out.writeInt(0);
14364 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070014365 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014366 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014367 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014368 } else {
14369 out.writeInt(0);
14370 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070014371 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
14372 if (u.mWifiBatchedScanTimer[i] != null) {
14373 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014374 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070014375 } else {
14376 out.writeInt(0);
14377 }
14378 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014379 if (u.mWifiMulticastTimer != null) {
14380 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014381 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014382 } else {
14383 out.writeInt(0);
14384 }
14385 if (u.mAudioTurnedOnTimer != null) {
14386 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014387 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014388 } else {
14389 out.writeInt(0);
14390 }
14391 if (u.mVideoTurnedOnTimer != null) {
14392 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014393 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014394 } else {
14395 out.writeInt(0);
14396 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014397 if (u.mFlashlightTurnedOnTimer != null) {
14398 out.writeInt(1);
14399 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14400 } else {
14401 out.writeInt(0);
14402 }
14403 if (u.mCameraTurnedOnTimer != null) {
14404 out.writeInt(1);
14405 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14406 } else {
14407 out.writeInt(0);
14408 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014409 if (u.mForegroundActivityTimer != null) {
14410 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014411 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070014412 } else {
14413 out.writeInt(0);
14414 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070014415 if (u.mForegroundServiceTimer != null) {
14416 out.writeInt(1);
14417 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14418 } else {
14419 out.writeInt(0);
14420 }
Bookatzc8c44962017-05-11 12:12:54 -070014421 if (u.mAggregatedPartialWakelockTimer != null) {
14422 out.writeInt(1);
14423 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14424 } else {
14425 out.writeInt(0);
14426 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014427 if (u.mBluetoothScanTimer != null) {
14428 out.writeInt(1);
14429 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14430 } else {
14431 out.writeInt(0);
14432 }
Bookatzb1f04f32017-05-19 13:57:32 -070014433 if (u.mBluetoothUnoptimizedScanTimer != null) {
14434 out.writeInt(1);
14435 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14436 } else {
14437 out.writeInt(0);
14438 }
Bookatz956f36bf2017-04-28 09:48:17 -070014439 if (u.mBluetoothScanResultCounter != null) {
14440 out.writeInt(1);
14441 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14442 } else {
14443 out.writeInt(0);
14444 }
Bookatzb1f04f32017-05-19 13:57:32 -070014445 if (u.mBluetoothScanResultBgCounter != null) {
14446 out.writeInt(1);
14447 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14448 } else {
14449 out.writeInt(0);
14450 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014451 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14452 if (u.mProcessStateTimer[i] != null) {
14453 out.writeInt(1);
14454 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14455 } else {
14456 out.writeInt(0);
14457 }
14458 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014459 if (u.mVibratorOnTimer != null) {
14460 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014461 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014462 } else {
14463 out.writeInt(0);
14464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014465
Dianne Hackborn617f8772009-03-31 15:04:46 -070014466 if (u.mUserActivityCounters == null) {
14467 out.writeInt(0);
14468 } else {
14469 out.writeInt(1);
14470 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14471 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14472 }
14473 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014474
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014475 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014476 out.writeInt(0);
14477 } else {
14478 out.writeInt(1);
14479 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014480 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14481 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014482 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014483 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14484 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014485 }
14486
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014487 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14488 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14489
Sudheer Shankaaf857412017-07-21 00:14:24 -070014490 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014491 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014492 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14493 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014494 if (cpuSpeeds != null) {
14495 out.writeInt(1);
14496 out.writeInt(cpuSpeeds.length);
14497 for (LongSamplingCounter c : cpuSpeeds) {
14498 if (c != null) {
14499 out.writeInt(1);
14500 c.writeSummaryFromParcelLocked(out);
14501 } else {
14502 out.writeInt(0);
14503 }
14504 }
14505 } else {
14506 out.writeInt(0);
14507 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014508 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014509 } else {
14510 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014511 }
14512
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014513 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14514 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014515
Mike Ma3d422c32017-10-25 11:08:57 -070014516 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14517 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14518
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014519 if (u.mProcStateTimeMs != null) {
14520 out.writeInt(u.mProcStateTimeMs.length);
14521 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14522 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14523 }
14524 } else {
14525 out.writeInt(0);
14526 }
14527 if (u.mProcStateScreenOffTimeMs != null) {
14528 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14529 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14530 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14531 }
14532 } else {
14533 out.writeInt(0);
14534 }
14535
Adam Lesinski5f056f62016-07-14 16:56:08 -070014536 if (u.mMobileRadioApWakeupCount != null) {
14537 out.writeInt(1);
14538 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14539 } else {
14540 out.writeInt(0);
14541 }
14542
14543 if (u.mWifiRadioApWakeupCount != null) {
14544 out.writeInt(1);
14545 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14546 } else {
14547 out.writeInt(0);
14548 }
14549
Dianne Hackbornd953c532014-08-16 18:17:38 -070014550 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14551 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014552 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014553 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014554 out.writeString(wakeStats.keyAt(iw));
14555 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014556 if (wl.mTimerFull != null) {
14557 out.writeInt(1);
14558 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14559 } else {
14560 out.writeInt(0);
14561 }
14562 if (wl.mTimerPartial != null) {
14563 out.writeInt(1);
14564 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14565 } else {
14566 out.writeInt(0);
14567 }
14568 if (wl.mTimerWindow != null) {
14569 out.writeInt(1);
14570 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14571 } else {
14572 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014573 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014574 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014575 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014576 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014577 } else {
14578 out.writeInt(0);
14579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014580 }
14581
Bookatz2bffb5b2017-04-13 11:59:33 -070014582 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014583 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014584 out.writeInt(NS);
14585 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014586 out.writeString(syncStats.keyAt(is));
14587 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014588 }
14589
Bookatzaa4594a2017-03-24 12:39:56 -070014590 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014591 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014592 out.writeInt(NJ);
14593 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014594 out.writeString(jobStats.keyAt(ij));
14595 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014596 }
14597
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014598 u.writeJobCompletionsToParcelLocked(out);
14599
Amith Yamasani977e11f2018-02-16 11:29:54 -080014600 u.mJobsDeferredEventCount.writeSummaryFromParcelLocked(out);
14601 u.mJobsDeferredCount.writeSummaryFromParcelLocked(out);
14602 u.mJobsFreshnessTimeMs.writeSummaryFromParcelLocked(out);
14603 for (int i = 0; i < JOB_FRESHNESS_BUCKETS.length; i++) {
14604 if (u.mJobsFreshnessBuckets[i] != null) {
Adam Lesinski14082082018-02-23 12:35:55 -080014605 out.writeInt(1);
Amith Yamasani977e11f2018-02-16 11:29:54 -080014606 u.mJobsFreshnessBuckets[i].writeSummaryFromParcelLocked(out);
14607 } else {
14608 out.writeInt(0);
14609 }
14610 }
14611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014612 int NSE = u.mSensorStats.size();
14613 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014614 for (int ise=0; ise<NSE; ise++) {
14615 out.writeInt(u.mSensorStats.keyAt(ise));
14616 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14617 if (se.mTimer != null) {
14618 out.writeInt(1);
14619 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14620 } else {
14621 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014622 }
14623 }
14624
14625 int NP = u.mProcessStats.size();
14626 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014627 for (int ip=0; ip<NP; ip++) {
14628 out.writeString(u.mProcessStats.keyAt(ip));
14629 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14630 out.writeLong(ps.mUserTime);
14631 out.writeLong(ps.mSystemTime);
14632 out.writeLong(ps.mForegroundTime);
14633 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014634 out.writeInt(ps.mNumCrashes);
14635 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014636 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014637 }
14638
14639 NP = u.mPackageStats.size();
14640 out.writeInt(NP);
14641 if (NP > 0) {
14642 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14643 : u.mPackageStats.entrySet()) {
14644 out.writeString(ent.getKey());
14645 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014646 final int NWA = ps.mWakeupAlarms.size();
14647 out.writeInt(NWA);
14648 for (int iwa=0; iwa<NWA; iwa++) {
14649 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14650 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14651 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014652 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014653 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014654 for (int is=0; is<NS; is++) {
14655 out.writeString(ps.mServiceStats.keyAt(is));
14656 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14657 long time = ss.getStartTimeToNowLocked(
14658 mOnBatteryTimeBase.getUptime(NOW_SYS));
14659 out.writeLong(time);
14660 out.writeInt(ss.mStarts);
14661 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014662 }
14663 }
14664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014665 }
14666 }
14667
14668 public void readFromParcel(Parcel in) {
14669 readFromParcelLocked(in);
14670 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014672 void readFromParcelLocked(Parcel in) {
14673 int magic = in.readInt();
14674 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014675 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014676 }
14677
Dianne Hackbornae384452011-06-28 12:33:48 -070014678 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014680 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014681 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014682 mStartPlatformVersion = in.readString();
14683 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014684 mUptime = in.readLong();
14685 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014686 mRealtime = in.readLong();
14687 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014688 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014689 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014690 mMinLearnedBatteryCapacity = in.readInt();
14691 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014692 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014693 mOnBatteryTimeBase.readFromParcel(in);
14694 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14695
Jeff Browne95c3cd2014-05-02 16:59:26 -070014696 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014697 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014698 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014699 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014700 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14701 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014702 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014703 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014704 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014705 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014706 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14707 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014708 mLongestLightIdleTime = in.readLong();
14709 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014710 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14711 mOnBatteryTimeBase, in);
14712 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14713 mOnBatteryTimeBase, in);
14714 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14715 mOnBatteryTimeBase, in);
14716 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14717 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014718 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014719 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014720 null, mOnBatteryTimeBase, in);
14721 }
Joe Onoratoabded112016-02-08 16:49:39 -080014722 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14723 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014724 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014725 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014726 null, mOnBatteryTimeBase, in);
14727 }
14728 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14729 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14730 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14731 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014732 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014733 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14734 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014735 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014736 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014737 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014738 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14739 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014740 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14741 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014742 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014743 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014744 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014745 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014746 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14747 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014748 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014749 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014750 null, mOnBatteryTimeBase, in);
14751 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014752 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014753 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014754 null, mOnBatteryTimeBase, in);
14755 }
14756 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014757 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014758 null, mOnBatteryTimeBase, in);
14759 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014760 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14761 mOnBatteryTimeBase, in);
14762 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14763 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014764 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14765 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14766 null, mOnBatteryTimeBase, in);
14767 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014768 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14769 NUM_BT_TX_LEVELS, in);
14770 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14771 ModemActivityInfo.TX_POWER_LEVELS, in);
14772 mHasWifiReporting = in.readInt() != 0;
14773 mHasBluetoothReporting = in.readInt() != 0;
14774 mHasModemReporting = in.readInt() != 0;
14775
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014776 mNumConnectivityChange = in.readInt();
14777 mLoadedNumConnectivityChange = in.readInt();
14778 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014779 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014780 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014781 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014782 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014783 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014784 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014785 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014786 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014787 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014788 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Siddharth Rayf5e796a2018-01-22 18:18:17 -080014789 mIsCellularTxPowerHigh = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014790 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014791 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014792 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014793 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014794 mLowDischargeAmountSinceCharge = in.readInt();
14795 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014796 mDischargeAmountScreenOn = in.readInt();
14797 mDischargeAmountScreenOnSinceCharge = in.readInt();
14798 mDischargeAmountScreenOff = in.readInt();
14799 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014800 mDischargeAmountScreenDoze = in.readInt();
14801 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014802 mDischargeStepTracker.readFromParcel(in);
14803 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014804 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014805 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14806 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014807 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14808 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014809 mLastWriteTime = in.readLong();
14810
Bookatz50df7112017-08-04 14:53:26 -070014811 mRpmStats.clear();
14812 int NRPMS = in.readInt();
14813 for (int irpm = 0; irpm < NRPMS; irpm++) {
14814 if (in.readInt() != 0) {
14815 String rpmName = in.readString();
14816 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14817 mRpmStats.put(rpmName, rpmt);
14818 }
14819 }
14820 mScreenOffRpmStats.clear();
14821 int NSORPMS = in.readInt();
14822 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14823 if (in.readInt() != 0) {
14824 String rpmName = in.readString();
14825 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14826 mScreenOffRpmStats.put(rpmName, rpmt);
14827 }
14828 }
14829
Evan Millarc64edde2009-04-18 12:26:32 -070014830 mKernelWakelockStats.clear();
14831 int NKW = in.readInt();
14832 for (int ikw = 0; ikw < NKW; ikw++) {
14833 if (in.readInt() != 0) {
14834 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014835 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014836 mKernelWakelockStats.put(wakelockName, kwlt);
14837 }
14838 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014839
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014840 mWakeupReasonStats.clear();
14841 int NWR = in.readInt();
14842 for (int iwr = 0; iwr < NWR; iwr++) {
14843 if (in.readInt() != 0) {
14844 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014845 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014846 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014847 }
14848 }
14849
James Carr3a226052016-07-01 14:49:52 -070014850 mKernelMemoryStats.clear();
14851 int nmt = in.readInt();
14852 for (int imt = 0; imt < nmt; imt++) {
14853 if (in.readInt() != 0) {
14854 Long bucket = in.readLong();
14855 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14856 mKernelMemoryStats.put(bucket, kmt);
14857 }
14858 }
14859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014860 mPartialTimers.clear();
14861 mFullTimers.clear();
14862 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014863 mWifiRunningTimers.clear();
14864 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014865 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014866 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014867 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014868 mAudioTurnedOnTimers.clear();
14869 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014870 mFlashlightTurnedOnTimers.clear();
14871 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014872
14873 int numUids = in.readInt();
14874 mUidStats.clear();
14875 for (int i = 0; i < numUids; i++) {
14876 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014877 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014878 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014879 mUidStats.append(uid, u);
14880 }
14881 }
14882
14883 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014884 writeToParcelLocked(out, true, flags);
14885 }
14886
14887 public void writeToParcelWithoutUids(Parcel out, int flags) {
14888 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014889 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014890
14891 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014892 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014893 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014894 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014895
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014896 // Pull the clock time. This may update the time and make a new history entry
14897 // if we had originally pulled a time before the RTC was set.
14898 long startClockTime = getStartClockTime();
14899
Joe Onoratoabded112016-02-08 16:49:39 -080014900 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14901 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014902 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14903 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014905 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014906
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014907 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014909 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014910 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014911 out.writeString(mStartPlatformVersion);
14912 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014913 out.writeLong(mUptime);
14914 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014915 out.writeLong(mRealtime);
14916 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014917 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014918 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014919 out.writeInt(mMinLearnedBatteryCapacity);
14920 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014921 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14922 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14923
14924 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014925 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014926 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14927 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14928 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014929 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014930 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014931 out.writeLong(mLongestLightIdleTime);
14932 out.writeLong(mLongestFullIdleTime);
14933 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14934 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14935 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014936 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014937 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14938 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14939 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14940 }
14941 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14942 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14943 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14944 }
14945 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14946 mNetworkByteActivityCounters[i].writeToParcel(out);
14947 mNetworkPacketActivityCounters[i].writeToParcel(out);
14948 }
14949 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14950 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014951 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014952 mMobileRadioActiveUnknownTime.writeToParcel(out);
14953 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014954 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014955 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14956 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14957 for (int i=0; i<NUM_WIFI_STATES; i++) {
14958 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14959 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014960 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14961 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14962 }
14963 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14964 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14965 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014966 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
14967 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014968 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14969 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
14970 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014971 mBluetoothActivity.writeToParcel(out, 0);
14972 mModemActivity.writeToParcel(out, 0);
14973 out.writeInt(mHasWifiReporting ? 1 : 0);
14974 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14975 out.writeInt(mHasModemReporting ? 1 : 0);
14976
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014977 out.writeInt(mNumConnectivityChange);
14978 out.writeInt(mLoadedNumConnectivityChange);
14979 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014980 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014981 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014982 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014983 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014984 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014985 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014986 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014987 out.writeInt(mLowDischargeAmountSinceCharge);
14988 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014989 out.writeInt(mDischargeAmountScreenOn);
14990 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14991 out.writeInt(mDischargeAmountScreenOff);
14992 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014993 out.writeInt(mDischargeAmountScreenDoze);
14994 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014995 mDischargeStepTracker.writeToParcel(out);
14996 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014997 mDischargeCounter.writeToParcel(out);
14998 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014999 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080015000 mDischargeLightDozeCounter.writeToParcel(out);
15001 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015002 out.writeLong(mLastWriteTime);
15003
Bookatz50df7112017-08-04 14:53:26 -070015004 out.writeInt(mRpmStats.size());
15005 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
15006 SamplingTimer rpmt = ent.getValue();
15007 if (rpmt != null) {
15008 out.writeInt(1);
15009 out.writeString(ent.getKey());
15010 rpmt.writeToParcel(out, uSecRealtime);
15011 } else {
15012 out.writeInt(0);
15013 }
15014 }
15015 out.writeInt(mScreenOffRpmStats.size());
15016 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
15017 SamplingTimer rpmt = ent.getValue();
15018 if (rpmt != null) {
15019 out.writeInt(1);
15020 out.writeString(ent.getKey());
15021 rpmt.writeToParcel(out, uSecRealtime);
15022 } else {
15023 out.writeInt(0);
15024 }
15025 }
15026
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015027 if (inclUids) {
15028 out.writeInt(mKernelWakelockStats.size());
15029 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
15030 SamplingTimer kwlt = ent.getValue();
15031 if (kwlt != null) {
15032 out.writeInt(1);
15033 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015034 kwlt.writeToParcel(out, uSecRealtime);
15035 } else {
15036 out.writeInt(0);
15037 }
15038 }
15039 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015040 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
15041 SamplingTimer timer = ent.getValue();
15042 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015043 out.writeInt(1);
15044 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070015045 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015046 } else {
15047 out.writeInt(0);
15048 }
Evan Millarc64edde2009-04-18 12:26:32 -070015049 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015050 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070015051 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015052 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070015053 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070015054
James Carr3a226052016-07-01 14:49:52 -070015055 out.writeInt(mKernelMemoryStats.size());
15056 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
15057 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
15058 if (kmt != null) {
15059 out.writeInt(1);
15060 out.writeLong(mKernelMemoryStats.keyAt(i));
15061 kmt.writeToParcel(out, uSecRealtime);
15062 } else {
15063 out.writeInt(0);
15064 }
15065 }
15066
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015067 if (inclUids) {
15068 int size = mUidStats.size();
15069 out.writeInt(size);
15070 for (int i = 0; i < size; i++) {
15071 out.writeInt(mUidStats.keyAt(i));
15072 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015073
Bookatz867c0d72017-03-07 18:23:42 -080015074 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070015075 }
15076 } else {
15077 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015078 }
15079 }
15080
15081 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
15082 new Parcelable.Creator<BatteryStatsImpl>() {
15083 public BatteryStatsImpl createFromParcel(Parcel in) {
15084 return new BatteryStatsImpl(in);
15085 }
15086
15087 public BatteryStatsImpl[] newArray(int size) {
15088 return new BatteryStatsImpl[size];
15089 }
15090 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070015091
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015092 public void prepareForDumpLocked() {
15093 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080015094 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070015095
15096 // Pull the clock time. This may update the time and make a new history entry
15097 // if we had originally pulled a time before the RTC was set.
15098 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070015099 }
15100
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015101 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015102 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080015103 pw.println("mOnBatteryTimeBase:");
15104 mOnBatteryTimeBase.dump(pw, " ");
15105 pw.println("mOnBatteryScreenOffTimeBase:");
15106 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015107 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070015108 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015109 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070015110 pr.println("*** Screen doze timer:");
15111 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015112 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015113 pr.println("*** Screen brightness #" + i + ":");
15114 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070015115 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070015116 pr.println("*** Interactive timer:");
15117 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070015118 pr.println("*** Power save mode timer:");
15119 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070015120 pr.println("*** Device idle mode light timer:");
15121 mDeviceIdleModeLightTimer.logState(pr, " ");
15122 pr.println("*** Device idle mode full timer:");
15123 mDeviceIdleModeFullTimer.logState(pr, " ");
15124 pr.println("*** Device light idling timer:");
15125 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070015126 pr.println("*** Device idling timer:");
15127 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015128 pr.println("*** Phone timer:");
15129 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080015130 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070015131 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015132 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015133 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070015134 pr.println("*** Signal scanning :");
15135 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015136 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015137 pr.println("*** Data connection type #" + i + ":");
15138 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070015139 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070015140 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080015141 pr.println("*** Mobile network active timer:");
15142 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070015143 pr.println("*** Mobile network active adjusted timer:");
15144 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080015145 pr.println("*** Wifi Multicast WakeLock Timer:");
15146 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070015147 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070015148 pr.println("*** Wifi timer:");
15149 mWifiOnTimer.logState(pr, " ");
15150 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070015151 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080015152 for (int i=0; i<NUM_WIFI_STATES; i++) {
15153 pr.println("*** Wifi state #" + i + ":");
15154 mWifiStateTimer[i].logState(pr, " ");
15155 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070015156 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
15157 pr.println("*** Wifi suppl state #" + i + ":");
15158 mWifiSupplStateTimer[i].logState(pr, " ");
15159 }
15160 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
15161 pr.println("*** Wifi signal strength #" + i + ":");
15162 mWifiSignalStrengthsTimer[i].logState(pr, " ");
15163 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080015164 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
15165 pr.println("*** GPS signal quality #" + i + ":");
15166 mGpsSignalQualityTimer[i].logState(pr, " ");
15167 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070015168 pr.println("*** Flashlight timer:");
15169 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070015170 pr.println("*** Camera timer:");
15171 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015172 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080015173 super.dumpLocked(context, pw, flags, reqUid, histStart);
Sudheer Shankac20379e2018-02-15 00:06:21 -080015174 pw.print("Total cpu time reads: ");
15175 pw.println(mNumCpuTimeReads);
15176 pw.print("Batched cpu time reads: ");
15177 pw.println(mNumBatchedCpuTimeReads);
15178 pw.print("Batching Duration (min): ");
15179 pw.println((mClocks.uptimeMillis() - mCpuTimeReadsTrackingStartTime) / (60 * 1000));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015181}