blob: 039b66d4cd7d9e37d26d486c41f81d9c4ce36262 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Parcel;
45import android.os.ParcelFormatException;
46import android.os.Parcelable;
Evan Millarc64edde2009-04-18 12:26:32 -070047import android.os.Process;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080048import android.os.RemoteException;
49import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.SystemClock;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070051import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070052import android.os.WorkSource;
Narayan Kamath81822022017-12-08 11:56:01 +000053import android.os.WorkSource.WorkChain;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080054import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070055import android.telephony.DataConnectionRealTimeInfo;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080056import android.telephony.ModemActivityInfo;
Amith Yamasanif37447b2009-10-08 18:28:01 -070057import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070058import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070059import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070060import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070061import android.util.ArrayMap;
Sudheer Shankab2f83c12017-11-13 19:25:01 -080062import android.util.IntArray;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080063import android.util.KeyValueListParser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070065import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070066import android.util.LongSparseArray;
67import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070068import android.util.MutableInt;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070069import android.util.Pools;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070070import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070072import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080074import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070075import android.util.SparseLongArray;
Bookatzc1a050a2017-10-10 15:49:28 -070076import android.util.StatsLog;
Dianne Hackbornae384452011-06-28 12:33:48 -070077import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080078import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070079import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080
Adam Lesinski14ae39a2017-05-26 11:50:40 -070081import com.android.internal.annotations.GuardedBy;
Adam Lesinski98f0d462016-04-19 16:46:20 -070082import com.android.internal.annotations.VisibleForTesting;
Siddharth Ray78ccaf52017-12-23 16:16:21 -080083import com.android.internal.location.gnssmetrics.GnssMetrics;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070084import com.android.internal.net.NetworkStatsFactory;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080085import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070086import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080087import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070088import com.android.internal.util.JournaledFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080089import com.android.internal.util.XmlUtils;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070090
Narayan Kamath81822022017-12-08 11:56:01 +000091import java.util.List;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070092import libcore.util.EmptyArray;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080093import org.xmlpull.v1.XmlPullParser;
94import org.xmlpull.v1.XmlPullParserException;
95import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070096
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080097import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import java.io.File;
99import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800100import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import java.io.FileOutputStream;
102import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700103import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100104import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.ArrayList;
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700106import java.util.Arrays;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800107import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.HashMap;
Evan Millarc64edde2009-04-18 12:26:32 -0700109import java.util.Iterator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Map;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700111import java.util.concurrent.Future;
Christopher Tate4cee7252010-03-19 14:50:40 -0700112import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700113import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
115/**
116 * All information we are collecting about things that can happen that impact
117 * battery life. All times are represented in microseconds except where indicated
118 * otherwise.
119 */
Joe Onoratoabded112016-02-08 16:49:39 -0800120public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800122 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700123 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800124 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700125 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700126 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700127 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700128
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700129 // TODO: remove "tcp" from network methods, since we measure total stats.
130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700132 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133
134 // Current on-disk Parcel version
Siddharth Rayb50a6842017-12-14 15:15:28 -0800135 private static final int VERSION = 174 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700136
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700137 // Maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100138 private static final int MAX_HISTORY_ITEMS;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700139
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700140 // No, really, THIS is the maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100141 private static final int MAX_MAX_HISTORY_ITEMS;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700142
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800143 // The maximum number of names wakelocks we will keep track of
144 // per uid; once the limit is reached, we batch the remaining wakelocks
145 // in to one common name.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100146 private static final int MAX_WAKELOCKS_PER_UID;
147
148 static final int MAX_HISTORY_BUFFER; // 256KB
149 static final int MAX_MAX_HISTORY_BUFFER; // 320KB
150
151 static {
152 if (ActivityManager.isLowRamDeviceStatic()) {
153 MAX_HISTORY_ITEMS = 800;
154 MAX_MAX_HISTORY_ITEMS = 1200;
155 MAX_WAKELOCKS_PER_UID = 40;
156 MAX_HISTORY_BUFFER = 96*1024; // 96KB
157 MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
158 } else {
Makoto Onuki44d64602018-01-18 08:44:28 -0800159 MAX_HISTORY_ITEMS = 4000;
160 MAX_MAX_HISTORY_ITEMS = 6000;
161 MAX_WAKELOCKS_PER_UID = 200;
162 MAX_HISTORY_BUFFER = 512*1024; // 512KB
163 MAX_MAX_HISTORY_BUFFER = 640*1024; // 640KB
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100164 }
165 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700166
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800167 // Number of transmit power states the Wifi controller can be in.
168 private static final int NUM_WIFI_TX_LEVELS = 1;
169
170 // Number of transmit power states the Bluetooth controller can be in.
171 private static final int NUM_BT_TX_LEVELS = 1;
172
Sudheer Shanka38383232017-07-25 09:55:03 -0700173 /**
174 * Holding a wakelock costs more than just using the cpu.
175 * Currently, we assign only half the cpu time to an app that is running but
176 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
177 * If no app is holding a wakelock, then the distribution is normal.
178 */
179 @VisibleForTesting
180 public static final int WAKE_LOCK_WEIGHT = 50;
181
Joe Onoratoabded112016-02-08 16:49:39 -0800182 protected Clocks mClocks;
183
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700184 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700185 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800186 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700188 static final int MSG_UPDATE_WAKELOCKS = 1;
189 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700190 static final int MSG_REPORT_CHARGING = 3;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700191 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700192
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700193 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
194 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
195
Sudheer Shanka38383232017-07-25 09:55:03 -0700196 @VisibleForTesting
197 protected KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
198 @VisibleForTesting
199 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
200 @VisibleForTesting
201 protected KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700202 new KernelUidCpuFreqTimeReader();
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800203 @VisibleForTesting
Mike Ma3d422c32017-10-25 11:08:57 -0700204 protected KernelUidCpuActiveTimeReader mKernelUidCpuActiveTimeReader =
205 new KernelUidCpuActiveTimeReader();
206 @VisibleForTesting
207 protected KernelUidCpuClusterTimeReader mKernelUidCpuClusterTimeReader =
208 new KernelUidCpuClusterTimeReader();
209 @VisibleForTesting
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800210 protected KernelSingleUidTimeReader mKernelSingleUidTimeReader;
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700211
James Carr3a226052016-07-01 14:49:52 -0700212 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
213 = new KernelMemoryBandwidthStats();
214 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
215 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
216 return mKernelMemoryStats;
217 }
218
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800219 @GuardedBy("this")
220 public boolean mPerProcStateCpuTimesAvailable = true;
221
222 /**
223 * Uids for which per-procstate cpu times need to be updated.
224 *
225 * Contains uid -> procState mappings.
226 */
227 @GuardedBy("this")
228 @VisibleForTesting
229 protected final SparseIntArray mPendingUids = new SparseIntArray();
230
Bookatz0b8a0502017-09-13 11:51:52 -0700231 /** Container for Resource Power Manager stats. Updated by updateRpmStatsLocked. */
Bookatz50df7112017-08-04 14:53:26 -0700232 private final RpmStats mTmpRpmStats = new RpmStats();
Bookatz0b8a0502017-09-13 11:51:52 -0700233 /** The soonest the RPM stats can be updated after it was last updated. */
234 private static final long RPM_STATS_UPDATE_FREQ_MS = 1000;
235 /** Last time that RPM stats were updated by updateRpmStatsLocked. */
236 private long mLastRpmStatsUpdateTimeMs = -RPM_STATS_UPDATE_FREQ_MS;
Bookatz50df7112017-08-04 14:53:26 -0700237
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700238 public interface BatteryCallback {
239 public void batteryNeedsCpuUpdate();
240 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700241 public void batterySendBroadcast(Intent intent);
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700242 }
243
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700244 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700245 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700246 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000247 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700248 }
249
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700250 public static abstract class UserInfoProvider {
251 private int[] userIds;
252 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700253 @VisibleForTesting
254 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700255 userIds = getUserIds();
256 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700257 @VisibleForTesting
258 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700259 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
260 }
261 }
262
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700263 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
264
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700265 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800266 public MyHandler(Looper looper) {
267 super(looper, null, true);
268 }
269
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700270 @Override
271 public void handleMessage(Message msg) {
272 BatteryCallback cb = mCallback;
273 switch (msg.what) {
274 case MSG_UPDATE_WAKELOCKS:
Adam Lesinski72478f02015-06-17 15:39:43 -0700275 synchronized (BatteryStatsImpl.this) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -0700276 updateCpuTimeLocked();
Adam Lesinski72478f02015-06-17 15:39:43 -0700277 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700278 if (cb != null) {
279 cb.batteryNeedsCpuUpdate();
280 }
281 break;
282 case MSG_REPORT_POWER_CHANGE:
283 if (cb != null) {
284 cb.batteryPowerChanged(msg.arg1 != 0);
285 }
286 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700287 case MSG_REPORT_CHARGING:
288 if (cb != null) {
289 final String action;
290 synchronized (BatteryStatsImpl.this) {
291 action = mCharging ? BatteryManager.ACTION_CHARGING
292 : BatteryManager.ACTION_DISCHARGING;
293 }
294 Intent intent = new Intent(action);
295 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
296 cb.batterySendBroadcast(intent);
297 }
298 break;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700299 }
300 }
301 }
302
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800303 /**
304 * Update per-freq cpu times for all the uids in {@link #mPendingUids}.
305 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800306 public void updateProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800307 final SparseIntArray uidStates;
308 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800309 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
310 return;
311 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800312 if(!initKernelSingleUidTimeReaderLocked()) {
313 return;
314 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800315 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
316 // compute deltas since it might result in mis-attributing cpu times to wrong states.
317 if (mKernelSingleUidTimeReader.hasStaleData()) {
318 mPendingUids.clear();
319 return;
320 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800321
322 if (mPendingUids.size() == 0) {
323 return;
324 }
325 uidStates = mPendingUids.clone();
326 mPendingUids.clear();
327 }
328 for (int i = uidStates.size() - 1; i >= 0; --i) {
329 final int uid = uidStates.keyAt(i);
330 final int procState = uidStates.valueAt(i);
331 final int[] isolatedUids;
332 final Uid u;
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800333 synchronized (BatteryStatsImpl.this) {
334 // It's possible that uid no longer exists and any internal references have
335 // already been deleted, so using {@link #getAvailableUidStatsLocked} to avoid
336 // creating an UidStats object if it doesn't already exist.
337 u = getAvailableUidStatsLocked(uid);
338 if (u == null) {
339 continue;
340 }
341 if (u.mChildUids == null) {
342 isolatedUids = null;
343 } else {
344 isolatedUids = u.mChildUids.toArray();
345 for (int j = isolatedUids.length - 1; j >= 0; --j) {
346 isolatedUids[j] = u.mChildUids.get(j);
347 }
348 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800349 }
350 long[] cpuTimesMs = mKernelSingleUidTimeReader.readDeltaMs(uid);
351 if (isolatedUids != null) {
352 for (int j = isolatedUids.length - 1; j >= 0; --j) {
353 cpuTimesMs = addCpuTimes(cpuTimesMs,
354 mKernelSingleUidTimeReader.readDeltaMs(isolatedUids[j]));
355 }
356 }
357 if (onBattery && cpuTimesMs != null) {
358 synchronized (BatteryStatsImpl.this) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800359 u.addProcStateTimesMs(procState, cpuTimesMs, onBattery);
360 u.addProcStateScreenOffTimesMs(procState, cpuTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800361 }
362 }
363 }
364 }
365
Sudheer Shankae544d162017-12-28 17:06:20 -0800366 public void copyFromAllUidsCpuTimes() {
367 synchronized (BatteryStatsImpl.this) {
368 copyFromAllUidsCpuTimes(
369 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
370 }
371 }
372
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800373 /**
374 * When the battery/screen state changes, we don't attribute the cpu times to any process
375 * but we still need to snapshots of all uids to get correct deltas later on. Since we
376 * already read this data for updating per-freq cpu times, we can use the same data for
377 * per-procstate cpu times.
378 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800379 public void copyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800380 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800381 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
382 return;
383 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800384 if(!initKernelSingleUidTimeReaderLocked()) {
385 return;
386 }
387
388 final SparseArray<long[]> allUidCpuFreqTimesMs =
389 mKernelUidCpuFreqTimeReader.getAllUidCpuFreqTimeMs();
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800390 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
391 // compute deltas since it might result in mis-attributing cpu times to wrong states.
392 if (mKernelSingleUidTimeReader.hasStaleData()) {
393 mKernelSingleUidTimeReader.setAllUidsCpuTimesMs(allUidCpuFreqTimesMs);
394 mKernelSingleUidTimeReader.markDataAsStale(false);
395 mPendingUids.clear();
396 return;
397 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800398 for (int i = allUidCpuFreqTimesMs.size() - 1; i >= 0; --i) {
399 final int uid = allUidCpuFreqTimesMs.keyAt(i);
400 final Uid u = getAvailableUidStatsLocked(mapUid(uid));
401 if (u == null) {
402 continue;
403 }
404 final long[] cpuTimesMs = allUidCpuFreqTimesMs.valueAt(i);
405 if (cpuTimesMs == null) {
406 continue;
407 }
408 final long[] deltaTimesMs = mKernelSingleUidTimeReader.computeDelta(
409 uid, cpuTimesMs.clone());
Sudheer Shankae544d162017-12-28 17:06:20 -0800410 if (onBattery && deltaTimesMs != null) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800411 final int procState;
412 final int idx = mPendingUids.indexOfKey(uid);
413 if (idx >= 0) {
414 procState = mPendingUids.valueAt(idx);
415 mPendingUids.removeAt(idx);
416 } else {
417 procState = u.mProcessState;
418 }
419 if (procState >= 0 && procState < Uid.NUM_PROCESS_STATE) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800420 u.addProcStateTimesMs(procState, deltaTimesMs, onBattery);
421 u.addProcStateScreenOffTimesMs(procState, deltaTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800422 }
423 }
424 }
425 }
426 }
427
428 @VisibleForTesting
429 public long[] addCpuTimes(long[] timesA, long[] timesB) {
430 if (timesA != null && timesB != null) {
431 for (int i = timesA.length - 1; i >= 0; --i) {
432 timesA[i] += timesB[i];
433 }
434 return timesA;
435 }
436 return timesA == null ? (timesB == null ? null : timesB) : timesA;
437 }
438
439 @GuardedBy("this")
440 private boolean initKernelSingleUidTimeReaderLocked() {
441 if (mKernelSingleUidTimeReader == null) {
442 if (mPowerProfile == null) {
443 return false;
444 }
445 if (mCpuFreqs == null) {
446 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
447 }
448 if (mCpuFreqs != null) {
449 mKernelSingleUidTimeReader = new KernelSingleUidTimeReader(mCpuFreqs.length);
450 } else {
451 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable();
452 return false;
453 }
454 }
455 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable()
456 && mKernelSingleUidTimeReader.singleUidCpuTimesAvailable();
457 return true;
458 }
459
Joe Onoratoabded112016-02-08 16:49:39 -0800460 public interface Clocks {
461 public long elapsedRealtime();
462 public long uptimeMillis();
463 }
464
465 public static class SystemClocks implements Clocks {
466 public long elapsedRealtime() {
467 return SystemClock.elapsedRealtime();
468 }
469
470 public long uptimeMillis() {
471 return SystemClock.uptimeMillis();
472 }
473 }
474
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700475 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700476 int UPDATE_CPU = 0x01;
477 int UPDATE_WIFI = 0x02;
478 int UPDATE_RADIO = 0x04;
479 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700480 int UPDATE_RPM = 0x10; // 16
481 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800482
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700483 Future<?> scheduleSync(String reason, int flags);
484 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Sudheer Shankae544d162017-12-28 17:06:20 -0800485 Future<?> scheduleReadProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
486 Future<?> scheduleCopyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800487 Future<?> scheduleCpuSyncDueToSettingChange();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700488 }
489
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800490 public Handler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700491 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700492 @VisibleForTesting
493 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700494
495 private BatteryCallback mCallback;
496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800498 * Mapping isolated uids to the actual owning app uid.
499 */
500 final SparseIntArray mIsolatedUids = new SparseIntArray();
501
502 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 * The statistics we have collected organized by uids.
504 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800505 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506
507 // A set of pools of currently active timers. When a timer is queried, we will divide the
508 // elapsed time by the number of active timers to arrive at that timer's share of the time.
509 // In order to do this, we must refresh each timer whenever the number of active timers
510 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700511 @VisibleForTesting
512 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700513 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
514 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700515 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700516 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
517 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
518 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
519 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
520 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
521 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
522 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
523 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700524 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
525 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800526 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700528 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700529 @VisibleForTesting
530 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 // These are the objects that will want to do something when the device
533 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800534 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800535
536 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700537 // is unplugged from power *and* the screen is off or doze.
538 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800539
540 // Set to true when we want to distribute CPU across wakelocks for the next
541 // CPU update, even if we aren't currently running wake locks.
542 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700543
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700544 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700545
Dianne Hackborn37de0982014-05-09 09:32:18 -0700546 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800547
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700548 long mHistoryBaseTime;
Narayan Kamath695cf722017-12-21 18:32:47 +0000549 protected boolean mHaveBatteryLevel = false;
550 protected boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700551 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700552
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700553 final Parcel mHistoryBuffer = Parcel.obtain();
554 final HistoryItem mHistoryLastWritten = new HistoryItem();
555 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700556 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700557 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700558 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800559 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800560 int[] mReadHistoryUids;
561 int mReadHistoryChars;
562 int mNextHistoryTagIdx = 0;
563 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700564 int mHistoryBufferLastPos = -1;
565 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700566 int mActiveHistoryStates = 0xffffffff;
567 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700568 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700569 long mTrackRunningHistoryElapsedRealtime = 0;
570 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700571
572 final HistoryItem mHistoryCur = new HistoryItem();
573
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700574 HistoryItem mHistory;
575 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700576 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700577 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700578
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800579 // Used by computeHistoryStepDetails
580 HistoryStepDetails mLastHistoryStepDetails = null;
581 byte mLastHistoryStepLevel = 0;
582 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
583 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
584 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700585
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800586 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700587 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800588 */
589 long mLastStepCpuUserTime;
590 long mCurStepCpuUserTime;
591 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700592 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800593 */
594 long mLastStepCpuSystemTime;
595 long mCurStepCpuSystemTime;
596 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700597 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800598 */
599 long mLastStepStatUserTime;
600 long mLastStepStatSystemTime;
601 long mLastStepStatIOWaitTime;
602 long mLastStepStatIrqTime;
603 long mLastStepStatSoftIrqTime;
604 long mLastStepStatIdleTime;
605 long mCurStepStatUserTime;
606 long mCurStepStatSystemTime;
607 long mCurStepStatIOWaitTime;
608 long mCurStepStatIrqTime;
609 long mCurStepStatSoftIrqTime;
610 long mCurStepStatIdleTime;
611
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700612 private HistoryItem mHistoryIterator;
613 private boolean mReadOverflow;
614 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 int mStartCount;
617
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800618 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700619 String mStartPlatformVersion;
620 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 long mUptime;
623 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 long mRealtime;
625 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700626
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800627 int mWakeLockNesting;
628 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700629 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700630 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800631
Mike Mac2f518a2017-09-19 16:06:03 -0700632 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
633 protected int mScreenState = Display.STATE_UNKNOWN;
634 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
635 protected StopwatchTimer mScreenOnTimer;
636 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
637 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700638
Dianne Hackborn617f8772009-03-31 15:04:46 -0700639 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700640 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700641
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800642 boolean mPretendScreenOff;
643
Jeff Browne95c3cd2014-05-02 16:59:26 -0700644 boolean mInteractive;
645 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700646
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700647 boolean mPowerSaveModeEnabled;
648 StopwatchTimer mPowerSaveModeEnabledTimer;
649
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700650 boolean mDeviceIdling;
651 StopwatchTimer mDeviceIdlingTimer;
652
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700653 boolean mDeviceLightIdling;
654 StopwatchTimer mDeviceLightIdlingTimer;
655
656 int mDeviceIdleMode;
657 long mLastIdleTimeStart;
658 long mLongestLightIdleTime;
659 long mLongestFullIdleTime;
660 StopwatchTimer mDeviceIdleModeLightTimer;
661 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700664 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700665
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700666 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700667 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700668
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700669 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700670 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700671
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700672 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700673 StopwatchTimer mFlashlightOnTimer;
674
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700675 int mCameraOnNesting;
676 StopwatchTimer mCameraOnTimer;
677
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800678 int mGpsSignalQualityBin = -1;
679 final StopwatchTimer[] mGpsSignalQualityTimer =
680 new StopwatchTimer[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
681
Dianne Hackborn627bba72009-03-24 22:32:56 -0700682 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800683 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700684 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800685 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700686
687 StopwatchTimer mPhoneSignalScanningTimer;
688
Dianne Hackborn627bba72009-03-24 22:32:56 -0700689 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700690 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700691 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700692
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800693 final LongSamplingCounter[] mNetworkByteActivityCounters =
694 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
695 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700696 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
697
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800698 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800699 * The WiFi Overall wakelock timer
700 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
701 * since addition of per UID timers would not result in an accurate value due to overlapp of
702 * per uid wakelock timers
703 */
704 StopwatchTimer mWifiMulticastWakelockTimer;
705
706 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800707 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
708 */
709 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700710
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800711 /**
712 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
713 */
714 ControllerActivityCounterImpl mBluetoothActivity;
715
716 /**
717 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
718 */
719 ControllerActivityCounterImpl mModemActivity;
720
721 /**
722 * Whether the device supports WiFi controller energy reporting. This is set to true on
723 * the first WiFi energy report. See {@link #mWifiActivity}.
724 */
725 boolean mHasWifiReporting = false;
726
727 /**
728 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
729 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
730 */
731 boolean mHasBluetoothReporting = false;
732
733 /**
734 * Whether the device supports Modem controller energy reporting. This is set to true on
735 * the first Modem energy report. See {@link #mModemActivity}.
736 */
737 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700738
The Android Open Source Project10592532009-03-18 17:39:46 -0700739 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700740 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700741
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700742 boolean mGlobalWifiRunning;
743 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700744
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800745 int mWifiState = -1;
746 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
747
Dianne Hackborn3251b902014-06-20 14:40:53 -0700748 int mWifiSupplState = -1;
749 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
750
751 int mWifiSignalStrengthBin = -1;
752 final StopwatchTimer[] mWifiSignalStrengthsTimer =
753 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
754
Siddharth Rayb50a6842017-12-14 15:15:28 -0800755 StopwatchTimer mWifiActiveTimer;
756
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800757 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800758 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
759 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800760
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700761 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700762 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800763 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800764 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700765 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800766 LongSamplingCounter mMobileRadioActiveUnknownTime;
767 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800768
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700769 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 /**
772 * These provide time bases that discount the time the device is plugged
773 * in to power.
774 */
775 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700776 @VisibleForTesting
777 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700778
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700779 /**
780 * External reporting of whether the device is actually charging.
781 */
782 boolean mCharging = true;
783 int mLastChargingStateLevel;
784
The Android Open Source Project10592532009-03-18 17:39:46 -0700785 /*
786 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
787 */
Evan Millar633a1742009-04-02 16:36:33 -0700788 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700789 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700790 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700791 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700792 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700793 int mLowDischargeAmountSinceCharge;
794 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800795 int mDischargeScreenOnUnplugLevel;
796 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700797 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800798 int mDischargeAmountScreenOn;
799 int mDischargeAmountScreenOnSinceCharge;
800 int mDischargeAmountScreenOff;
801 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700802 int mDischargeAmountScreenDoze;
803 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700804
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700805 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700806 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700807 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800808 private LongSamplingCounter mDischargeLightDozeCounter;
809 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700810
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700811 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700812
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700813 int mInitStepMode = 0;
814 int mCurStepMode = 0;
815 int mModStepMode = 0;
816
Dianne Hackborn260c5022014-04-29 11:23:16 -0700817 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700818 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800819 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
820 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700821 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700822
823 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700824 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800825 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
826 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
827
828 static final int MAX_DAILY_ITEMS = 10;
829
830 long mDailyStartTime = 0;
831 long mNextMinDailyDeadline = 0;
832 long mNextMaxDailyDeadline = 0;
833
834 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700837
Amith Yamasanif37447b2009-10-08 18:28:01 -0700838 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800839 private int mPhoneServiceStateRaw = -1;
840 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700841
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800842 private int mNumConnectivityChange;
843 private int mLoadedNumConnectivityChange;
844 private int mUnpluggedNumConnectivityChange;
845
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700846 private int mEstimatedBatteryCapacity = -1;
847
Jocelyn Dangc627d102017-04-14 13:15:14 -0700848 private int mMinLearnedBatteryCapacity = -1;
849 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800850
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700851 private long[] mCpuFreqs;
852
Sudheer Shanka38383232017-07-25 09:55:03 -0700853 @VisibleForTesting
854 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700855
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800856 @GuardedBy("this")
857 private final Constants mConstants;
858
Evan Millarc64edde2009-04-18 12:26:32 -0700859 /*
Bookatz50df7112017-08-04 14:53:26 -0700860 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
861 * recording their times when on-battery (regardless of screen state).
862 */
863 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
864 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
865 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
866
867 @Override
868 public Map<String, ? extends Timer> getRpmStats() {
869 return mRpmStats;
870 }
871
Bookatz82b341172017-09-07 19:06:08 -0700872 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700873 @Override
874 public Map<String, ? extends Timer> getScreenOffRpmStats() {
875 return mScreenOffRpmStats;
876 }
877
878 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700879 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
880 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700881 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700882
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700883 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700884 return mKernelWakelockStats;
885 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700886
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700887 String mLastWakeupReason = null;
888 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700889 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700890
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700891 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700892 return mWakeupReasonStats;
893 }
894
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700895 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700896 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700897 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700898 }
899
900 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700901 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700902 return mDischargeScreenOffCounter.getCountLocked(which);
903 }
904
905 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700906 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700907 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700908 }
909
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700910 @Override
Mike Ma15313c92017-11-15 17:58:21 -0800911 public long getUahDischargeLightDoze(int which) {
912 return mDischargeLightDozeCounter.getCountLocked(which);
913 }
914
915 @Override
916 public long getUahDischargeDeepDoze(int which) {
917 return mDischargeDeepDozeCounter.getCountLocked(which);
918 }
919
920 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700921 public int getEstimatedBatteryCapacity() {
922 return mEstimatedBatteryCapacity;
923 }
924
Jocelyn Dangc627d102017-04-14 13:15:14 -0700925 @Override
926 public int getMinLearnedBatteryCapacity() {
927 return mMinLearnedBatteryCapacity;
928 }
929
930 @Override
931 public int getMaxLearnedBatteryCapacity() {
932 return mMaxLearnedBatteryCapacity;
933 }
934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -0800936 this(new SystemClocks());
937 }
938
939 public BatteryStatsImpl(Clocks clocks) {
940 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700941 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700942 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800943 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700944 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700945 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700946 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800947 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700948 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 }
950
Joe Onoratoabded112016-02-08 16:49:39 -0800951 private void init(Clocks clocks) {
952 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -0800953 }
954
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700955 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800956 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
957 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
958 }
959
Joe Onoratoabded112016-02-08 16:49:39 -0800960 // methods are protected not private to be VisibleForTesting
961 public static class TimeBase {
962 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800963
Joe Onoratoabded112016-02-08 16:49:39 -0800964 protected long mUptime;
965 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800966
Joe Onoratoabded112016-02-08 16:49:39 -0800967 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800968
Joe Onoratoabded112016-02-08 16:49:39 -0800969 protected long mPastUptime;
970 protected long mUptimeStart;
971 protected long mPastRealtime;
972 protected long mRealtimeStart;
973 protected long mUnpluggedUptime;
974 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800975
976 public void dump(PrintWriter pw, String prefix) {
977 StringBuilder sb = new StringBuilder(128);
978 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
979 sb.setLength(0);
980 sb.append(prefix);
981 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700982 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800983 pw.println(sb.toString());
984 sb.setLength(0);
985 sb.append(prefix);
986 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700987 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800988 pw.println(sb.toString());
989 sb.setLength(0);
990 sb.append(prefix);
991 sb.append("mPastUptime=");
992 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
993 formatTimeMs(sb, mUptimeStart / 1000);
994 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
995 pw.println(sb.toString());
996 sb.setLength(0);
997 sb.append(prefix);
998 sb.append("mPastRealtime=");
999 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
1000 formatTimeMs(sb, mRealtimeStart / 1000);
1001 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
1002 pw.println(sb.toString());
1003 }
1004
1005 public void add(TimeBaseObs observer) {
1006 mObservers.add(observer);
1007 }
1008
1009 public void remove(TimeBaseObs observer) {
1010 if (!mObservers.remove(observer)) {
1011 Slog.wtf(TAG, "Removed unknown observer: " + observer);
1012 }
1013 }
1014
Joe Onoratoabded112016-02-08 16:49:39 -08001015 public boolean hasObserver(TimeBaseObs observer) {
1016 return mObservers.contains(observer);
1017 }
1018
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001019 public void init(long uptime, long realtime) {
1020 mRealtime = 0;
1021 mUptime = 0;
1022 mPastUptime = 0;
1023 mPastRealtime = 0;
1024 mUptimeStart = uptime;
1025 mRealtimeStart = realtime;
1026 mUnpluggedUptime = getUptime(mUptimeStart);
1027 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1028 }
1029
1030 public void reset(long uptime, long realtime) {
1031 if (!mRunning) {
1032 mPastUptime = 0;
1033 mPastRealtime = 0;
1034 } else {
1035 mUptimeStart = uptime;
1036 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001037 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1038 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001039 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001040 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001041 mUnpluggedRealtime = getRealtime(realtime);
1042 }
1043 }
1044
1045 public long computeUptime(long curTime, int which) {
1046 switch (which) {
1047 case STATS_SINCE_CHARGED:
1048 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001049 case STATS_CURRENT:
1050 return getUptime(curTime);
1051 case STATS_SINCE_UNPLUGGED:
1052 return getUptime(curTime) - mUnpluggedUptime;
1053 }
1054 return 0;
1055 }
1056
1057 public long computeRealtime(long curTime, int which) {
1058 switch (which) {
1059 case STATS_SINCE_CHARGED:
1060 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001061 case STATS_CURRENT:
1062 return getRealtime(curTime);
1063 case STATS_SINCE_UNPLUGGED:
1064 return getRealtime(curTime) - mUnpluggedRealtime;
1065 }
1066 return 0;
1067 }
1068
1069 public long getUptime(long curTime) {
1070 long time = mPastUptime;
1071 if (mRunning) {
1072 time += curTime - mUptimeStart;
1073 }
1074 return time;
1075 }
1076
1077 public long getRealtime(long curTime) {
1078 long time = mPastRealtime;
1079 if (mRunning) {
1080 time += curTime - mRealtimeStart;
1081 }
1082 return time;
1083 }
1084
1085 public long getUptimeStart() {
1086 return mUptimeStart;
1087 }
1088
1089 public long getRealtimeStart() {
1090 return mRealtimeStart;
1091 }
1092
1093 public boolean isRunning() {
1094 return mRunning;
1095 }
1096
1097 public boolean setRunning(boolean running, long uptime, long realtime) {
1098 if (mRunning != running) {
1099 mRunning = running;
1100 if (running) {
1101 mUptimeStart = uptime;
1102 mRealtimeStart = realtime;
1103 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1104 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
1105
1106 for (int i = mObservers.size() - 1; i >= 0; i--) {
1107 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
1108 }
1109 } else {
1110 mPastUptime += uptime - mUptimeStart;
1111 mPastRealtime += realtime - mRealtimeStart;
1112
1113 long batteryUptime = getUptime(uptime);
1114 long batteryRealtime = getRealtime(realtime);
1115
1116 for (int i = mObservers.size() - 1; i >= 0; i--) {
1117 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
1118 }
1119 }
1120 return true;
1121 }
1122 return false;
1123 }
1124
1125 public void readSummaryFromParcel(Parcel in) {
1126 mUptime = in.readLong();
1127 mRealtime = in.readLong();
1128 }
1129
1130 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1131 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1132 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1133 }
1134
1135 public void readFromParcel(Parcel in) {
1136 mRunning = false;
1137 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001138 mPastUptime = in.readLong();
1139 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001140 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001141 mPastRealtime = in.readLong();
1142 mRealtimeStart = in.readLong();
1143 mUnpluggedUptime = in.readLong();
1144 mUnpluggedRealtime = in.readLong();
1145 }
1146
1147 public void writeToParcel(Parcel out, long uptime, long realtime) {
1148 final long runningUptime = getUptime(uptime);
1149 final long runningRealtime = getRealtime(realtime);
1150 out.writeLong(mUptime);
1151 out.writeLong(runningUptime);
1152 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001153 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001154 out.writeLong(runningRealtime);
1155 out.writeLong(mRealtimeStart);
1156 out.writeLong(mUnpluggedUptime);
1157 out.writeLong(mUnpluggedRealtime);
1158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001162 * State for keeping track of counting information.
1163 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001164 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -07001165 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001166 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001167 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001168 int mUnpluggedCount;
1169 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001170
Bookatz8c6f3c52017-05-24 12:00:17 -07001171 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001172 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -07001173 mPluggedCount = in.readInt();
1174 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001175 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001176 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001177 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001178 }
1179
Bookatz8c6f3c52017-05-24 12:00:17 -07001180 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001181 mTimeBase = timeBase;
1182 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001183 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001184
Dianne Hackborn617f8772009-03-31 15:04:46 -07001185 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001186 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001187 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001188 out.writeInt(mUnpluggedCount);
1189 }
1190
Bookatz8c6f3c52017-05-24 12:00:17 -07001191 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001192 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001193 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001194 }
1195
Bookatz8c6f3c52017-05-24 12:00:17 -07001196 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001197 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001198 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001199 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001200
Dianne Hackborn617f8772009-03-31 15:04:46 -07001201 /**
1202 * Writes a possibly null Counter to a Parcel.
1203 *
1204 * @param out the Parcel to be written to.
1205 * @param counter a Counter, or null.
1206 */
1207 public static void writeCounterToParcel(Parcel out, Counter counter) {
1208 if (counter == null) {
1209 out.writeInt(0); // indicates null
1210 return;
1211 }
1212 out.writeInt(1); // indicates non-null
1213
1214 counter.writeToParcel(out);
1215 }
1216
1217 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001218 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001219 int val = mCount.get();
1220 if (which == STATS_SINCE_UNPLUGGED) {
1221 val -= mUnpluggedCount;
1222 } else if (which != STATS_SINCE_CHARGED) {
1223 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001224 }
1225
1226 return val;
1227 }
1228
1229 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001230 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001231 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001232 + " mUnpluggedCount=" + mUnpluggedCount
1233 + " mPluggedCount=" + mPluggedCount);
1234 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001235
Bookatz8c6f3c52017-05-24 12:00:17 -07001236 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1237 public void stepAtomic() {
1238 if (mTimeBase.isRunning()) {
1239 mCount.incrementAndGet();
1240 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001241 }
1242
Bookatz4ebc0642017-05-11 12:21:19 -07001243 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001244 if (mTimeBase.isRunning()) {
1245 mCount.addAndGet(delta);
1246 }
Bookatz4ebc0642017-05-11 12:21:19 -07001247 }
1248
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001249 /**
1250 * Clear state of this counter.
1251 */
1252 void reset(boolean detachIfReset) {
1253 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001254 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001255 if (detachIfReset) {
1256 detach();
1257 }
1258 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001259
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001260 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001261 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001262 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001263
Bookatz8c6f3c52017-05-24 12:00:17 -07001264 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1265 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001266 int count = mCount.get();
1267 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001268 }
1269
Bookatz8c6f3c52017-05-24 12:00:17 -07001270 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1271 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001272 mLoadedCount = in.readInt();
1273 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001274 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001275 }
1276 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001277
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001278 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001279 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1280 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001281 public long[] mCounts;
1282 public long[] mLoadedCounts;
1283 public long[] mUnpluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001284
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001285 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001286 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001287 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001288 mLoadedCounts = in.createLongArray();
1289 mUnpluggedCounts = in.createLongArray();
1290 timeBase.add(this);
1291 }
1292
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001293 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001294 mTimeBase = timeBase;
1295 timeBase.add(this);
1296 }
1297
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001298 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001299 out.writeLongArray(mCounts);
1300 out.writeLongArray(mLoadedCounts);
1301 out.writeLongArray(mUnpluggedCounts);
1302 }
1303
1304 @Override
1305 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001306 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001307 }
1308
1309 @Override
1310 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001311 }
1312
1313 @Override
1314 public long[] getCountsLocked(int which) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001315 long[] val = copyArray(mCounts, null);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001316 if (which == STATS_SINCE_UNPLUGGED) {
1317 subtract(val, mUnpluggedCounts);
1318 } else if (which != STATS_SINCE_CHARGED) {
1319 subtract(val, mLoadedCounts);
1320 }
1321 return val;
1322 }
1323
1324 @Override
1325 public void logState(Printer pw, String prefix) {
1326 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1327 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
Sudheer Shankae544d162017-12-28 17:06:20 -08001328 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001329 }
1330
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001331 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001332 addCountLocked(counts, mTimeBase.isRunning());
1333 }
1334
1335 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001336 if (counts == null) {
1337 return;
1338 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001339 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001340 if (mCounts == null) {
1341 mCounts = new long[counts.length];
1342 }
1343 for (int i = 0; i < counts.length; ++i) {
1344 mCounts[i] += counts[i];
1345 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001346 }
1347 }
1348
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001349 public int getSize() {
1350 return mCounts == null ? 0 : mCounts.length;
1351 }
1352
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001353 /**
1354 * Clear state of this counter.
1355 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001356 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001357 fillArray(mCounts, 0);
1358 fillArray(mLoadedCounts, 0);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001359 fillArray(mUnpluggedCounts, 0);
1360 if (detachIfReset) {
1361 detach();
1362 }
1363 }
1364
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001365 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001366 mTimeBase.remove(this);
1367 }
1368
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001369 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001370 out.writeLongArray(mCounts);
1371 }
1372
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001373 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001374 mCounts = in.createLongArray();
1375 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1376 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001377 }
1378
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001379 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1380 if (counterArray != null) {
1381 out.writeInt(1);
1382 counterArray.writeToParcel(out);
1383 } else {
1384 out.writeInt(0);
1385 }
1386 }
1387
1388 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1389 if (in.readInt() != 0) {
1390 return new LongSamplingCounterArray(timeBase, in);
1391 } else {
1392 return null;
1393 }
1394 }
1395
1396 public static void writeSummaryToParcelLocked(Parcel out,
1397 LongSamplingCounterArray counterArray) {
1398 if (counterArray != null) {
1399 out.writeInt(1);
1400 counterArray.writeSummaryToParcelLocked(out);
1401 } else {
1402 out.writeInt(0);
1403 }
1404 }
1405
1406 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1407 TimeBase timeBase) {
1408 if (in.readInt() != 0) {
1409 final LongSamplingCounterArray counterArray
1410 = new LongSamplingCounterArray(timeBase);
1411 counterArray.readSummaryFromParcelLocked(in);
1412 return counterArray;
1413 } else {
1414 return null;
1415 }
1416 }
1417
Bookatz8c6f3c52017-05-24 12:00:17 -07001418 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001419 if (a != null) {
1420 Arrays.fill(a, val);
1421 }
1422 }
1423
Bookatz8c6f3c52017-05-24 12:00:17 -07001424 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001425 if (toSubtract == null) {
1426 return;
1427 }
1428 for (int i = 0; i < val.length; i++) {
1429 val[i] -= toSubtract[i];
1430 }
1431 }
1432
Bookatz8c6f3c52017-05-24 12:00:17 -07001433 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001434 if (src == null) {
1435 return null;
1436 } else {
1437 if (dest == null) {
1438 dest = new long[src.length];
1439 }
1440 System.arraycopy(src, 0, dest, 0, src.length);
1441 return dest;
1442 }
1443 }
1444 }
1445
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001446 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001447 final TimeBase mTimeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001448 long mCount;
1449 long mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001450 long mUnpluggedCount;
1451 long mPluggedCount;
1452
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001453 LongSamplingCounter(TimeBase timeBase, Parcel in) {
1454 mTimeBase = timeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001455 mPluggedCount = in.readLong();
1456 mCount = mPluggedCount;
1457 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001458 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001459 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001460 }
1461
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001462 LongSamplingCounter(TimeBase timeBase) {
1463 mTimeBase = timeBase;
1464 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001465 }
1466
1467 public void writeToParcel(Parcel out) {
1468 out.writeLong(mCount);
1469 out.writeLong(mLoadedCount);
1470 out.writeLong(mUnpluggedCount);
1471 }
1472
1473 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001474 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001475 mUnpluggedCount = mPluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001476 }
1477
1478 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001479 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001480 mPluggedCount = mCount;
1481 }
1482
1483 public long getCountLocked(int which) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001484 long val = mTimeBase.isRunning() ? mCount : mPluggedCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001485 if (which == STATS_SINCE_UNPLUGGED) {
1486 val -= mUnpluggedCount;
1487 } else if (which != STATS_SINCE_CHARGED) {
1488 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001489 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001490 return val;
1491 }
1492
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001493 @Override
1494 public void logState(Printer pw, String prefix) {
1495 pw.println(prefix + "mCount=" + mCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001496 + " mLoadedCount=" + mLoadedCount
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001497 + " mUnpluggedCount=" + mUnpluggedCount
1498 + " mPluggedCount=" + mPluggedCount);
1499 }
1500
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001501 void addCountLocked(long count) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001502 if (mTimeBase.isRunning()) {
1503 mCount += count;
1504 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001505 }
1506
1507 /**
1508 * Clear state of this counter.
1509 */
1510 void reset(boolean detachIfReset) {
1511 mCount = 0;
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001512 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001513 if (detachIfReset) {
1514 detach();
1515 }
1516 }
1517
1518 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001519 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001520 }
1521
1522 void writeSummaryFromParcelLocked(Parcel out) {
1523 out.writeLong(mCount);
1524 }
1525
1526 void readSummaryFromParcelLocked(Parcel in) {
1527 mLoadedCount = in.readLong();
1528 mCount = mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001529 mUnpluggedCount = mPluggedCount = mLoadedCount;
1530 }
1531 }
1532
Dianne Hackborn617f8772009-03-31 15:04:46 -07001533 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 * State for keeping track of timing information.
1535 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001536 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001537 protected final Clocks mClocks;
1538 protected final int mType;
1539 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001540
Joe Onoratoabded112016-02-08 16:49:39 -08001541 protected int mCount;
1542 protected int mLoadedCount;
1543 protected int mLastCount;
1544 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 // Times are in microseconds for better accuracy when dividing by the
1547 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 /**
1550 * The total time we have accumulated since the start of the original
1551 * boot, to the last time something interesting happened in the
1552 * current run.
1553 */
Joe Onoratoabded112016-02-08 16:49:39 -08001554 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 /**
1557 * The total time we loaded for the previous runs. Subtract this from
1558 * mTotalTime to find the time for the current run of the system.
1559 */
Joe Onoratoabded112016-02-08 16:49:39 -08001560 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 /**
1563 * The run time of the last run of the system, as loaded from the
1564 * saved data.
1565 */
Joe Onoratoabded112016-02-08 16:49:39 -08001566 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 /**
1569 * The value of mTotalTime when unplug() was last called. Subtract
1570 * this from mTotalTime to find the time since the last unplug from
1571 * power.
1572 */
Joe Onoratoabded112016-02-08 16:49:39 -08001573 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001574
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001575 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001576 * The total time this timer has been running until the latest mark has been set.
1577 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1578 */
Joe Onoratoabded112016-02-08 16:49:39 -08001579 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001580
1581 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001582 * Constructs from a parcel.
1583 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001584 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001585 * @param in
1586 */
Joe Onoratoabded112016-02-08 16:49:39 -08001587 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1588 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001590 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 mCount = in.readInt();
1593 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001594 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 mUnpluggedCount = in.readInt();
1596 mTotalTime = in.readLong();
1597 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001598 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001600 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001601 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001602 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 }
1604
Joe Onoratoabded112016-02-08 16:49:39 -08001605 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1606 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001608 mTimeBase = timeBase;
1609 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 }
Evan Millarc64edde2009-04-18 12:26:32 -07001611
1612 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001613
Evan Millarc64edde2009-04-18 12:26:32 -07001614 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001615
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001616 /**
1617 * Clear state of this timer. Returns true if the timer is inactive
1618 * so can be completely dropped.
1619 */
Joe Onoratoabded112016-02-08 16:49:39 -08001620 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001621 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001622 mCount = mLoadedCount = mLastCount = 0;
1623 if (detachIfReset) {
1624 detach();
1625 }
1626 return true;
1627 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001628
Joe Onoratoabded112016-02-08 16:49:39 -08001629 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001630 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001631 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001632
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001633 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001634 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1635 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001636 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001639 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001642 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644
Adam Lesinskie08af192015-03-25 16:42:59 -07001645 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001646 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001648 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 + " old mUnpluggedTime=" + mUnpluggedTime
1650 + " old mUnpluggedCount=" + mUnpluggedCount);
1651 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001652 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001653 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 if (DEBUG && mType < 0) {
1655 Log.v(TAG, "unplug #" + mType
1656 + ": new mUnpluggedTime=" + mUnpluggedTime
1657 + " new mUnpluggedCount=" + mUnpluggedCount);
1658 }
1659 }
1660
Adam Lesinskie08af192015-03-25 16:42:59 -07001661 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001662 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001663 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001664 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001665 + " old mTotalTime=" + mTotalTime);
1666 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001667 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001668 mCount = computeCurrentCountLocked();
1669 if (DEBUG && mType < 0) {
1670 Log.v(TAG, "plug #" + mType
1671 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
1673 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 /**
1676 * Writes a possibly null Timer to a Parcel.
1677 *
1678 * @param out the Parcel to be written to.
1679 * @param timer a Timer, or null.
1680 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001681 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 if (timer == null) {
1683 out.writeInt(0); // indicates null
1684 return;
1685 }
1686 out.writeInt(1); // indicates non-null
1687
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001688 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
1690
1691 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001692 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001693 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1694 if (which == STATS_SINCE_UNPLUGGED) {
1695 val -= mUnpluggedTime;
1696 } else if (which != STATS_SINCE_CHARGED) {
1697 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 }
1699
1700 return val;
1701 }
1702
1703 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001704 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001705 int val = computeCurrentCountLocked();
1706 if (which == STATS_SINCE_UNPLUGGED) {
1707 val -= mUnpluggedCount;
1708 } else if (which != STATS_SINCE_CHARGED) {
1709 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
1711
1712 return val;
1713 }
1714
Adam Lesinskie08af192015-03-25 16:42:59 -07001715 @Override
1716 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1717 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1718 return val - mTimeBeforeMark;
1719 }
1720
1721 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001722 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001723 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1725 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001726 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001728 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001730 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001731
1732
Joe Onoratoabded112016-02-08 16:49:39 -08001733 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001734 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1735 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001736 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001737 }
1738
Joe Onoratoabded112016-02-08 16:49:39 -08001739 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001740 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001741 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001742 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001743 mUnpluggedTime = mTotalTime;
1744 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001745 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001746 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001747
1748 // When reading the summary, we set the mark to be the latest information.
1749 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001750 }
1751 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001752
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001753 /**
1754 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1755 * method. The state of the timer according to its {@link TimeBase} will determine how much
1756 * of the value is recorded.
1757 *
1758 * If the value being recorded resets, {@link #endSample()} can be called in order to
1759 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1760 * between calls, the {@link #endSample()} is automatically called and the new value is
1761 * expected to increase monotonically from that point on.
1762 */
Joe Onoratoabded112016-02-08 16:49:39 -08001763 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001764
Evan Millarc64edde2009-04-18 12:26:32 -07001765 /**
1766 * The most recent reported count from /proc/wakelocks.
1767 */
1768 int mCurrentReportedCount;
1769
1770 /**
1771 * The reported count from /proc/wakelocks when unplug() was last
1772 * called.
1773 */
1774 int mUnpluggedReportedCount;
1775
1776 /**
1777 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001778 */
Evan Millarc64edde2009-04-18 12:26:32 -07001779 long mCurrentReportedTotalTime;
1780
1781
1782 /**
1783 * The reported total_time from /proc/wakelocks when unplug() was last
1784 * called.
1785 */
1786 long mUnpluggedReportedTotalTime;
1787
1788 /**
1789 * Whether we are currently in a discharge cycle.
1790 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001791 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001792
1793 /**
1794 * Whether we are currently recording reported values.
1795 */
1796 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001797
Evan Millarc64edde2009-04-18 12:26:32 -07001798 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001799 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001800 */
1801 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001802
Adam Lesinski98f0d462016-04-19 16:46:20 -07001803 @VisibleForTesting
1804 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001805 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001806 mCurrentReportedCount = in.readInt();
1807 mUnpluggedReportedCount = in.readInt();
1808 mCurrentReportedTotalTime = in.readLong();
1809 mUnpluggedReportedTotalTime = in.readLong();
1810 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001811 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001812 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001813
Adam Lesinski98f0d462016-04-19 16:46:20 -07001814 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001815 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001816 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001817 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001818 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001819 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001820
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001821 /**
1822 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1823 * be less than the values used for a previous invocation.
1824 */
1825 public void endSample() {
1826 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1827 mCount = computeCurrentCountLocked();
1828 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1829 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001830 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001831
Evan Millarc64edde2009-04-18 12:26:32 -07001832 public void setUpdateVersion(int version) {
1833 mUpdateVersion = version;
1834 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001835
Evan Millarc64edde2009-04-18 12:26:32 -07001836 public int getUpdateVersion() {
1837 return mUpdateVersion;
1838 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001839
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001840 /**
1841 * Updates the current recorded values. These are meant to be monotonically increasing
1842 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1843 *
1844 * If the values being recorded have been reset, the monotonically increasing requirement
1845 * will be broken. In this case, {@link #endSample()} is automatically called and
1846 * the total value of totalTime and count are recorded, starting a new monotonically
1847 * increasing sample.
1848 *
1849 * @param totalTime total time of sample in microseconds.
1850 * @param count total number of times the event being sampled occurred.
1851 */
1852 public void update(long totalTime, int count) {
1853 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001854 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001855 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001856 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001857 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001858
1859 mTrackingReportedValues = true;
1860
1861 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1862 endSample();
1863 }
1864
1865 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001866 mCurrentReportedCount = count;
1867 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001868
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001869 /**
1870 * Adds deltaTime and deltaCount to the current sample.
1871 *
1872 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1873 * @param deltaCount additional number of times the event being sampled occurred.
1874 */
1875 public void add(long deltaTime, int deltaCount) {
1876 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001877 }
1878
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001879 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001880 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
1881 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001882 if (mTrackingReportedValues) {
1883 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
1884 mUnpluggedReportedCount = mCurrentReportedCount;
1885 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001886 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07001887 }
1888
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001889 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001890 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1891 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1892 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07001893 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001894
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001895 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001896 public void logState(Printer pw, String prefix) {
1897 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001898 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07001899 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
1900 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
1901 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
1902 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001903
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001904 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001905 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001906 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001907 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
1908 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001909
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001910 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001911 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001912 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001913 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
1914 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001915
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001916 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001917 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1918 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001919 out.writeInt(mCurrentReportedCount);
1920 out.writeInt(mUnpluggedReportedCount);
1921 out.writeLong(mCurrentReportedTotalTime);
1922 out.writeLong(mUnpluggedReportedTotalTime);
1923 out.writeInt(mTrackingReportedValues ? 1 : 0);
1924 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001925
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001926 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001927 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001928 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001929 mTrackingReportedValues = false;
1930 mUnpluggedReportedTotalTime = 0;
1931 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001932 return true;
1933 }
Evan Millarc64edde2009-04-18 12:26:32 -07001934 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001935
Evan Millarc64edde2009-04-18 12:26:32 -07001936 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001937 * A timer that increments in batches. It does not run for durations, but just jumps
1938 * for a pre-determined amount.
1939 */
Joe Onoratoabded112016-02-08 16:49:39 -08001940 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001941 final Uid mUid;
1942
1943 /**
1944 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
1945 */
1946 long mLastAddedTime;
1947
1948 /**
1949 * The last duration that we added to the timer. This is in microseconds.
1950 */
1951 long mLastAddedDuration;
1952
1953 /**
1954 * Whether we are currently in a discharge cycle.
1955 */
1956 boolean mInDischarge;
1957
Joe Onoratoabded112016-02-08 16:49:39 -08001958 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
1959 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001960 mUid = uid;
1961 mLastAddedTime = in.readLong();
1962 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001963 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001964 }
1965
Joe Onoratoabded112016-02-08 16:49:39 -08001966 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
1967 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001968 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001969 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001970 }
1971
1972 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001973 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1974 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001975 out.writeLong(mLastAddedTime);
1976 out.writeLong(mLastAddedDuration);
1977 }
1978
1979 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001980 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001981 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001982 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001983 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001984 }
1985
1986 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001987 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001988 recomputeLastDuration(elapsedRealtime, false);
1989 mInDischarge = true;
1990 // If we are still within the last added duration, then re-added whatever remains.
1991 if (mLastAddedTime == elapsedRealtime) {
1992 mTotalTime += mLastAddedDuration;
1993 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001994 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001995 }
1996
1997 @Override
1998 public void logState(Printer pw, String prefix) {
1999 super.logState(pw, prefix);
2000 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
2001 + " mLastAddedDuration=" + mLastAddedDuration);
2002 }
2003
2004 private long computeOverage(long curTime) {
2005 if (mLastAddedTime > 0) {
2006 return mLastTime + mLastAddedDuration - curTime;
2007 }
2008 return 0;
2009 }
2010
2011 private void recomputeLastDuration(long curTime, boolean abort) {
2012 final long overage = computeOverage(curTime);
2013 if (overage > 0) {
2014 // Aborting before the duration ran out -- roll back the remaining
2015 // duration. Only do this if currently discharging; otherwise we didn't
2016 // actually add the time.
2017 if (mInDischarge) {
2018 mTotalTime -= overage;
2019 }
2020 if (abort) {
2021 mLastAddedTime = 0;
2022 } else {
2023 mLastAddedTime = curTime;
2024 mLastAddedDuration -= overage;
2025 }
2026 }
2027 }
2028
2029 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08002030 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002031 recomputeLastDuration(now, true);
2032 mLastAddedTime = now;
2033 mLastAddedDuration = durationMillis * 1000;
2034 if (mInDischarge) {
2035 mTotalTime += mLastAddedDuration;
2036 mCount++;
2037 }
2038 }
2039
2040 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002041 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002042 recomputeLastDuration(now, true);
2043 }
2044
2045 @Override
2046 protected int computeCurrentCountLocked() {
2047 return mCount;
2048 }
2049
2050 @Override
2051 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002052 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002053 if (overage > 0) {
2054 return mTotalTime = overage;
2055 }
2056 return mTotalTime;
2057 }
2058
2059 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002060 public boolean reset(boolean detachIfReset) {
2061 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002062 recomputeLastDuration(now, true);
2063 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002064 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002065 return !stillActive;
2066 }
2067 }
2068
Joe Onorato92fd23f2016-07-25 11:18:42 -07002069
2070 /**
2071 * A StopwatchTimer that also tracks the total and max individual
2072 * time spent active according to the given timebase. Whereas
2073 * StopwatchTimer apportions the time amongst all in the pool,
2074 * the total and max durations are not apportioned.
2075 */
2076 public static class DurationTimer extends StopwatchTimer {
2077 /**
2078 * The time (in ms) that the timer was last acquired or the time base
2079 * last (re-)started. Increasing the nesting depth does not reset this time.
2080 *
2081 * -1 if the timer is currently not running or the time base is not running.
2082 *
2083 * If written to a parcel, the start time is reset, as is mNesting in the base class
2084 * StopwatchTimer.
2085 */
2086 long mStartTimeMs = -1;
2087
2088 /**
Bookatz867c0d72017-03-07 18:23:42 -08002089 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002090 */
2091 long mMaxDurationMs;
2092
2093 /**
Bookatz867c0d72017-03-07 18:23:42 -08002094 * The time (in ms) that that the timer has been active since most recent
2095 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002096 */
2097 long mCurrentDurationMs;
2098
Bookatz867c0d72017-03-07 18:23:42 -08002099 /**
2100 * The total time (in ms) that that the timer has been active since most recent reset()
2101 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2102 * (but not including the present currentDuration) since reset. Not pooled.
2103 */
2104 long mTotalDurationMs;
2105
Joe Onorato92fd23f2016-07-25 11:18:42 -07002106 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2107 TimeBase timeBase, Parcel in) {
2108 super(clocks, uid, type, timerPool, timeBase, in);
2109 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002110 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002111 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002112 }
2113
2114 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2115 TimeBase timeBase) {
2116 super(clocks, uid, type, timerPool, timeBase);
2117 }
2118
2119 @Override
2120 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2121 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002122 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002123 out.writeLong(mTotalDurationMs);
2124 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002125 }
2126
2127 /**
2128 * Write the summary to the parcel.
2129 *
2130 * Since the time base is probably meaningless after we come back, reading
2131 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002132 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002133 */
2134 @Override
2135 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2136 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002137 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002138 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002139 }
2140
2141 /**
2142 * Read the summary parcel.
2143 *
2144 * Has the side effect of stopping the timer.
2145 */
2146 @Override
2147 public void readSummaryFromParcelLocked(Parcel in) {
2148 super.readSummaryFromParcelLocked(in);
2149 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002150 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002151 mStartTimeMs = -1;
2152 mCurrentDurationMs = 0;
2153 }
2154
2155 /**
2156 * The TimeBase time started (again).
2157 *
2158 * If the timer is also running, store the start time.
2159 */
2160 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2161 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2162 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002163 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002164 }
2165 }
2166
2167 /**
2168 * The TimeBase stopped running.
2169 *
2170 * If the timer is running, add the duration into mCurrentDurationMs.
2171 */
2172 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002173 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2174 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002175 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002176 // baseRealtimeUs has already been converted to the timebase's realtime.
2177 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002178 }
2179 mStartTimeMs = -1;
2180 }
2181
2182 @Override
2183 public void logState(Printer pw, String prefix) {
2184 super.logState(pw, prefix);
2185 }
2186
2187 @Override
2188 public void startRunningLocked(long elapsedRealtimeMs) {
2189 super.startRunningLocked(elapsedRealtimeMs);
2190 if (mNesting == 1 && mTimeBase.isRunning()) {
2191 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002192 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002193 }
2194 }
2195
2196 /**
2197 * Decrements the mNesting ref-count on this timer.
2198 *
2199 * If it actually stopped (mNesting went to 0), then possibly update
2200 * mMaxDuration if the current duration was the longest ever.
2201 */
2202 @Override
2203 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002204 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002205 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002206 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002207 if (durationMs > mMaxDurationMs) {
2208 mMaxDurationMs = durationMs;
2209 }
2210 mStartTimeMs = -1;
2211 mCurrentDurationMs = 0;
2212 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002213 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2214 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2215 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002216 }
2217
2218 @Override
2219 public boolean reset(boolean detachIfReset) {
2220 boolean result = super.reset(detachIfReset);
2221 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002222 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002223 mCurrentDurationMs = 0;
2224 if (mNesting > 0) {
2225 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2226 } else {
2227 mStartTimeMs = -1;
2228 }
2229 return result;
2230 }
2231
2232 /**
2233 * Returns the max duration that this timer has ever seen.
2234 *
2235 * Note that this time is NOT split between the timers in the timer group that
2236 * this timer is attached to. It is the TOTAL time.
2237 */
2238 @Override
2239 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2240 if (mNesting > 0) {
2241 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2242 if (durationMs > mMaxDurationMs) {
2243 return durationMs;
2244 }
2245 }
2246 return mMaxDurationMs;
2247 }
2248
2249 /**
2250 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002251 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002252 *
2253 * Note that this time is NOT split between the timers in the timer group that
2254 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002255 *
2256 * Note that if running timer is parceled and unparceled, this method will return
2257 * current duration value at the time of parceling even though timer may not be
2258 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002259 */
2260 @Override
2261 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2262 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002263 if (mNesting > 0 && mTimeBase.isRunning()) {
2264 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2265 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002266 }
2267 return durationMs;
2268 }
Bookatz867c0d72017-03-07 18:23:42 -08002269
2270 /**
2271 * Returns the total cumulative duration that this timer has been on since reset().
2272 * If mTimerPool == null, this should be the same
2273 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2274 *
2275 * Note that this time is NOT split between the timers in the timer group that
2276 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2277 * the result will not be equivalent to getTotalTimeLocked.
2278 */
2279 @Override
2280 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2281 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2282 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002283 }
2284
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002285 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002286 * State for keeping track of timing information.
2287 */
Joe Onoratoabded112016-02-08 16:49:39 -08002288 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002289 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002290 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002291
Evan Millarc64edde2009-04-18 12:26:32 -07002292 int mNesting;
2293
Evan Millarc64edde2009-04-18 12:26:32 -07002294 /**
2295 * The last time at which we updated the timer. If mNesting is > 0,
2296 * subtract this from the current battery time to find the amount of
2297 * time we have been running since we last computed an update.
2298 */
2299 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002300
Evan Millarc64edde2009-04-18 12:26:32 -07002301 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002302 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002303 * was actually held for an interesting duration. If time base was not running when timer
2304 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002305 */
Bookatzceebafe2017-04-06 11:59:13 -07002306 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002307
Amith Yamasanif37447b2009-10-08 18:28:01 -07002308 long mTimeout;
2309
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002310 /**
2311 * For partial wake locks, keep track of whether we are in the list
2312 * to consume CPU cycles.
2313 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002314 @VisibleForTesting
2315 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002316
Joe Onoratoabded112016-02-08 16:49:39 -08002317 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002318 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002319 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002320 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002321 mTimerPool = timerPool;
2322 mUpdateTime = in.readLong();
2323 }
2324
Joe Onoratoabded112016-02-08 16:49:39 -08002325 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002326 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002327 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002328 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002329 mTimerPool = timerPool;
2330 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002331
Joe Onoratoabded112016-02-08 16:49:39 -08002332 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002333 mTimeout = timeout;
2334 }
2335
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002336 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2337 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002338 out.writeLong(mUpdateTime);
2339 }
2340
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002341 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002342 if (mNesting > 0) {
2343 if (DEBUG && mType < 0) {
2344 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2345 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002346 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2347 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002348 if (DEBUG && mType < 0) {
2349 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2350 }
2351 }
2352 }
2353
2354 public void logState(Printer pw, String prefix) {
2355 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002356 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 + " mAcquireTime=" + mAcquireTime);
2358 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002359
Joe Onoratoabded112016-02-08 16:49:39 -08002360 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002362 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002363 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 if (mTimerPool != null) {
2365 // Accumulate time to all currently active timers before adding
2366 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002367 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 // Add this timer to the active pool
2369 mTimerPool.add(this);
2370 }
Bookatzceebafe2017-04-06 11:59:13 -07002371 if (mTimeBase.isRunning()) {
2372 // Increment the count
2373 mCount++;
2374 mAcquireTime = mTotalTime;
2375 } else {
2376 mAcquireTime = -1;
2377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 if (DEBUG && mType < 0) {
2379 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2380 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2381 + " mAcquireTime=" + mAcquireTime);
2382 }
2383 }
2384 }
2385
Joe Onoratoabded112016-02-08 16:49:39 -08002386 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002387 return mNesting > 0;
2388 }
2389
Joe Onoratoabded112016-02-08 16:49:39 -08002390 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 // Ignore attempt to stop a timer that isn't running
2392 if (mNesting == 0) {
2393 return;
2394 }
2395 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002396 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 if (mTimerPool != null) {
2398 // Accumulate time to all active counters, scaled by the total
2399 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002400 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 // Remove this timer from the active pool
2402 mTimerPool.remove(this);
2403 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 mNesting = 1;
2405 mTotalTime = computeRunTimeLocked(batteryRealtime);
2406 mNesting = 0;
2407 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 if (DEBUG && mType < 0) {
2410 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2411 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2412 + " mAcquireTime=" + mAcquireTime);
2413 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002414
Bookatzceebafe2017-04-06 11:59:13 -07002415 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 // If there was no change in the time, then discard this
2417 // count. A somewhat cheezy strategy, but hey.
2418 mCount--;
2419 }
2420 }
2421 }
2422
Joe Onoratoabded112016-02-08 16:49:39 -08002423 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002424 if (mNesting > 0) {
2425 mNesting = 1;
2426 stopRunningLocked(elapsedRealtimeMs);
2427 }
2428 }
2429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 // Update the total time for all other running Timers with the same type as this Timer
2431 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002432 private static long refreshTimersLocked(long batteryRealtime,
2433 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002434 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 final int N = pool.size();
2436 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002437 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 long heldTime = batteryRealtime - t.mUpdateTime;
2439 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002440 final long myTime = heldTime / N;
2441 if (t == self) {
2442 selfTime = myTime;
2443 }
2444 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 }
2446 t.mUpdateTime = batteryRealtime;
2447 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002448 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 }
2450
Evan Millarc64edde2009-04-18 12:26:32 -07002451 @Override
2452 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002453 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2454 curBatteryRealtime = mUpdateTime + mTimeout;
2455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 return mTotalTime + (mNesting > 0
2457 ? (curBatteryRealtime - mUpdateTime)
2458 / (mTimerPool != null ? mTimerPool.size() : 1)
2459 : 0);
2460 }
2461
Evan Millarc64edde2009-04-18 12:26:32 -07002462 @Override
2463 protected int computeCurrentCountLocked() {
2464 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 }
2466
Adam Lesinskie08af192015-03-25 16:42:59 -07002467 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002468 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002469 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002470 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002471 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002472 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002473 }
Bookatzceebafe2017-04-06 11:59:13 -07002474 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002475 return canDetach;
2476 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002477
Adam Lesinskie08af192015-03-25 16:42:59 -07002478 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002479 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002480 super.detach();
2481 if (mTimerPool != null) {
2482 mTimerPool.remove(this);
2483 }
2484 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002485
Adam Lesinskie08af192015-03-25 16:42:59 -07002486 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002487 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002488 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 mNesting = 0;
2490 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002491
2492 /**
2493 * Set the mark so that we can query later for the total time the timer has
2494 * accumulated since this point. The timer can be running or not.
2495 *
2496 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2497 */
2498 public void setMark(long elapsedRealtimeMs) {
2499 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2500 if (mNesting > 0) {
2501 // We are running.
2502 if (mTimerPool != null) {
2503 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2504 } else {
2505 mTotalTime += batteryRealtime - mUpdateTime;
2506 mUpdateTime = batteryRealtime;
2507 }
2508 }
2509 mTimeBeforeMark = mTotalTime;
2510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002512
Bookatz867c0d72017-03-07 18:23:42 -08002513 /**
2514 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2515 * TimeBase is effectively a subset of the other.
2516 */
Bookatzaa4594a2017-03-24 12:39:56 -07002517 public static class DualTimer extends DurationTimer {
2518 // This class both is a DurationTimer and also holds a second DurationTimer.
2519 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2520 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2521 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002522 // mSubTimer typically tracks only part of the total time, such as background time, as
2523 // determined by a subTimeBase. It is NOT pooled.
2524 private final DurationTimer mSubTimer;
2525
2526 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002527 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2528 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002529 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002530 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002531 */
2532 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2533 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002534 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002535 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2536 }
2537
2538 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002539 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2540 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002541 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002542 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002543 */
2544 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2545 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002546 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002547 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2548 }
2549
Bookatz867c0d72017-03-07 18:23:42 -08002550 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002551 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002552 public DurationTimer getSubTimer() {
2553 return mSubTimer;
2554 }
2555
Bookatzaa4594a2017-03-24 12:39:56 -07002556 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002557 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002558 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002559 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2560 }
2561
Bookatzaa4594a2017-03-24 12:39:56 -07002562 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002563 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002564 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002565 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2566 }
2567
Bookatzaa4594a2017-03-24 12:39:56 -07002568 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002569 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002570 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002571 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2572 }
2573
Bookatzaa4594a2017-03-24 12:39:56 -07002574 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002575 public boolean reset(boolean detachIfReset) {
2576 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002577 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2578 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002579 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002580 return !active;
2581 }
2582
Bookatzaa4594a2017-03-24 12:39:56 -07002583 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002584 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002585 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002586 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002587 }
2588
Bookatzaa4594a2017-03-24 12:39:56 -07002589 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002590 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002591 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002592 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2593 }
2594
Bookatzaa4594a2017-03-24 12:39:56 -07002595 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002596 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002597 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002598 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2599 }
2600
Bookatzaa4594a2017-03-24 12:39:56 -07002601 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002602 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002603 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002604 mSubTimer.readSummaryFromParcelLocked(in);
2605 }
2606 }
2607
2608
Dianne Hackbornd953c532014-08-16 18:17:38 -07002609 public abstract class OverflowArrayMap<T> {
2610 private static final String OVERFLOW_NAME = "*overflow*";
2611
Dianne Hackborn657153b2016-07-29 14:54:14 -07002612 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002613 final ArrayMap<String, T> mMap = new ArrayMap<>();
2614 T mCurOverflow;
2615 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002616 long mLastOverflowTime;
2617 long mLastOverflowFinishTime;
2618 long mLastClearTime;
2619 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002620
Dianne Hackborn657153b2016-07-29 14:54:14 -07002621 public OverflowArrayMap(int uid) {
2622 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002623 }
2624
2625 public ArrayMap<String, T> getMap() {
2626 return mMap;
2627 }
2628
2629 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002630 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002631 mMap.clear();
2632 mCurOverflow = null;
2633 mActiveOverflow = null;
2634 }
2635
2636 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002637 if (name == null) {
2638 name = "";
2639 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002640 mMap.put(name, obj);
2641 if (OVERFLOW_NAME.equals(name)) {
2642 mCurOverflow = obj;
2643 }
2644 }
2645
2646 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002647 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002648 if (mActiveOverflow != null) {
2649 if (mActiveOverflow.size() == 0) {
2650 mActiveOverflow = null;
2651 }
2652 }
2653 if (mActiveOverflow == null) {
2654 // There is no currently active overflow, so we should no longer have
2655 // an overflow entry.
2656 if (mMap.containsKey(OVERFLOW_NAME)) {
2657 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2658 + mMap.get(OVERFLOW_NAME));
2659 mMap.remove(OVERFLOW_NAME);
2660 }
2661 mCurOverflow = null;
2662 } else {
2663 // There is currently active overflow, so we should still have an overflow entry.
2664 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2665 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2666 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2667 }
2668 }
2669 }
2670
2671 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002672 if (name == null) {
2673 name = "";
2674 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002675 T obj = mMap.get(name);
2676 if (obj != null) {
2677 return obj;
2678 }
2679
2680 // No object exists for the given name, but do we currently have it
2681 // running as part of the overflow?
2682 if (mActiveOverflow != null) {
2683 MutableInt over = mActiveOverflow.get(name);
2684 if (over != null) {
2685 // We are already actively counting this name in the overflow object.
2686 obj = mCurOverflow;
2687 if (obj == null) {
2688 // Shouldn't be here, but we'll try to recover.
2689 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2690 obj = mCurOverflow = instantiateObject();
2691 mMap.put(OVERFLOW_NAME, obj);
2692 }
2693 over.value++;
2694 return obj;
2695 }
2696 }
2697
2698 // No object exists for given name nor in the overflow; we need to make
2699 // a new one.
2700 final int N = mMap.size();
2701 if (N >= MAX_WAKELOCKS_PER_UID) {
2702 // Went over the limit on number of objects to track; this one goes
2703 // in to the overflow.
2704 obj = mCurOverflow;
2705 if (obj == null) {
2706 // Need to start overflow now...
2707 obj = mCurOverflow = instantiateObject();
2708 mMap.put(OVERFLOW_NAME, obj);
2709 }
2710 if (mActiveOverflow == null) {
2711 mActiveOverflow = new ArrayMap<>();
2712 }
2713 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002714 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002715 return obj;
2716 }
2717
2718 // Normal case where we just need to make a new object.
2719 obj = instantiateObject();
2720 mMap.put(name, obj);
2721 return obj;
2722 }
2723
2724 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002725 if (name == null) {
2726 name = "";
2727 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002728 T obj = mMap.get(name);
2729 if (obj != null) {
2730 return obj;
2731 }
2732
2733 // No object exists for the given name, but do we currently have it
2734 // running as part of the overflow?
2735 if (mActiveOverflow != null) {
2736 MutableInt over = mActiveOverflow.get(name);
2737 if (over != null) {
2738 // We are already actively counting this name in the overflow object.
2739 obj = mCurOverflow;
2740 if (obj != null) {
2741 over.value--;
2742 if (over.value <= 0) {
2743 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002744 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002745 }
2746 return obj;
2747 }
2748 }
2749 }
2750
2751 // Huh, they are stopping an active operation but we can't find one!
2752 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002753 StringBuilder sb = new StringBuilder();
2754 sb.append("Unable to find object for ");
2755 sb.append(name);
2756 sb.append(" in uid ");
2757 sb.append(mUid);
2758 sb.append(" mapsize=");
2759 sb.append(mMap.size());
2760 sb.append(" activeoverflow=");
2761 sb.append(mActiveOverflow);
2762 sb.append(" curoverflow=");
2763 sb.append(mCurOverflow);
2764 long now = SystemClock.elapsedRealtime();
2765 if (mLastOverflowTime != 0) {
2766 sb.append(" lastOverflowTime=");
2767 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2768 }
2769 if (mLastOverflowFinishTime != 0) {
2770 sb.append(" lastOverflowFinishTime=");
2771 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2772 }
2773 if (mLastClearTime != 0) {
2774 sb.append(" lastClearTime=");
2775 TimeUtils.formatDuration(mLastClearTime-now, sb);
2776 }
2777 if (mLastCleanupTime != 0) {
2778 sb.append(" lastCleanupTime=");
2779 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2780 }
2781 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002782 return null;
2783 }
2784
2785 public abstract T instantiateObject();
2786 }
2787
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002788 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2789 implements Parcelable {
2790 private final LongSamplingCounter mIdleTimeMillis;
Siddharth Rayb50a6842017-12-14 15:15:28 -08002791 private final LongSamplingCounter mScanTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002792 private final LongSamplingCounter mRxTimeMillis;
2793 private final LongSamplingCounter[] mTxTimeMillis;
2794 private final LongSamplingCounter mPowerDrainMaMs;
2795
2796 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2797 mIdleTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002798 mScanTimeMillis = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002799 mRxTimeMillis = new LongSamplingCounter(timeBase);
2800 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2801 for (int i = 0; i < numTxStates; i++) {
2802 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2803 }
2804 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2805 }
2806
2807 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2808 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002809 mScanTimeMillis = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002810 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2811 final int recordedTxStates = in.readInt();
2812 if (recordedTxStates != numTxStates) {
2813 throw new ParcelFormatException("inconsistent tx state lengths");
2814 }
2815
2816 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2817 for (int i = 0; i < numTxStates; i++) {
2818 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2819 }
2820 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2821 }
2822
2823 public void readSummaryFromParcel(Parcel in) {
2824 mIdleTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002825 mScanTimeMillis.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002826 mRxTimeMillis.readSummaryFromParcelLocked(in);
2827 final int recordedTxStates = in.readInt();
2828 if (recordedTxStates != mTxTimeMillis.length) {
2829 throw new ParcelFormatException("inconsistent tx state lengths");
2830 }
2831 for (LongSamplingCounter counter : mTxTimeMillis) {
2832 counter.readSummaryFromParcelLocked(in);
2833 }
2834 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2835 }
2836
2837 @Override
2838 public int describeContents() {
2839 return 0;
2840 }
2841
2842 public void writeSummaryToParcel(Parcel dest) {
2843 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002844 mScanTimeMillis.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002845 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2846 dest.writeInt(mTxTimeMillis.length);
2847 for (LongSamplingCounter counter : mTxTimeMillis) {
2848 counter.writeSummaryFromParcelLocked(dest);
2849 }
2850 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2851 }
2852
2853 @Override
2854 public void writeToParcel(Parcel dest, int flags) {
2855 mIdleTimeMillis.writeToParcel(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002856 mScanTimeMillis.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002857 mRxTimeMillis.writeToParcel(dest);
2858 dest.writeInt(mTxTimeMillis.length);
2859 for (LongSamplingCounter counter : mTxTimeMillis) {
2860 counter.writeToParcel(dest);
2861 }
2862 mPowerDrainMaMs.writeToParcel(dest);
2863 }
2864
2865 public void reset(boolean detachIfReset) {
2866 mIdleTimeMillis.reset(detachIfReset);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002867 mScanTimeMillis.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002868 mRxTimeMillis.reset(detachIfReset);
2869 for (LongSamplingCounter counter : mTxTimeMillis) {
2870 counter.reset(detachIfReset);
2871 }
2872 mPowerDrainMaMs.reset(detachIfReset);
2873 }
2874
2875 public void detach() {
2876 mIdleTimeMillis.detach();
Siddharth Rayb50a6842017-12-14 15:15:28 -08002877 mScanTimeMillis.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002878 mRxTimeMillis.detach();
2879 for (LongSamplingCounter counter : mTxTimeMillis) {
2880 counter.detach();
2881 }
2882 mPowerDrainMaMs.detach();
2883 }
2884
2885 /**
2886 * @return a LongSamplingCounter, measuring time spent in the idle state in
2887 * milliseconds.
2888 */
2889 @Override
2890 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07002891 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002892 }
2893
2894 /**
Siddharth Rayb50a6842017-12-14 15:15:28 -08002895 * @return a LongSamplingCounter, measuring time spent in the scan state in
2896 * milliseconds.
2897 */
2898 @Override
2899 public LongSamplingCounter getScanTimeCounter() {
2900 return mScanTimeMillis;
2901 }
2902
2903 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002904 * @return a LongSamplingCounter, measuring time spent in the receive state in
2905 * milliseconds.
2906 */
2907 @Override
2908 public LongSamplingCounter getRxTimeCounter() {
2909 return mRxTimeMillis;
2910 }
2911
2912 /**
2913 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
2914 * milliseconds.
2915 */
2916 @Override
2917 public LongSamplingCounter[] getTxTimeCounters() {
2918 return mTxTimeMillis;
2919 }
2920
2921 /**
2922 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
2923 */
2924 @Override
2925 public LongSamplingCounter getPowerCounter() {
2926 return mPowerDrainMaMs;
2927 }
2928 }
2929
Bookatz50df7112017-08-04 14:53:26 -07002930 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
2931 public SamplingTimer getRpmTimerLocked(String name) {
2932 SamplingTimer rpmt = mRpmStats.get(name);
2933 if (rpmt == null) {
2934 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2935 mRpmStats.put(name, rpmt);
2936 }
2937 return rpmt;
2938 }
2939
2940 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
2941 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
2942 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
2943 if (rpmt == null) {
2944 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
2945 mScreenOffRpmStats.put(name, rpmt);
2946 }
2947 return rpmt;
2948 }
2949
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002950 /*
2951 * Get the wakeup reason counter, and create a new one if one
2952 * doesn't already exist.
2953 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002954 public SamplingTimer getWakeupReasonTimerLocked(String name) {
2955 SamplingTimer timer = mWakeupReasonStats.get(name);
2956 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002957 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002958 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002959 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002960 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002961 }
2962
Evan Millarc64edde2009-04-18 12:26:32 -07002963 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002964 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07002965 * doesn't already exist.
2966 */
2967 public SamplingTimer getKernelWakelockTimerLocked(String name) {
2968 SamplingTimer kwlt = mKernelWakelockStats.get(name);
2969 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002970 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07002971 mKernelWakelockStats.put(name, kwlt);
2972 }
2973 return kwlt;
2974 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07002975
James Carr3a226052016-07-01 14:49:52 -07002976 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
2977 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
2978 if (kmt == null) {
2979 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2980 mKernelMemoryStats.put(bucket, kmt);
2981 }
2982 return kmt;
2983 }
2984
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002985 private int writeHistoryTag(HistoryTag tag) {
2986 Integer idxObj = mHistoryTagPool.get(tag);
2987 int idx;
2988 if (idxObj != null) {
2989 idx = idxObj;
2990 } else {
2991 idx = mNextHistoryTagIdx;
2992 HistoryTag key = new HistoryTag();
2993 key.setTo(tag);
2994 tag.poolIdx = idx;
2995 mHistoryTagPool.put(key, idx);
2996 mNextHistoryTagIdx++;
2997 mNumHistoryTagChars += key.string.length() + 1;
2998 }
2999 return idx;
3000 }
3001
3002 private void readHistoryTag(int index, HistoryTag tag) {
3003 tag.string = mReadHistoryStrings[index];
3004 tag.uid = mReadHistoryUids[index];
3005 tag.poolIdx = index;
3006 }
3007
Adam Lesinski926969b2016-04-28 17:31:12 -07003008 /*
3009 The history delta format uses flags to denote further data in subsequent ints in the parcel.
3010
3011 There is always the first token, which may contain the delta time, or an indicator of
3012 the length of the time (int or long) following this token.
3013
3014 First token: always present,
3015 31 23 15 7 0
3016 â–ˆ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â–ˆ
3017
3018 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
3019 follows containing the time, and 0x7ffff indicates a long immediately follows with the
3020 delta time.
3021 A: battery level changed and an int follows with battery data.
3022 B: state changed and an int follows with state change data.
3023 C: state2 has changed and an int follows with state2 change data.
3024 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
3025 E: event data has changed and an event struct follows.
3026 F: battery charge in coulombs has changed and an int with the charge follows.
3027 G: state flag denoting that the mobile radio was active.
3028 H: state flag denoting that the wifi radio was active.
3029 I: state flag denoting that a wifi scan occurred.
3030 J: state flag denoting that a wifi full lock was held.
3031 K: state flag denoting that the gps was on.
3032 L: state flag denoting that a wakelock was held.
3033 M: state flag denoting that the cpu was running.
3034
3035 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3036 with the time delta.
3037
3038 Battery level int: if A in the first token is set,
3039 31 23 15 7 0
3040 â–ˆ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â–ˆ
3041
3042 D: indicates that extra history details follow.
3043 V: the battery voltage.
3044 T: the battery temperature.
3045 L: the battery level (out of 100).
3046
3047 State change int: if B in the first token is set,
3048 31 23 15 7 0
3049 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3050
3051 A: wifi multicast was on.
3052 B: battery was plugged in.
3053 C: screen was on.
3054 D: phone was scanning for signal.
3055 E: audio was on.
3056 F: a sensor was active.
3057
3058 State2 change int: if C in the first token is set,
3059 31 23 15 7 0
3060 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3061
3062 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3063 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3064 C: a bluetooth scan was active.
3065 D: the camera was active.
3066 E: bluetooth was on.
3067 F: a phone call was active.
3068 G: the device was charging.
3069 H: 2 bits indicating the device-idle (doze) state: off, light, full
3070 I: the flashlight was on.
3071 J: wifi was on.
3072 K: wifi was running.
3073 L: video was playing.
3074 M: power save mode was on.
3075
3076 Wakelock/wakereason struct: if D in the first token is set,
3077 TODO(adamlesinski): describe wakelock/wakereason struct.
3078
3079 Event struct: if E in the first token is set,
3080 TODO(adamlesinski): describe the event struct.
3081
3082 History step details struct: if D in the battery level int is set,
3083 TODO(adamlesinski): describe the history step details struct.
3084
3085 Battery charge int: if F in the first token is set, an int representing the battery charge
3086 in coulombs follows.
3087 */
3088
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003089 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003090 static final int DELTA_TIME_MASK = 0x7ffff;
3091 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3092 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3093 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003094 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003095 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003096 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003097 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003098 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003099 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003100 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003101 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003102 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003103 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003104 // Flag in delta int: contains the battery charge count in uAh.
3105 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003106 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003107 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003108
3109 // These are the pieces of battery state that are packed in to the upper bits of
3110 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003111 // in STATE_BATTERY_MASK.
3112 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003113 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3114 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3115 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3116 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3117 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3118 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003119
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003120 // We use the low bit of the battery state int to indicate that we have full details
3121 // from a battery level change.
3122 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3123
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003124 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003125 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003126 dest.writeInt(DELTA_TIME_ABS);
3127 cur.writeToParcel(dest, 0);
3128 return;
3129 }
3130
3131 final long deltaTime = cur.time - last.time;
3132 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3133 final int lastStateInt = buildStateInt(last);
3134
3135 int deltaTimeToken;
3136 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3137 deltaTimeToken = DELTA_TIME_LONG;
3138 } else if (deltaTime >= DELTA_TIME_ABS) {
3139 deltaTimeToken = DELTA_TIME_INT;
3140 } else {
3141 deltaTimeToken = (int)deltaTime;
3142 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003143 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003144 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3145 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3146 final boolean computeStepDetails = includeStepDetails != 0
3147 || mLastHistoryStepDetails == null;
3148 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003149 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3150 if (batteryLevelIntChanged) {
3151 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3152 }
3153 final int stateInt = buildStateInt(cur);
3154 final boolean stateIntChanged = stateInt != lastStateInt;
3155 if (stateIntChanged) {
3156 firstToken |= DELTA_STATE_FLAG;
3157 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003158 final boolean state2IntChanged = cur.states2 != last.states2;
3159 if (state2IntChanged) {
3160 firstToken |= DELTA_STATE2_FLAG;
3161 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003162 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003163 firstToken |= DELTA_WAKELOCK_FLAG;
3164 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003165 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3166 firstToken |= DELTA_EVENT_FLAG;
3167 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003168
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003169 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3170 if (batteryChargeChanged) {
3171 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003172 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003173 dest.writeInt(firstToken);
3174 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3175 + " deltaTime=" + deltaTime);
3176
3177 if (deltaTimeToken >= DELTA_TIME_INT) {
3178 if (deltaTimeToken == DELTA_TIME_INT) {
3179 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3180 dest.writeInt((int)deltaTime);
3181 } else {
3182 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3183 dest.writeLong(deltaTime);
3184 }
3185 }
3186 if (batteryLevelIntChanged) {
3187 dest.writeInt(batteryLevelInt);
3188 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3189 + Integer.toHexString(batteryLevelInt)
3190 + " batteryLevel=" + cur.batteryLevel
3191 + " batteryTemp=" + cur.batteryTemperature
3192 + " batteryVolt=" + (int)cur.batteryVoltage);
3193 }
3194 if (stateIntChanged) {
3195 dest.writeInt(stateInt);
3196 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3197 + Integer.toHexString(stateInt)
3198 + " batteryStatus=" + cur.batteryStatus
3199 + " batteryHealth=" + cur.batteryHealth
3200 + " batteryPlugType=" + cur.batteryPlugType
3201 + " states=0x" + Integer.toHexString(cur.states));
3202 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003203 if (state2IntChanged) {
3204 dest.writeInt(cur.states2);
3205 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3206 + Integer.toHexString(cur.states2));
3207 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003208 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3209 int wakeLockIndex;
3210 int wakeReasonIndex;
3211 if (cur.wakelockTag != null) {
3212 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3213 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3214 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3215 } else {
3216 wakeLockIndex = 0xffff;
3217 }
3218 if (cur.wakeReasonTag != null) {
3219 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3220 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3221 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3222 } else {
3223 wakeReasonIndex = 0xffff;
3224 }
3225 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003226 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003227 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003228 int index = writeHistoryTag(cur.eventTag);
3229 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003230 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003231 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3232 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3233 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003234 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003235 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003236 if (mPlatformIdleStateCallback != null) {
3237 mCurHistoryStepDetails.statPlatformIdleState =
3238 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3239 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3240 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003241
3242 mCurHistoryStepDetails.statSubsystemPowerState =
3243 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3244 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3245 mCurHistoryStepDetails.statSubsystemPowerState);
3246
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003247 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003248 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3249 if (includeStepDetails != 0) {
3250 mCurHistoryStepDetails.writeToParcel(dest);
3251 }
3252 cur.stepDetails = mCurHistoryStepDetails;
3253 mLastHistoryStepDetails = mCurHistoryStepDetails;
3254 } else {
3255 cur.stepDetails = null;
3256 }
3257 if (mLastHistoryStepLevel < cur.batteryLevel) {
3258 mLastHistoryStepDetails = null;
3259 }
3260 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003261
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003262 if (batteryChargeChanged) {
3263 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3264 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003265 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003266 }
3267
3268 private int buildBatteryLevelInt(HistoryItem h) {
3269 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003270 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3271 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3272 }
3273
3274 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3275 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3276 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3277 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003278 }
3279
3280 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003281 int plugType = 0;
3282 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3283 plugType = 1;
3284 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3285 plugType = 2;
3286 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3287 plugType = 3;
3288 }
3289 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3290 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3291 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003292 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003293 }
3294
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003295 private void computeHistoryStepDetails(final HistoryStepDetails out,
3296 final HistoryStepDetails last) {
3297 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3298
3299 // Perform a CPU update right after we do this collection, so we have started
3300 // collecting good data for the next step.
3301 requestImmediateCpuUpdate();
3302
3303 if (last == null) {
3304 // We are not generating a delta, so all we need to do is reset the stats
3305 // we will later be doing a delta from.
3306 final int NU = mUidStats.size();
3307 for (int i=0; i<NU; i++) {
3308 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3309 uid.mLastStepUserTime = uid.mCurStepUserTime;
3310 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3311 }
3312 mLastStepCpuUserTime = mCurStepCpuUserTime;
3313 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3314 mLastStepStatUserTime = mCurStepStatUserTime;
3315 mLastStepStatSystemTime = mCurStepStatSystemTime;
3316 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3317 mLastStepStatIrqTime = mCurStepStatIrqTime;
3318 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3319 mLastStepStatIdleTime = mCurStepStatIdleTime;
3320 tmp.clear();
3321 return;
3322 }
3323 if (DEBUG) {
3324 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3325 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3326 + " irq=" + mLastStepStatIrqTime + " sirq="
3327 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3328 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3329 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3330 + " irq=" + mCurStepStatIrqTime + " sirq="
3331 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3332 }
3333 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3334 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3335 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3336 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3337 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3338 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3339 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3340 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3341 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3342 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3343 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3344 final int NU = mUidStats.size();
3345 for (int i=0; i<NU; i++) {
3346 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3347 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3348 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3349 final int totalTime = totalUTime + totalSTime;
3350 uid.mLastStepUserTime = uid.mCurStepUserTime;
3351 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3352 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3353 continue;
3354 }
3355 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3356 out.appCpuUid3 = uid.mUid;
3357 out.appCpuUTime3 = totalUTime;
3358 out.appCpuSTime3 = totalSTime;
3359 } else {
3360 out.appCpuUid3 = out.appCpuUid2;
3361 out.appCpuUTime3 = out.appCpuUTime2;
3362 out.appCpuSTime3 = out.appCpuSTime2;
3363 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3364 out.appCpuUid2 = uid.mUid;
3365 out.appCpuUTime2 = totalUTime;
3366 out.appCpuSTime2 = totalSTime;
3367 } else {
3368 out.appCpuUid2 = out.appCpuUid1;
3369 out.appCpuUTime2 = out.appCpuUTime1;
3370 out.appCpuSTime2 = out.appCpuSTime1;
3371 out.appCpuUid1 = uid.mUid;
3372 out.appCpuUTime1 = totalUTime;
3373 out.appCpuSTime1 = totalSTime;
3374 }
3375 }
3376 }
3377 mLastStepCpuUserTime = mCurStepCpuUserTime;
3378 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3379 mLastStepStatUserTime = mCurStepStatUserTime;
3380 mLastStepStatSystemTime = mCurStepStatSystemTime;
3381 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3382 mLastStepStatIrqTime = mCurStepStatIrqTime;
3383 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3384 mLastStepStatIdleTime = mCurStepStatIdleTime;
3385 }
3386
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003387 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3388 int firstToken = src.readInt();
3389 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003390 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003391 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003392 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3393 + " deltaTimeToken=" + deltaTimeToken);
3394
3395 if (deltaTimeToken < DELTA_TIME_ABS) {
3396 cur.time += deltaTimeToken;
3397 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3398 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003399 cur.numReadInts += 2;
3400 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003401 cur.readFromParcel(src);
3402 return;
3403 } else if (deltaTimeToken == DELTA_TIME_INT) {
3404 int delta = src.readInt();
3405 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003406 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003407 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3408 } else {
3409 long delta = src.readLong();
3410 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3411 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003412 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003413 }
3414
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003415 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003416 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003417 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003418 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003419 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003420 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3421 + Integer.toHexString(batteryLevelInt)
3422 + " batteryLevel=" + cur.batteryLevel
3423 + " batteryTemp=" + cur.batteryTemperature
3424 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003425 } else {
3426 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003427 }
3428
3429 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3430 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003431 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003432 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3433 & STATE_BATTERY_STATUS_MASK);
3434 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3435 & STATE_BATTERY_HEALTH_MASK);
3436 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3437 & STATE_BATTERY_PLUG_MASK);
3438 switch (cur.batteryPlugType) {
3439 case 1:
3440 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3441 break;
3442 case 2:
3443 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3444 break;
3445 case 3:
3446 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3447 break;
3448 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003449 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003450 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3451 + Integer.toHexString(stateInt)
3452 + " batteryStatus=" + cur.batteryStatus
3453 + " batteryHealth=" + cur.batteryHealth
3454 + " batteryPlugType=" + cur.batteryPlugType
3455 + " states=0x" + Integer.toHexString(cur.states));
3456 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003457 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003458 }
3459
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003460 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3461 cur.states2 = src.readInt();
3462 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3463 + Integer.toHexString(cur.states2));
3464 }
3465
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003466 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003467 int indexes = src.readInt();
3468 int wakeLockIndex = indexes&0xffff;
3469 int wakeReasonIndex = (indexes>>16)&0xffff;
3470 if (wakeLockIndex != 0xffff) {
3471 cur.wakelockTag = cur.localWakelockTag;
3472 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3473 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3474 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3475 } else {
3476 cur.wakelockTag = null;
3477 }
3478 if (wakeReasonIndex != 0xffff) {
3479 cur.wakeReasonTag = cur.localWakeReasonTag;
3480 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3481 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3482 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3483 } else {
3484 cur.wakeReasonTag = null;
3485 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003486 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003487 } else {
3488 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003489 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003490 }
3491
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003492 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003493 cur.eventTag = cur.localEventTag;
3494 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003495 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003496 final int index = ((codeAndIndex>>16)&0xffff);
3497 readHistoryTag(index, cur.eventTag);
3498 cur.numReadInts += 1;
3499 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3500 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3501 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003502 } else {
3503 cur.eventCode = HistoryItem.EVENT_NONE;
3504 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003505
3506 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3507 cur.stepDetails = mReadHistoryStepDetails;
3508 cur.stepDetails.readFromParcel(src);
3509 } else {
3510 cur.stepDetails = null;
3511 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003512
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003513 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3514 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003515 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003516 }
3517
Dianne Hackbornfc064132014-06-02 12:42:12 -07003518 @Override
3519 public void commitCurrentHistoryBatchLocked() {
3520 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3521 }
3522
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003523 void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003524 if (!mHaveBatteryLevel || !mRecordingHistory) {
3525 return;
3526 }
3527
Dianne Hackborn40c87252014-03-19 16:55:40 -07003528 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003529 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3530 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003531 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003532 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003533 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3534 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003535 + Integer.toHexString(lastDiffStates) + " diff2="
3536 + Integer.toHexString(diffStates2) + " lastDiff2="
3537 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003538 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003539 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003540 && (diffStates2&lastDiffStates2) == 0
3541 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3542 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003543 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003544 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003545 || cur.eventCode == HistoryItem.EVENT_NONE)
3546 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3547 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3548 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3549 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3550 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3551 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003552 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003553 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003554 // as long as no bit has changed both between now and the last entry, as
3555 // well as the last entry and the one before it (so we capture any toggles).
3556 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003557 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3558 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3559 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003560 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003561 // If the last written history had a wakelock tag, we need to retain it.
3562 // Note that the condition above made sure that we aren't in a case where
3563 // both it and the current history item have a wakelock tag.
3564 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003565 cur.wakelockTag = cur.localWakelockTag;
3566 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003567 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003568 // If the last written history had a wake reason tag, we need to retain it.
3569 // Note that the condition above made sure that we aren't in a case where
3570 // both it and the current history item have a wakelock tag.
3571 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003572 cur.wakeReasonTag = cur.localWakeReasonTag;
3573 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003574 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003575 // If the last written history had an event, we need to retain it.
3576 // Note that the condition above made sure that we aren't in a case where
3577 // both it and the current history item have an event.
3578 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003579 cur.eventCode = mHistoryLastWritten.eventCode;
3580 cur.eventTag = cur.localEventTag;
3581 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003582 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003583 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003584 }
3585
Adam Lesinski45489782016-12-15 23:45:17 -08003586 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003587 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003588 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3589 // Clients can't deal with history buffers this large. This only
3590 // really happens when the device is on charger and interacted with
3591 // for long periods of time, like in retail mode. Since the device is
3592 // most likely charged, when unplugged, stats would have reset anyways.
3593 // Reset the stats and mark that we overflowed.
3594 // b/32540341
3595 resetAllStatsLocked();
3596
3597 // Mark that we want to set *OVERFLOW* event and the RESET:START
3598 // events.
3599 recordResetDueToOverflow = true;
3600
3601 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003602 if (!mHistoryOverflow) {
3603 mHistoryOverflow = true;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003604 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
3605 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003606 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003607 }
3608
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003609 // After overflow, we allow various bit-wise states to settle to 0.
3610 boolean writeAnyway = false;
3611 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3612 & mActiveHistoryStates;
3613 if (mHistoryLastWritten.states != curStates) {
3614 // mActiveHistoryStates keeps track of which bits in .states are now being
3615 // forced to 0.
3616 int old = mActiveHistoryStates;
3617 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3618 writeAnyway |= old != mActiveHistoryStates;
3619 }
3620 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3621 & mActiveHistoryStates2;
3622 if (mHistoryLastWritten.states2 != curStates2) {
3623 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3624 // forced to 0.
3625 int old = mActiveHistoryStates2;
3626 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3627 writeAnyway |= old != mActiveHistoryStates2;
3628 }
3629
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003630 // Once we've reached the maximum number of items, we only
3631 // record changes to the battery level and the most interesting states.
3632 // Once we've reached the maximum maximum number of items, we only
3633 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003634 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003635 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003636 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003637 & HistoryItem.MOST_INTERESTING_STATES) == 0
3638 || ((mHistoryLastWritten.states2^cur.states2)
3639 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003640 return;
3641 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003642
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003643 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003644 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003645 }
3646
Adam Lesinski45489782016-12-15 23:45:17 -08003647 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003648 // The history is currently empty; we need it to start with a time stamp.
3649 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003650 if (recordResetDueToOverflow) {
3651 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
3652 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003653 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_RESET, cur);
3654 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003655 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003656 }
3657
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003658 private void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd,
3659 HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003660 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003661 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003662 }
3663 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3664 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003665 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003666 mHistoryLastWritten.states &= mActiveHistoryStates;
3667 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003668 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003669 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003670 cur.wakelockTag = null;
3671 cur.wakeReasonTag = null;
3672 cur.eventCode = HistoryItem.EVENT_NONE;
3673 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003674 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3675 + " now " + mHistoryBuffer.dataPosition()
3676 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003677 }
3678
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003679 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003680 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003681
Dianne Hackborn40c87252014-03-19 16:55:40 -07003682 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003683 if (mTrackRunningHistoryElapsedRealtime != 0) {
3684 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3685 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3686 if (diffUptime < (diffElapsed-20)) {
3687 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3688 mHistoryAddTmp.setTo(mHistoryLastWritten);
3689 mHistoryAddTmp.wakelockTag = null;
3690 mHistoryAddTmp.wakeReasonTag = null;
3691 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3692 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
3693 addHistoryRecordInnerLocked(wakeElapsedTime, uptimeMs, mHistoryAddTmp);
3694 }
3695 }
3696 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3697 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3698 mTrackRunningHistoryUptime = uptimeMs;
3699 addHistoryRecordInnerLocked(elapsedRealtimeMs, uptimeMs, mHistoryCur);
3700 }
3701
3702 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
3703 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003704
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003705 if (!USE_OLD_HISTORY) {
3706 return;
3707 }
3708
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003709 if (!mHaveBatteryLevel || !mRecordingHistory) {
3710 return;
3711 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003712
3713 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003714 // and no states have since the last recorded entry changed and
3715 // are now resetting back to their original value, then just collapse
3716 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003717 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003718 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003719 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3720 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003721 // If the current is the same as the one before, then we no
3722 // longer need the entry.
3723 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003724 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003725 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003726 mHistoryLastEnd.next = null;
3727 mHistoryEnd.next = mHistoryCache;
3728 mHistoryCache = mHistoryEnd;
3729 mHistoryEnd = mHistoryLastEnd;
3730 mHistoryLastEnd = null;
3731 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003732 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3733 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003734 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003735 }
3736 return;
3737 }
3738
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003739 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003740 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003741
3742 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3743 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07003744 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003745 }
3746
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003747 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3748 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003749 // record changes to the battery level and the most interesting states.
3750 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003751 // record changes to the battery level.
3752 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003753 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003754 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003755 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003756 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003757 return;
3758 }
3759 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003760
Dianne Hackborn40c87252014-03-19 16:55:40 -07003761 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003762 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003763
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003764 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003765 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003766 mHistoryCur.eventCode = code;
3767 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3768 mHistoryCur.eventTag.string = name;
3769 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003770 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003771 }
3772
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003773 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003774 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003775 if (rec != null) {
3776 mHistoryCache = rec.next;
3777 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003778 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003779 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003780 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003781
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003782 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003783 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003784
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003785 void addHistoryRecordLocked(HistoryItem rec) {
3786 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003787 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003788 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003789 if (mHistoryEnd != null) {
3790 mHistoryEnd.next = rec;
3791 mHistoryEnd = rec;
3792 } else {
3793 mHistory = mHistoryEnd = rec;
3794 }
3795 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003796
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003797 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003798 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003799 if (USE_OLD_HISTORY) {
3800 if (mHistory != null) {
3801 mHistoryEnd.next = mHistoryCache;
3802 mHistoryCache = mHistory;
3803 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3804 }
3805 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003806 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003807
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003808 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003809 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003810 mTrackRunningHistoryElapsedRealtime = 0;
3811 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003812
3813 mHistoryBuffer.setDataSize(0);
3814 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003815 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003816 mHistoryLastLastWritten.clear();
3817 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003818 mHistoryTagPool.clear();
3819 mNextHistoryTagIdx = 0;
3820 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003821 mHistoryBufferLastPos = -1;
3822 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003823 mActiveHistoryStates = 0xffffffff;
3824 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003825 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003826
Mike Mac2f518a2017-09-19 16:06:03 -07003827 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003828 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003829 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003830 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3831 final boolean updateOnBatteryScreenOffTimeBase =
3832 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003833
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003834 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3835 if (updateOnBatteryScreenOffTimeBase) {
3836 updateKernelWakelocksLocked();
3837 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003838 }
Bookatz82b341172017-09-07 19:06:08 -07003839 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3840 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3841 // improved, remove the surrounding if{}.
3842 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3843 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3844 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003845 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003846 Slog.d(TAG, "Updating cpu time because screen is now "
3847 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003848 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003849 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -07003850 updateCpuTimeLocked();
Sudheer Shankae544d162017-12-28 17:06:20 -08003851 mExternalSync.scheduleCopyFromAllUidsCpuTimes(mOnBatteryTimeBase.isRunning(),
3852 mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003853
3854 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07003855 if (updateOnBatteryTimeBase) {
3856 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3857 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003858 }
Mike Mac2f518a2017-09-19 16:06:03 -07003859 }
3860 if (updateOnBatteryScreenOffTimeBase) {
3861 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
3862 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3863 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003864 }
Bookatzc8c44962017-05-11 12:12:54 -07003865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 }
3867 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003868
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003869 private void updateBatteryPropertiesLocked() {
3870 try {
3871 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
3872 ServiceManager.getService("batteryproperties"));
3873 registrar.scheduleUpdate();
3874 } catch (RemoteException e) {
3875 // Ignore.
3876 }
3877 }
3878
Dianne Hackborn099bc622014-01-22 13:39:16 -08003879 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
3880 mIsolatedUids.put(isolatedUid, appUid);
David Chen21582962017-11-01 17:32:46 -07003881 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid, 1);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003882 final Uid u = getUidStatsLocked(appUid);
3883 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003884 }
3885
Adam Lesinski61db88f2015-07-01 15:05:07 -07003886 /**
3887 * Schedules a read of the latest cpu times before removing the isolated UID.
3888 * @see #removeIsolatedUidLocked(int)
3889 */
3890 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003891 int curUid = mIsolatedUids.get(isolatedUid, -1);
3892 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07003893 if (mExternalSync != null) {
3894 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
3895 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08003896 }
3897 }
3898
Adam Lesinski61db88f2015-07-01 15:05:07 -07003899 /**
3900 * This should only be called after the cpu times have been read.
3901 * @see #scheduleRemoveIsolatedUidLocked(int, int)
3902 */
3903 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003904 StatsLog.write(
3905 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1), isolatedUid, 0);
3906 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
3907 if (idx >= 0) {
3908 final int ownerUid = mIsolatedUids.valueAt(idx);
3909 final Uid u = getUidStatsLocked(ownerUid);
3910 u.removeIsolatedUid(isolatedUid);
3911 mIsolatedUids.removeAt(idx);
3912 }
3913 mKernelUidCpuTimeReader.removeUid(isolatedUid);
3914 mKernelUidCpuFreqTimeReader.removeUid(isolatedUid);
Mike Mafae87da2018-01-19 20:07:20 -08003915 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
3916 mKernelUidCpuActiveTimeReader.removeUid(isolatedUid);
3917 mKernelUidCpuClusterTimeReader.removeUid(isolatedUid);
3918 }
Adam Lesinski61db88f2015-07-01 15:05:07 -07003919 }
3920
Dianne Hackborn099bc622014-01-22 13:39:16 -08003921 public int mapUid(int uid) {
3922 int isolated = mIsolatedUids.get(uid, -1);
3923 return isolated > 0 ? isolated : uid;
3924 }
3925
3926 public void noteEventLocked(int code, String name, int uid) {
3927 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003928 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3929 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003930 }
Joe Onoratoabded112016-02-08 16:49:39 -08003931 final long elapsedRealtime = mClocks.elapsedRealtime();
3932 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003933 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003934 }
3935
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003936 boolean ensureStartClockTime(final long currentTime) {
3937 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
3938 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
3939 // If the start clock time has changed by more than a year, then presumably
3940 // the previous time was completely bogus. So we are going to figure out a
3941 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08003942 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003943 return true;
3944 }
3945 return false;
3946 }
3947
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003948 public void noteCurrentTimeChangedLocked() {
3949 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003950 final long elapsedRealtime = mClocks.elapsedRealtime();
3951 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003952 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003953 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003954 }
3955
Dianne Hackborn61659e52014-07-09 16:13:01 -07003956 public void noteProcessStartLocked(String name, int uid) {
3957 uid = mapUid(uid);
3958 if (isOnBattery()) {
3959 Uid u = getUidStatsLocked(uid);
3960 u.getProcessStatsLocked(name).incStartsLocked();
3961 }
3962 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3963 return;
3964 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003965 if (!mRecordAllHistory) {
3966 return;
3967 }
Joe Onoratoabded112016-02-08 16:49:39 -08003968 final long elapsedRealtime = mClocks.elapsedRealtime();
3969 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07003970 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
3971 }
3972
Dianne Hackborn1e01d162014-12-04 17:46:42 -08003973 public void noteProcessCrashLocked(String name, int uid) {
3974 uid = mapUid(uid);
3975 if (isOnBattery()) {
3976 Uid u = getUidStatsLocked(uid);
3977 u.getProcessStatsLocked(name).incNumCrashesLocked();
3978 }
3979 }
3980
3981 public void noteProcessAnrLocked(String name, int uid) {
3982 uid = mapUid(uid);
3983 if (isOnBattery()) {
3984 Uid u = getUidStatsLocked(uid);
3985 u.getProcessStatsLocked(name).incNumAnrsLocked();
3986 }
3987 }
3988
Dianne Hackborna8d10942015-11-19 17:55:19 -08003989 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07003990 int parentUid = mapUid(uid);
3991 if (uid != parentUid) {
3992 // Isolated UIDs process state is already rolled up into parent, so no need to track
3993 // Otherwise the parent's process state will get downgraded incorrectly
3994 return;
3995 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08003996 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003997 }
3998
3999 public void noteProcessFinishLocked(String name, int uid) {
4000 uid = mapUid(uid);
4001 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4002 return;
4003 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004004 if (!mRecordAllHistory) {
4005 return;
4006 }
Joe Onoratoabded112016-02-08 16:49:39 -08004007 final long elapsedRealtime = mClocks.elapsedRealtime();
4008 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004009 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004010 }
4011
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004012 public void noteSyncStartLocked(String name, int uid) {
4013 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004014 final long elapsedRealtime = mClocks.elapsedRealtime();
4015 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004016 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4017 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4018 return;
4019 }
4020 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4021 }
4022
4023 public void noteSyncFinishLocked(String name, int uid) {
4024 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004025 final long elapsedRealtime = mClocks.elapsedRealtime();
4026 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004027 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4028 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4029 return;
4030 }
4031 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4032 }
4033
4034 public void noteJobStartLocked(String name, int uid) {
4035 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004036 final long elapsedRealtime = mClocks.elapsedRealtime();
4037 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004038 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4039 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4040 return;
4041 }
4042 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4043 }
4044
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004045 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004046 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004047 final long elapsedRealtime = mClocks.elapsedRealtime();
4048 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004049 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004050 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4051 return;
4052 }
4053 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4054 }
4055
Narayan Kamath695cf722017-12-21 18:32:47 +00004056 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4057 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004058 }
4059
Narayan Kamath695cf722017-12-21 18:32:47 +00004060 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4061 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4062 }
4063
4064 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4065 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004066 if (!mRecordAllHistory) {
4067 return;
4068 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004069
Joe Onoratoabded112016-02-08 16:49:39 -08004070 final long elapsedRealtime = mClocks.elapsedRealtime();
4071 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004072
4073 if (workSource != null) {
4074 for (int i = 0; i < workSource.size(); ++i) {
4075 uid = mapUid(workSource.get(i));
4076 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4077 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4078 }
4079 }
4080
4081 List<WorkChain> workChains = workSource.getWorkChains();
4082 if (workChains != null) {
4083 for (int i = 0; i < workChains.size(); ++i) {
4084 uid = mapUid(workChains.get(i).getAttributionUid());
4085 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4086 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4087 }
4088 }
4089 }
4090 } else {
4091 uid = mapUid(uid);
4092
4093 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4094 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4095 }
4096 }
4097 }
4098
4099 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4100 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004101 if (workSource != null) {
4102 for (int i = 0; i < workSource.size(); ++i) {
4103 uid = workSource.get(i);
4104 final String workSourceName = workSource.getName(i);
4105
Tej Singh6f724c42018-01-03 20:02:03 -08004106 if (isOnBattery()) {
4107 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4108 workSourceName != null ? workSourceName : packageName);
4109 pkg.noteWakeupAlarmLocked(tag);
4110 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004111 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4112 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004113 }
4114
4115 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4116 if (workChains != null) {
4117 for (int i = 0; i < workChains.size(); ++i) {
4118 final WorkChain wc = workChains.get(i);
4119 uid = wc.getAttributionUid();
4120
Tej Singh6f724c42018-01-03 20:02:03 -08004121 if (isOnBattery()) {
4122 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4123 pkg.noteWakeupAlarmLocked(tag);
4124 }
Yangster-macafad8c62018-01-05 22:30:49 -08004125 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004126 }
4127 }
4128 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004129 if (isOnBattery()) {
4130 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4131 pkg.noteWakeupAlarmLocked(tag);
4132 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004133 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004134 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004135 }
4136
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004137 private void requestWakelockCpuUpdate() {
4138 if (!mHandler.hasMessages(MSG_UPDATE_WAKELOCKS)) {
4139 Message m = mHandler.obtainMessage(MSG_UPDATE_WAKELOCKS);
4140 mHandler.sendMessageDelayed(m, DELAY_UPDATE_WAKELOCKS);
4141 }
4142 }
4143
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004144 private void requestImmediateCpuUpdate() {
4145 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
4146 mHandler.sendEmptyMessage(MSG_UPDATE_WAKELOCKS);
4147 }
4148
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004149 public void setRecordAllHistoryLocked(boolean enabled) {
4150 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004151 if (!enabled) {
4152 // Clear out any existing state.
4153 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004154 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004155 // Record the currently running processes as stopping, now that we are no
4156 // longer tracking them.
4157 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4158 HistoryItem.EVENT_PROC);
4159 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004160 long mSecRealtime = mClocks.elapsedRealtime();
4161 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004162 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4163 SparseIntArray uids = ent.getValue();
4164 for (int j=0; j<uids.size(); j++) {
4165 addHistoryEventLocked(mSecRealtime, mSecUptime,
4166 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4167 }
4168 }
4169 }
4170 } else {
4171 // Record the currently running processes as starting, now that we are tracking them.
4172 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4173 HistoryItem.EVENT_PROC);
4174 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004175 long mSecRealtime = mClocks.elapsedRealtime();
4176 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004177 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4178 SparseIntArray uids = ent.getValue();
4179 for (int j=0; j<uids.size(); j++) {
4180 addHistoryEventLocked(mSecRealtime, mSecUptime,
4181 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4182 }
4183 }
4184 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004185 }
4186 }
4187
Dianne Hackborn9a755432014-05-15 17:05:22 -07004188 public void setNoAutoReset(boolean enabled) {
4189 mNoAutoReset = enabled;
4190 }
4191
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004192 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004193 if (mPretendScreenOff != pretendScreenOff) {
4194 mPretendScreenOff = pretendScreenOff;
4195 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4196 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004197 }
4198
Dianne Hackborn9a755432014-05-15 17:05:22 -07004199 private String mInitialAcquireWakeName;
4200 private int mInitialAcquireWakeUid = -1;
4201
Narayan Kamath81822022017-12-08 11:56:01 +00004202 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4203 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004204 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004205 if (type == WAKE_TYPE_PARTIAL) {
4206 // Only care about partial wake locks, since full wake locks
4207 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004208 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004209 if (historyName == null) {
4210 historyName = name;
4211 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004212 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004213 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4214 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004215 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004216 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004217 }
4218 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004219 if (mWakeLockNesting == 0) {
4220 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4221 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4222 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004223 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004224 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004225 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004226 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004227 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004228 } else if (!mWakeLockImportant && !unimportantForLogging
4229 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004230 if (mHistoryLastWritten.wakelockTag != null) {
4231 // We'll try to update the last tag.
4232 mHistoryLastWritten.wakelockTag = null;
4233 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004234 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004235 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004236 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004237 }
4238 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004239 }
4240 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004241 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004242 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004243 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4244 // We only update the cpu time when a wake lock is acquired if the screen is off.
4245 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4246 if (DEBUG_ENERGY_CPU) {
4247 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4248 }
4249 requestWakelockCpuUpdate();
4250 }
Narayan Kamath81822022017-12-08 11:56:01 +00004251
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004252 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004253
Yangster-mac20877162017-12-22 17:19:39 -08004254 if (wc != null) {
4255 StatsLog.write(
4256 StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(), type, name, 1);
Yangster-macafad8c62018-01-05 22:30:49 -08004257 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004258 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null, type, name,
4259 1);
Narayan Kamath81822022017-12-08 11:56:01 +00004260 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004261 }
4262 }
4263
Narayan Kamath81822022017-12-08 11:56:01 +00004264 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4265 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004266 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004267 if (type == WAKE_TYPE_PARTIAL) {
4268 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004269 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004270 if (historyName == null) {
4271 historyName = name;
4272 }
4273 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4274 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004275 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004276 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004277 }
4278 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004279 if (mWakeLockNesting == 0) {
4280 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4281 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4282 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004283 mInitialAcquireWakeName = null;
4284 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004285 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004286 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004287 }
4288 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004289 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4290 if (DEBUG_ENERGY_CPU) {
4291 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4292 }
4293 requestWakelockCpuUpdate();
4294 }
Narayan Kamath81822022017-12-08 11:56:01 +00004295
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004296 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004297 if (wc != null) {
4298 StatsLog.write(
4299 StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(), type, name, 0);
Yangster-macafad8c62018-01-05 22:30:49 -08004300 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004301 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null, type, name,
4302 0);
Narayan Kamath81822022017-12-08 11:56:01 +00004303 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004304 }
4305 }
4306
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004307 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4308 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004309 final long elapsedRealtime = mClocks.elapsedRealtime();
4310 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004311 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004312 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004313 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4314 unimportantForLogging, elapsedRealtime, uptime);
4315 }
4316
4317 List<WorkChain> wcs = ws.getWorkChains();
4318 if (wcs != null) {
4319 for (int i = 0; i < wcs.size(); ++i) {
4320 final WorkChain wc = wcs.get(i);
4321 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4322 unimportantForLogging, elapsedRealtime, uptime);
4323 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004324 }
4325 }
4326
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004327 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4328 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004329 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004330 final long elapsedRealtime = mClocks.elapsedRealtime();
4331 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004332
4333 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4334
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004335 // For correct semantics, we start the need worksources first, so that we won't
4336 // make inappropriate history items as if all wake locks went away and new ones
4337 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004338 //
4339 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004340 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004341 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004342 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004343 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004344 }
Narayan Kamath81822022017-12-08 11:56:01 +00004345 if (wcs != null) {
4346 List<WorkChain> newChains = wcs[0];
4347 if (newChains != null) {
4348 for (int i = 0; i < newChains.size(); ++i) {
4349 final WorkChain newChain = newChains.get(i);
4350 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4351 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4352 uptime);
4353 }
4354 }
4355 }
4356
4357 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004358 final int NO = ws.size();
4359 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004360 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4361 uptime);
4362 }
4363 if (wcs != null) {
4364 List<WorkChain> goneChains = wcs[1];
4365 if (goneChains != null) {
4366 for (int i = 0; i < goneChains.size(); ++i) {
4367 final WorkChain goneChain = goneChains.get(i);
4368 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4369 historyName, type, elapsedRealtime, uptime);
4370 }
4371 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004372 }
4373 }
4374
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004375 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4376 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004377 final long elapsedRealtime = mClocks.elapsedRealtime();
4378 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004379 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004380 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004381 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4382 uptime);
4383 }
4384
4385 List<WorkChain> wcs = ws.getWorkChains();
4386 if (wcs != null) {
4387 for (int i = 0; i < wcs.size(); ++i) {
4388 final WorkChain wc = wcs.get(i);
4389 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4390 elapsedRealtime, uptime);
4391 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004392 }
4393 }
4394
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004395 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004396 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4397 uid, null, name, historyName, 1);
Yangster-macafad8c62018-01-05 22:30:49 -08004398
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004399 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004400 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004401 }
4402
4403 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4404 WorkSource workSource) {
4405 final int N = workSource.size();
4406 for (int i = 0; i < N; ++i) {
4407 final int uid = mapUid(workSource.get(i));
4408 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004409 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4410 workSource.get(i), workSource.getName(i), name, historyName, 1);
Narayan Kamath96a92562018-01-02 18:57:17 +00004411 }
4412
4413 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4414 if (workChains != null) {
4415 for (int i = 0; i < workChains.size(); ++i) {
4416 final WorkChain workChain = workChains.get(i);
4417 final int uid = workChain.getAttributionUid();
4418 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4419
Yangster-macafad8c62018-01-05 22:30:49 -08004420 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4421 workChain.getUids(), workChain.getTags(), name, historyName, 1);
Narayan Kamath96a92562018-01-02 18:57:17 +00004422 }
4423 }
4424 }
4425
4426 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004427 final long elapsedRealtime = mClocks.elapsedRealtime();
4428 final long uptime = mClocks.uptimeMillis();
4429 if (historyName == null) {
4430 historyName = name;
4431 }
4432 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4433 0)) {
4434 return;
4435 }
4436 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4437 historyName, uid);
4438 }
4439
4440 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004441 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4442 uid, null, name, historyName, 0);
Yangster-macafad8c62018-01-05 22:30:49 -08004443
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004444 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004445 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004446 }
4447
4448 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4449 WorkSource workSource) {
4450 final int N = workSource.size();
4451 for (int i = 0; i < N; ++i) {
4452 final int uid = mapUid(workSource.get(i));
4453 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004454 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4455 workSource.get(i), workSource.getName(i), name, historyName, 0);
Narayan Kamath96a92562018-01-02 18:57:17 +00004456 }
4457
4458 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4459 if (workChains != null) {
4460 for (int i = 0; i < workChains.size(); ++i) {
4461 final WorkChain workChain = workChains.get(i);
4462 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004463 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004464 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4465 workChain.getUids(), workChain.getTags(), name, historyName, 0);
Narayan Kamath96a92562018-01-02 18:57:17 +00004466 }
4467 }
4468 }
4469
4470 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004471 final long elapsedRealtime = mClocks.elapsedRealtime();
4472 final long uptime = mClocks.uptimeMillis();
4473 if (historyName == null) {
4474 historyName = name;
4475 }
4476 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4477 0)) {
4478 return;
4479 }
4480 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4481 historyName, uid);
4482 }
4483
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004484 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4485 if (mLastWakeupReason != null) {
4486 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004487 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004488 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz8c6571b2017-10-24 15:04:41 -07004489 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason, deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004490 mLastWakeupReason = null;
4491 }
4492 }
4493
4494 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004495 final long elapsedRealtime = mClocks.elapsedRealtime();
4496 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004497 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004498 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004499 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004500 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4501 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004502 mHistoryCur.wakeReasonTag.uid = 0;
4503 mLastWakeupReason = reason;
4504 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004505 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004506 }
4507
Adam Lesinski72478f02015-06-17 15:39:43 -07004508 public boolean startAddingCpuLocked() {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004509 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
Adam Lesinski72478f02015-06-17 15:39:43 -07004510 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004511 }
4512
Adam Lesinski72478f02015-06-17 15:39:43 -07004513 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4514 int statSystemTime, int statIOWaitTime, int statIrqTime,
4515 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004516 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4517 + " user=" + statUserTime + " sys=" + statSystemTime
4518 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4519 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4520 mCurStepCpuUserTime += totalUTime;
4521 mCurStepCpuSystemTime += totalSTime;
4522 mCurStepStatUserTime += statUserTime;
4523 mCurStepStatSystemTime += statSystemTime;
4524 mCurStepStatIOWaitTime += statIOWaitTime;
4525 mCurStepStatIrqTime += statIrqTime;
4526 mCurStepStatSoftIrqTime += statSoftIrqTime;
4527 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004528 }
4529
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004530 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004531 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004532 Uid u = mUidStats.get(uid);
4533 if (u != null) {
4534 u.mPids.remove(pid);
4535 }
4536 }
4537
4538 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004539 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004540 Uid u = mUidStats.get(uid);
4541 if (u != null) {
4542 Uid.Pid p = u.mPids.get(pid);
4543 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004544 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004545 }
4546 }
4547 return 0;
4548 }
4549
Dianne Hackborn287952c2010-09-22 22:34:31 -07004550 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004551 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004552 Uid u = mUidStats.get(uid);
4553 if (u != null) {
4554 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4555 }
4556 }
4557
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004558 int mSensorNesting;
4559
4560 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004561 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004562 final long elapsedRealtime = mClocks.elapsedRealtime();
4563 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004564 if (mSensorNesting == 0) {
4565 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4566 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4567 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004568 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004569 }
4570 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004571 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004572 }
4573
4574 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004575 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004576 final long elapsedRealtime = mClocks.elapsedRealtime();
4577 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004578 mSensorNesting--;
4579 if (mSensorNesting == 0) {
4580 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4581 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4582 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004583 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004584 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004585 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004586 }
4587
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004588 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004589
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004590 public void noteStartGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004591 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004592 final long elapsedRealtime = mClocks.elapsedRealtime();
4593 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004594 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004595 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004596 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4597 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004598 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004599 }
4600 mGpsNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004601 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004603
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004604 public void noteStopGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004605 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004606 final long elapsedRealtime = mClocks.elapsedRealtime();
4607 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004608 mGpsNesting--;
4609 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004610 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004611 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4612 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004613 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004614 stopAllGpsSignalQualityTimersLocked(-1);
4615 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004616 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004617 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004618 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004619
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004620 public void noteGpsSignalQualityLocked(int signalLevel) {
4621 if (mGpsNesting == 0) {
4622 return;
4623 }
4624 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4625 stopAllGpsSignalQualityTimersLocked(-1);
4626 return;
4627 }
4628 final long elapsedRealtime = mClocks.elapsedRealtime();
4629 final long uptime = mClocks.uptimeMillis();
4630 if (mGpsSignalQualityBin != signalLevel) {
4631 if (mGpsSignalQualityBin >= 0) {
4632 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4633 }
4634 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4635 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4636 }
4637 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4638 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4639 addHistoryRecordLocked(elapsedRealtime, uptime);
4640 mGpsSignalQualityBin = signalLevel;
4641 }
4642 return;
4643 }
4644
Jeff Browne95c3cd2014-05-02 16:59:26 -07004645 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004646 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004647
4648 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4649 // original 4 are mapped to one of the originals.
4650 if (state > MAX_TRACKED_SCREEN_STATE) {
4651 switch (state) {
4652 case Display.STATE_VR:
4653 state = Display.STATE_ON;
4654 break;
4655 default:
4656 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4657 break;
4658 }
4659 }
4660
Jeff Browne95c3cd2014-05-02 16:59:26 -07004661 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004662 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004663 final int oldState = mScreenState;
4664 mScreenState = state;
4665 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4666 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004667
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004668 if (state != Display.STATE_UNKNOWN) {
4669 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004670 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4671 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4672 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004673 } else {
4674 Slog.wtf(TAG, "Unexpected screen state: " + state);
4675 }
4676 }
4677
Mike Mac2f518a2017-09-19 16:06:03 -07004678 final long elapsedRealtime = mClocks.elapsedRealtime();
4679 final long uptime = mClocks.uptimeMillis();
4680
4681 boolean updateHistory = false;
4682 if (isScreenDoze(state)) {
4683 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4684 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4685 updateHistory = true;
4686 } else if (isScreenDoze(oldState)) {
4687 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4688 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4689 updateHistory = true;
4690 }
4691 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004692 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4693 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4694 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004695 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4696 if (mScreenBrightnessBin >= 0) {
4697 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4698 }
Mike Mac2f518a2017-09-19 16:06:03 -07004699 updateHistory = true;
4700 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004701 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4702 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4703 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004704 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4705 if (mScreenBrightnessBin >= 0) {
4706 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4707 }
Mike Mac2f518a2017-09-19 16:06:03 -07004708 updateHistory = true;
4709 }
4710 if (updateHistory) {
4711 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4712 + Display.stateToString(state));
4713 addHistoryRecordLocked(elapsedRealtime, uptime);
4714 }
4715 if (isScreenOn(state)) {
4716 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4717 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4718 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004719 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004720 elapsedRealtime, uptime);
4721 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004722 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004723 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004724 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004725 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004726 }
4727 // Update discharge amounts.
4728 if (mOnBatteryInternal) {
4729 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004730 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004731 }
4732 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004733
Dianne Hackborn617f8772009-03-31 15:04:46 -07004734 public void noteScreenBrightnessLocked(int brightness) {
4735 // Bin the brightness.
4736 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4737 if (bin < 0) bin = 0;
4738 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4739 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004740 final long elapsedRealtime = mClocks.elapsedRealtime();
4741 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004742 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4743 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004744 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4745 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004746 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004747 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004748 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004749 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004750 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004751 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004752 }
4753 mScreenBrightnessBin = bin;
4754 }
4755 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004756
Dianne Hackborn617f8772009-03-31 15:04:46 -07004757 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004758 if (mOnBatteryInternal) {
4759 uid = mapUid(uid);
4760 getUidStatsLocked(uid).noteUserActivityLocked(event);
4761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004762 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004763
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004764 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004765 final long elapsedRealtime = mClocks.elapsedRealtime();
4766 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004767 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4768 reason, reasonUid);
4769 }
4770
Jeff Browne95c3cd2014-05-02 16:59:26 -07004771 public void noteInteractiveLocked(boolean interactive) {
4772 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08004773 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004774 mInteractive = interactive;
4775 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
4776 if (interactive) {
4777 mInteractiveTimer.startRunningLocked(elapsedRealtime);
4778 } else {
4779 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
4780 }
4781 }
4782 }
4783
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004784 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004785 final long elapsedRealtime = mClocks.elapsedRealtime();
4786 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004787 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4788 extra, type);
4789 mNumConnectivityChange++;
4790 }
4791
Adam Lesinski5f056f62016-07-14 16:56:08 -07004792 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4793 final long uptimeMillis, int uid) {
4794 uid = mapUid(uid);
4795 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4796 uid);
4797 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4798 }
4799
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004800 /**
4801 * Updates the radio power state and returns true if an external stats collection should occur.
4802 */
4803 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004804 final long elapsedRealtime = mClocks.elapsedRealtime();
4805 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004806 if (mMobileRadioPowerState != powerState) {
4807 long realElapsedRealtimeMs;
4808 final boolean active =
4809 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4810 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4811 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004812 if (uid > 0) {
4813 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4814 }
4815
Adam Lesinski9acfd812016-04-19 18:29:50 -07004816 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004817 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4818 } else {
4819 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004820 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004821 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4822 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4823 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004824 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004825 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4826 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4827 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004828 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004829 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4830 }
4831 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4832 + Integer.toHexString(mHistoryCur.states));
4833 addHistoryRecordLocked(elapsedRealtime, uptime);
4834 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08004835 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004836 if (active) {
4837 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4838 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4839 } else {
4840 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004841 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004842 // Tell the caller to collect radio network/power stats.
4843 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004844 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004845 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004846 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004847 }
4848
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004849 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004850 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004851 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4852 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4853 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004854 final long elapsedRealtime = mClocks.elapsedRealtime();
4855 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004856 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004857 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004858 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4859 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004860 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004861 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004862 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004863 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4864 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004865 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004866 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004867 }
4868 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatzc1a050a2017-10-10 15:49:28 -07004869 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ? 1 : 0);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004870 }
4871 }
4872
Bookatzddccf0a2017-11-28 16:48:14 -08004873 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004874 final long elapsedRealtime = mClocks.elapsedRealtime();
4875 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004876 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004877 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004878 // We don't go out of general idling mode until explicitly taken out of
4879 // device idle through going active or significant motion.
4880 nowIdling = true;
4881 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004882 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
4883 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
4884 // We don't go out of general light idling mode until explicitly taken out of
4885 // device idle through going active or significant motion.
4886 nowLightIdling = true;
4887 }
4888 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
4889 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
4890 activeReason, activeUid);
4891 }
Bookatzddccf0a2017-11-28 16:48:14 -08004892 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
4893 int statsmode;
4894 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
4895 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
4896 else statsmode = DEVICE_IDLE_MODE_OFF;
4897 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
4898 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004899 if (mDeviceIdling != nowIdling) {
4900 mDeviceIdling = nowIdling;
4901 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
4902 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
4903 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004904 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004905 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
4906 } else {
4907 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
4908 }
4909 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004910 if (mDeviceLightIdling != nowLightIdling) {
4911 mDeviceLightIdling = nowLightIdling;
4912 if (nowLightIdling) {
4913 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004914 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004915 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004916 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004917 }
4918 if (mDeviceIdleMode != mode) {
4919 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
4920 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
4921 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
4922 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004923 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004924 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
4925 mLastIdleTimeStart = elapsedRealtime;
4926 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
4927 if (lastDuration > mLongestLightIdleTime) {
4928 mLongestLightIdleTime = lastDuration;
4929 }
4930 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004931 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004932 if (lastDuration > mLongestFullIdleTime) {
4933 mLongestFullIdleTime = lastDuration;
4934 }
4935 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
4936 }
4937 if (mode == DEVICE_IDLE_MODE_LIGHT) {
4938 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004939 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004940 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
4941 }
4942 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08004943 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004944 }
4945 }
4946
Dianne Hackborn3accca02013-09-20 09:32:11 -07004947 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08004948 final long elapsedRealtime = mClocks.elapsedRealtime();
4949 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07004950 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004951 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07004952 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004953 PackageChange pc = new PackageChange();
4954 pc.mPackageName = pkgName;
4955 pc.mUpdate = true;
4956 pc.mVersionCode = versionCode;
4957 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004958 }
4959
4960 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08004961 final long elapsedRealtime = mClocks.elapsedRealtime();
4962 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004963 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
4964 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004965 PackageChange pc = new PackageChange();
4966 pc.mPackageName = pkgName;
4967 pc.mUpdate = true;
4968 addPackageChange(pc);
4969 }
4970
4971 private void addPackageChange(PackageChange pc) {
4972 if (mDailyPackageChanges == null) {
4973 mDailyPackageChanges = new ArrayList<>();
4974 }
4975 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004976 }
4977
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004978 void stopAllGpsSignalQualityTimersLocked(int except) {
4979 final long elapsedRealtime = mClocks.elapsedRealtime();
4980 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
4981 if (i == except) {
4982 continue;
4983 }
4984 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
4985 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
4986 }
4987 }
4988 }
4989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004990 public void notePhoneOnLocked() {
4991 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004992 final long elapsedRealtime = mClocks.elapsedRealtime();
4993 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004994 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004995 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
4996 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004997 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004999 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 }
5001 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005003 public void notePhoneOffLocked() {
5004 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005005 final long elapsedRealtime = mClocks.elapsedRealtime();
5006 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005007 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005008 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5009 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005010 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005011 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005012 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005013 }
5014 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005015
Dianne Hackborn3251b902014-06-20 14:40:53 -07005016 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005017 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005018 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005019 if (i == except) {
5020 continue;
5021 }
5022 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005023 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005024 }
5025 }
5026 }
5027
Dianne Hackborne4a59512010-12-07 11:08:07 -08005028 private int fixPhoneServiceState(int state, int signalBin) {
5029 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5030 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5031 // to infer that we are scanning from other data.
5032 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005033 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005034 state = ServiceState.STATE_IN_SERVICE;
5035 }
5036 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005037
Dianne Hackborne4a59512010-12-07 11:08:07 -08005038 return state;
5039 }
5040
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005041 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005042 boolean scanning = false;
5043 boolean newHistory = false;
5044
5045 mPhoneServiceStateRaw = state;
5046 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005047 mPhoneSignalStrengthBinRaw = strengthBin;
5048
Joe Onoratoabded112016-02-08 16:49:39 -08005049 final long elapsedRealtime = mClocks.elapsedRealtime();
5050 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005051
5052 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5053 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5054 // to infer that we are scanning from other data.
5055 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005056 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005057 state = ServiceState.STATE_IN_SERVICE;
5058 }
5059 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005060
5061 // If the phone is powered off, stop all timers.
5062 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005063 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005064
Dianne Hackborne4a59512010-12-07 11:08:07 -08005065 // If we are in service, make sure the correct signal string timer is running.
5066 } else if (state == ServiceState.STATE_IN_SERVICE) {
5067 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005068
5069 // If we're out of service, we are in the lowest signal strength
5070 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005071 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005072 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005073 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005074 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005075 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005076 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005077 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5078 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005079 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005080 }
5081 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005082
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005083 if (!scanning) {
5084 // If we are no longer scanning, then stop the scanning timer.
5085 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5086 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5087 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5088 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005089 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005090 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005091 }
5092 }
5093
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005094 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005095 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5096 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005097 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005098 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005099 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005100 mPhoneServiceState = state;
5101 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005102
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005103 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005104 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005105 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005106 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005107 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005108 if (strengthBin >= 0) {
5109 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005110 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005111 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005112 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5113 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005114 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005115 + Integer.toHexString(mHistoryCur.states));
5116 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005117 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005118 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005119 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005120 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005121 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005122 }
5123
5124 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005125 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005126 }
5127 }
5128
5129 /**
5130 * Telephony stack updates the phone state.
5131 * @param state phone state from ServiceState.getState()
5132 */
5133 public void notePhoneStateLocked(int state, int simState) {
5134 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005135 }
5136
Wink Savillee9b06d72009-05-18 21:47:50 -07005137 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005138 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005139 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005140 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005141 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005142
Dianne Hackborn627bba72009-03-24 22:32:56 -07005143 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
5144 int bin = DATA_CONNECTION_NONE;
5145 if (hasData) {
5146 switch (dataType) {
5147 case TelephonyManager.NETWORK_TYPE_EDGE:
5148 bin = DATA_CONNECTION_EDGE;
5149 break;
5150 case TelephonyManager.NETWORK_TYPE_GPRS:
5151 bin = DATA_CONNECTION_GPRS;
5152 break;
5153 case TelephonyManager.NETWORK_TYPE_UMTS:
5154 bin = DATA_CONNECTION_UMTS;
5155 break;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005156 case TelephonyManager.NETWORK_TYPE_CDMA:
5157 bin = DATA_CONNECTION_CDMA;
5158 break;
5159 case TelephonyManager.NETWORK_TYPE_EVDO_0:
5160 bin = DATA_CONNECTION_EVDO_0;
5161 break;
5162 case TelephonyManager.NETWORK_TYPE_EVDO_A:
5163 bin = DATA_CONNECTION_EVDO_A;
5164 break;
5165 case TelephonyManager.NETWORK_TYPE_1xRTT:
5166 bin = DATA_CONNECTION_1xRTT;
5167 break;
5168 case TelephonyManager.NETWORK_TYPE_HSDPA:
5169 bin = DATA_CONNECTION_HSDPA;
5170 break;
5171 case TelephonyManager.NETWORK_TYPE_HSUPA:
5172 bin = DATA_CONNECTION_HSUPA;
5173 break;
5174 case TelephonyManager.NETWORK_TYPE_HSPA:
5175 bin = DATA_CONNECTION_HSPA;
5176 break;
5177 case TelephonyManager.NETWORK_TYPE_IDEN:
5178 bin = DATA_CONNECTION_IDEN;
5179 break;
5180 case TelephonyManager.NETWORK_TYPE_EVDO_B:
5181 bin = DATA_CONNECTION_EVDO_B;
5182 break;
Robert Greenwalt962a9902010-11-02 11:10:25 -07005183 case TelephonyManager.NETWORK_TYPE_LTE:
5184 bin = DATA_CONNECTION_LTE;
5185 break;
5186 case TelephonyManager.NETWORK_TYPE_EHRPD:
5187 bin = DATA_CONNECTION_EHRPD;
5188 break;
Patrick Tjinb71703c2013-11-06 09:27:03 -08005189 case TelephonyManager.NETWORK_TYPE_HSPAP:
5190 bin = DATA_CONNECTION_HSPAP;
5191 break;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005192 default:
5193 bin = DATA_CONNECTION_OTHER;
5194 break;
5195 }
5196 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005197 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005198 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005199 final long elapsedRealtime = mClocks.elapsedRealtime();
5200 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005201 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5202 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005203 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5204 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005205 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005206 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005207 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005208 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005209 }
5210 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005211 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005212 }
5213 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005214
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005215 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005216 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005217 final long elapsedRealtime = mClocks.elapsedRealtime();
5218 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005219 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005220 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5221 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005222 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005223 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005224 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005225 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005226 }
5227 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005228
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005229 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005230 final long elapsedRealtime = mClocks.elapsedRealtime();
5231 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005232 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005233 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005234 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5235 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005236 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005237 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005238 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005239 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005240 }
5241 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005242
5243 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005244 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005245 final long elapsedRealtime = mClocks.elapsedRealtime();
5246 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005247 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005248 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005249 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5250 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005251 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005252 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005253 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005254 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005255 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005256 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005257
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005258 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005259 if (mAudioOnNesting == 0) {
5260 return;
5261 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005262 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005263 final long elapsedRealtime = mClocks.elapsedRealtime();
5264 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005265 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005266 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005267 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5268 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005269 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005270 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005271 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005272 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005273 }
5274
5275 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005276 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005277 final long elapsedRealtime = mClocks.elapsedRealtime();
5278 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005279 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005280 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005281 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5282 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005283 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005284 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005285 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005286 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005287 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005288 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005289
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005290 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005291 if (mVideoOnNesting == 0) {
5292 return;
5293 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005294 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005295 final long elapsedRealtime = mClocks.elapsedRealtime();
5296 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005297 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005298 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005299 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5300 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005301 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005302 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005303 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005304 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005305 }
5306
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005307 public void noteResetAudioLocked() {
5308 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005309 final long elapsedRealtime = mClocks.elapsedRealtime();
5310 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005311 mAudioOnNesting = 0;
5312 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5313 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5314 + Integer.toHexString(mHistoryCur.states));
5315 addHistoryRecordLocked(elapsedRealtime, uptime);
5316 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5317 for (int i=0; i<mUidStats.size(); i++) {
5318 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5319 uid.noteResetAudioLocked(elapsedRealtime);
5320 }
5321 }
5322 }
5323
5324 public void noteResetVideoLocked() {
5325 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005326 final long elapsedRealtime = mClocks.elapsedRealtime();
5327 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005328 mAudioOnNesting = 0;
5329 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5330 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5331 + Integer.toHexString(mHistoryCur.states));
5332 addHistoryRecordLocked(elapsedRealtime, uptime);
5333 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5334 for (int i=0; i<mUidStats.size(); i++) {
5335 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5336 uid.noteResetVideoLocked(elapsedRealtime);
5337 }
5338 }
5339 }
5340
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005341 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005342 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005343 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005344 }
5345
5346 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005347 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005348 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005349 }
5350
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005351 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005352 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005353 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5354 }
5355
5356 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005357 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005358 getUidStatsLocked(uid).noteVibratorOffLocked();
5359 }
5360
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005361 public void noteFlashlightOnLocked(int uid) {
5362 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005363 final long elapsedRealtime = mClocks.elapsedRealtime();
5364 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005365 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005366 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5367 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005368 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005369 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005370 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5371 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005372 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5373 }
5374
5375 public void noteFlashlightOffLocked(int uid) {
5376 if (mFlashlightOnNesting == 0) {
5377 return;
5378 }
5379 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005380 final long elapsedRealtime = mClocks.elapsedRealtime();
5381 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005382 if (--mFlashlightOnNesting == 0) {
5383 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5384 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5385 + Integer.toHexString(mHistoryCur.states2));
5386 addHistoryRecordLocked(elapsedRealtime, uptime);
5387 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5388 }
5389 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5390 }
5391
5392 public void noteCameraOnLocked(int uid) {
5393 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005394 final long elapsedRealtime = mClocks.elapsedRealtime();
5395 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005396 if (mCameraOnNesting++ == 0) {
5397 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5398 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5399 + Integer.toHexString(mHistoryCur.states2));
5400 addHistoryRecordLocked(elapsedRealtime, uptime);
5401 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5402 }
5403 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5404 }
5405
5406 public void noteCameraOffLocked(int uid) {
5407 if (mCameraOnNesting == 0) {
5408 return;
5409 }
5410 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005411 final long elapsedRealtime = mClocks.elapsedRealtime();
5412 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005413 if (--mCameraOnNesting == 0) {
5414 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5415 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5416 + Integer.toHexString(mHistoryCur.states2));
5417 addHistoryRecordLocked(elapsedRealtime, uptime);
5418 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5419 }
5420 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5421 }
5422
5423 public void noteResetCameraLocked() {
5424 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005425 final long elapsedRealtime = mClocks.elapsedRealtime();
5426 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005427 mCameraOnNesting = 0;
5428 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5429 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5430 + Integer.toHexString(mHistoryCur.states2));
5431 addHistoryRecordLocked(elapsedRealtime, uptime);
5432 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5433 for (int i=0; i<mUidStats.size(); i++) {
5434 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5435 uid.noteResetCameraLocked(elapsedRealtime);
5436 }
5437 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005438 }
5439
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005440 public void noteResetFlashlightLocked() {
5441 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005442 final long elapsedRealtime = mClocks.elapsedRealtime();
5443 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005444 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005445 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5446 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005447 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005448 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005449 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5450 for (int i=0; i<mUidStats.size(); i++) {
5451 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5452 uid.noteResetFlashlightLocked(elapsedRealtime);
5453 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005454 }
5455 }
5456
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005457 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5458 boolean isUnoptimized) {
5459 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005460 final long elapsedRealtime = mClocks.elapsedRealtime();
5461 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005462 if (mBluetoothScanNesting == 0) {
5463 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5464 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5465 + Integer.toHexString(mHistoryCur.states2));
5466 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005467 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005468 }
5469 mBluetoothScanNesting++;
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005470
Yangster-macafad8c62018-01-05 22:30:49 -08005471 if (workChain != null) {
5472 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
5473 workChain.getUids(), workChain.getTags(), 1);
5474 if (isUnoptimized) {
5475 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
5476 workChain.getUids(), workChain.getTags(), 1);
5477 }
5478 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005479 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null, 1);
Yangster-macafad8c62018-01-05 22:30:49 -08005480 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005481 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
5482 1);
Yangster-macafad8c62018-01-05 22:30:49 -08005483 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005484 }
5485
Bookatzb1f04f32017-05-19 13:57:32 -07005486 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005487 if (workChain != null) {
5488 getUidStatsLocked(uid).addBluetoothWorkChain(workChain, isUnoptimized);
5489 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005490 }
5491
Bookatzb1f04f32017-05-19 13:57:32 -07005492 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005493 final int N = ws.size();
5494 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005495 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5496 }
5497
5498 final List<WorkChain> workChains = ws.getWorkChains();
5499 if (workChains != null) {
5500 for (int i = 0; i < workChains.size(); ++i) {
5501 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5502 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005503 }
5504 }
5505
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005506 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5507 boolean isUnoptimized) {
5508 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005509 final long elapsedRealtime = mClocks.elapsedRealtime();
5510 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005511 mBluetoothScanNesting--;
5512 if (mBluetoothScanNesting == 0) {
5513 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5514 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5515 + Integer.toHexString(mHistoryCur.states2));
5516 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005517 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005518 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005519
Yangster-macafad8c62018-01-05 22:30:49 -08005520 if (workChain != null) {
5521 StatsLog.write(
5522 StatsLog.BLE_SCAN_STATE_CHANGED, workChain.getUids(), workChain.getTags(), 0);
5523 if (isUnoptimized) {
5524 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
5525 workChain.getUids(), workChain.getTags(), 0);
5526 }
5527 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005528 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null, 0);
Yangster-macafad8c62018-01-05 22:30:49 -08005529 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005530 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
5531 0);
Yangster-macafad8c62018-01-05 22:30:49 -08005532 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005533 }
5534
Bookatz94c5a312017-07-11 16:49:17 -07005535 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005536 if (workChain != null) {
5537 getUidStatsLocked(uid).removeBluetoothWorkChain(workChain, isUnoptimized);
5538 }
5539 }
5540
5541 private int getAttributionUid(int uid, WorkChain workChain) {
5542 if (workChain != null) {
5543 return mapUid(workChain.getAttributionUid());
5544 }
5545
5546 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005547 }
5548
Bookatz94c5a312017-07-11 16:49:17 -07005549 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005550 final int N = ws.size();
5551 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005552 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5553 }
5554
5555 final List<WorkChain> workChains = ws.getWorkChains();
5556 if (workChains != null) {
5557 for (int i = 0; i < workChains.size(); ++i) {
5558 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5559 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005560 }
5561 }
5562
5563 public void noteResetBluetoothScanLocked() {
5564 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005565 final long elapsedRealtime = mClocks.elapsedRealtime();
5566 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005567 mBluetoothScanNesting = 0;
5568 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5569 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5570 + Integer.toHexString(mHistoryCur.states2));
5571 addHistoryRecordLocked(elapsedRealtime, uptime);
5572 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005573
5574
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005575 for (int i=0; i<mUidStats.size(); i++) {
5576 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5577 uid.noteResetBluetoothScanLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005578
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005579 List<WorkChain> allWorkChains = uid.getAllBluetoothWorkChains();
5580 if (allWorkChains != null) {
5581 for (int j = 0; j < allWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005582 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005583 allWorkChains.get(j).getUids(),
5584 allWorkChains.get(j).getTags(), 0);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005585 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005586 allWorkChains.clear();
5587 }
5588
5589 List<WorkChain> unoptimizedWorkChains = uid.getUnoptimizedBluetoothWorkChains();
5590 if (unoptimizedWorkChains != null) {
5591 for (int j = 0; j < unoptimizedWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005592 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005593 unoptimizedWorkChains.get(j).getUids(),
5594 unoptimizedWorkChains.get(j).getTags(), 0);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005595 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005596 unoptimizedWorkChains.clear();
5597 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005598 }
5599 }
5600 }
5601
Bookatz4ebc0642017-05-11 12:21:19 -07005602 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005603 final int N = ws.size();
5604 for (int i = 0; i < N; i++) {
5605 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005606 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005607 StatsLog.write_non_chained(StatsLog.BLE_SCAN_RESULT_RECEIVED, ws.get(i), ws.getName(i),
5608 numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005609 }
5610
5611 final List<WorkChain> workChains = ws.getWorkChains();
5612 if (workChains != null) {
5613 for (int i = 0; i < workChains.size(); ++i) {
5614 final WorkChain wc = workChains.get(i);
5615 int uid = mapUid(wc.getAttributionUid());
5616 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-macafad8c62018-01-05 22:30:49 -08005617 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED,
5618 wc.getUids(), wc.getTags(), numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005619 }
Bookatz956f36bf2017-04-28 09:48:17 -07005620 }
5621 }
5622
Adam Lesinski5f056f62016-07-14 16:56:08 -07005623 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5624 final long uptimeMillis, int uid) {
5625 uid = mapUid(uid);
5626 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5627 uid);
5628 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5629 }
5630
5631 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005632 final long elapsedRealtime = mClocks.elapsedRealtime();
5633 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005634 if (mWifiRadioPowerState != powerState) {
5635 final boolean active =
5636 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5637 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5638 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005639 if (uid > 0) {
5640 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5641 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005642 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005643 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005644 } else {
5645 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005646 mWifiActiveTimer.stopRunningLocked(
5647 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005648 }
5649 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5650 + Integer.toHexString(mHistoryCur.states));
5651 addHistoryRecordLocked(elapsedRealtime, uptime);
5652 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005653 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005654 }
5655 }
5656
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005657 public void noteWifiRunningLocked(WorkSource ws) {
5658 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005659 final long elapsedRealtime = mClocks.elapsedRealtime();
5660 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005661 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005662 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5663 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005664 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005665 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005666 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005667 int N = ws.size();
5668 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005669 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005670 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005671 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005672
5673 List<WorkChain> workChains = ws.getWorkChains();
5674 if (workChains != null) {
5675 for (int i = 0; i < workChains.size(); ++i) {
5676 int uid = mapUid(workChains.get(i).getAttributionUid());
5677 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5678 }
5679 }
5680
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005681 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005682 } else {
5683 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005684 }
5685 }
5686
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005687 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5688 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005689 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005690 int N = oldWs.size();
5691 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005692 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005693 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005694 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005695
5696 List<WorkChain> workChains = oldWs.getWorkChains();
5697 if (workChains != null) {
5698 for (int i = 0; i < workChains.size(); ++i) {
5699 int uid = mapUid(workChains.get(i).getAttributionUid());
5700 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5701 }
5702 }
5703
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005704 N = newWs.size();
5705 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005706 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005707 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005708 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005709
5710 workChains = newWs.getWorkChains();
5711 if (workChains != null) {
5712 for (int i = 0; i < workChains.size(); ++i) {
5713 int uid = mapUid(workChains.get(i).getAttributionUid());
5714 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5715 }
5716 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005717 } else {
5718 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5719 }
5720 }
5721
5722 public void noteWifiStoppedLocked(WorkSource ws) {
5723 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005724 final long elapsedRealtime = mClocks.elapsedRealtime();
5725 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005726 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005727 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5728 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005729 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005730 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005731 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005732 int N = ws.size();
5733 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005734 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005735 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005736 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005737
5738 List<WorkChain> workChains = ws.getWorkChains();
5739 if (workChains != null) {
5740 for (int i = 0; i < workChains.size(); ++i) {
5741 int uid = mapUid(workChains.get(i).getAttributionUid());
5742 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5743 }
5744 }
5745
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005746 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005747 } else {
5748 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005749 }
5750 }
5751
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005752 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5753 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5754 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005755 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005756 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005757 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005758 }
5759 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005760 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005761 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005762 }
5763 }
5764
Dianne Hackborn3251b902014-06-20 14:40:53 -07005765 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5766 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5767 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005768 final long elapsedRealtime = mClocks.elapsedRealtime();
5769 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005770 if (mWifiSupplState >= 0) {
5771 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5772 }
5773 mWifiSupplState = supplState;
5774 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5775 mHistoryCur.states2 =
5776 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5777 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5778 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5779 + Integer.toHexString(mHistoryCur.states2));
5780 addHistoryRecordLocked(elapsedRealtime, uptime);
5781 }
5782 }
5783
5784 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005785 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005786 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5787 if (i == except) {
5788 continue;
5789 }
5790 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5791 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5792 }
5793 }
5794 }
5795
5796 public void noteWifiRssiChangedLocked(int newRssi) {
5797 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5798 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5799 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005800 final long elapsedRealtime = mClocks.elapsedRealtime();
5801 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005802 if (mWifiSignalStrengthBin >= 0) {
5803 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5804 elapsedRealtime);
5805 }
5806 if (strengthBin >= 0) {
5807 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5808 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Bookatze5885242017-10-24 20:10:31 -07005809 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07005810 }
5811 mHistoryCur.states2 =
5812 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5813 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5814 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5815 + Integer.toHexString(mHistoryCur.states2));
5816 addHistoryRecordLocked(elapsedRealtime, uptime);
5817 } else {
5818 stopAllWifiSignalStrengthTimersLocked(-1);
5819 }
5820 mWifiSignalStrengthBin = strengthBin;
5821 }
5822 }
5823
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005824 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005825
The Android Open Source Project10592532009-03-18 17:39:46 -07005826 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005827 final long elapsedRealtime = mClocks.elapsedRealtime();
5828 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005829 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005830 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005831 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5832 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005833 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005834 }
5835 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005836 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005837 }
5838
5839 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005840 final long elapsedRealtime = mClocks.elapsedRealtime();
5841 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005842 mWifiFullLockNesting--;
5843 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005844 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005845 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
5846 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005847 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005848 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005849 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005850 }
5851
Nick Pelly6ccaa542012-06-15 15:22:47 -07005852 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005853
Nick Pelly6ccaa542012-06-15 15:22:47 -07005854 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005855 final long elapsedRealtime = mClocks.elapsedRealtime();
5856 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005857 if (mWifiScanNesting == 0) {
5858 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
5859 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005860 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005861 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005862 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07005863 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005864 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005865 }
5866
Nick Pelly6ccaa542012-06-15 15:22:47 -07005867 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005868 final long elapsedRealtime = mClocks.elapsedRealtime();
5869 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005870 mWifiScanNesting--;
5871 if (mWifiScanNesting == 0) {
5872 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
5873 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005874 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005875 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005876 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005877 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005878 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005879
Robert Greenwalta029ea12013-09-25 16:38:12 -07005880 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005881 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005882 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005883 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005884 }
5885
5886 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005887 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005888 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005889 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005890 }
5891
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005892 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005893
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005894 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005895 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005896 final long elapsedRealtime = mClocks.elapsedRealtime();
5897 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005898 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005899 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005900 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
5901 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005902 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08005903
5904 // Start Wifi Multicast overall timer
5905 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
5906 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
5907 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
5908 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005909 }
5910 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005911 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005912 }
5913
5914 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005915 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005916 final long elapsedRealtime = mClocks.elapsedRealtime();
5917 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005918 mWifiMulticastNesting--;
5919 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005920 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005921 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
5922 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005923 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08005924
5925 // Stop Wifi Multicast overall timer
5926 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
5927 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
5928 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
5929 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005930 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005931 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005932 }
5933
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005934 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
5935 int N = ws.size();
5936 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005937 final int uid = mapUid(ws.get(i));
5938 noteFullWifiLockAcquiredLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005939 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i), 1);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005940 }
5941
5942 final List<WorkChain> workChains = ws.getWorkChains();
5943 if (workChains != null) {
5944 for (int i = 0; i < workChains.size(); ++i) {
5945 final WorkChain workChain = workChains.get(i);
5946 final int uid = mapUid(workChain.getAttributionUid());
5947 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08005948 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
5949 workChain.getUids(), workChain.getTags(), 1);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005950 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005951 }
5952 }
5953
5954 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
5955 int N = ws.size();
5956 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005957 final int uid = mapUid(ws.get(i));
5958 noteFullWifiLockReleasedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005959 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i), 0);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005960 }
5961
5962 final List<WorkChain> workChains = ws.getWorkChains();
5963 if (workChains != null) {
5964 for (int i = 0; i < workChains.size(); ++i) {
5965 final WorkChain workChain = workChains.get(i);
5966 final int uid = mapUid(workChain.getAttributionUid());
5967 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08005968 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
5969 workChain.getUids(), workChain.getTags(), 0);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005970 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005971 }
5972 }
5973
Nick Pelly6ccaa542012-06-15 15:22:47 -07005974 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005975 int N = ws.size();
5976 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005977 final int uid = mapUid(ws.get(i));
5978 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005979 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
5980 1);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005981 }
5982
5983 final List<WorkChain> workChains = ws.getWorkChains();
5984 if (workChains != null) {
5985 for (int i = 0; i < workChains.size(); ++i) {
5986 final WorkChain workChain = workChains.get(i);
5987 final int uid = mapUid(workChain.getAttributionUid());
5988 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08005989 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
5990 workChain.getTags(), 1);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005991 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005992 }
5993 }
5994
Nick Pelly6ccaa542012-06-15 15:22:47 -07005995 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005996 int N = ws.size();
5997 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005998 final int uid = mapUid(ws.get(i));
5999 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006000 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
6001 0);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006002 }
6003
6004 final List<WorkChain> workChains = ws.getWorkChains();
6005 if (workChains != null) {
6006 for (int i = 0; i < workChains.size(); ++i) {
6007 final WorkChain workChain = workChains.get(i);
6008 final int uid = mapUid(workChain.getAttributionUid());
6009 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006010 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
6011 workChain.getUids(), workChain.getTags(), 0);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006012 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006013 }
6014 }
6015
Robert Greenwalta029ea12013-09-25 16:38:12 -07006016 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6017 int N = ws.size();
6018 for (int i=0; i<N; i++) {
6019 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6020 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006021
6022 final List<WorkChain> workChains = ws.getWorkChains();
6023 if (workChains != null) {
6024 for (int i = 0; i < workChains.size(); ++i) {
6025 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6026 }
6027 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006028 }
6029
6030 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6031 int N = ws.size();
6032 for (int i=0; i<N; i++) {
6033 noteWifiBatchedScanStoppedLocked(ws.get(i));
6034 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006035
6036 final List<WorkChain> workChains = ws.getWorkChains();
6037 if (workChains != null) {
6038 for (int i = 0; i < workChains.size(); ++i) {
6039 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6040 }
6041 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006042 }
6043
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006044 private static String[] includeInStringArray(String[] array, String str) {
6045 if (ArrayUtils.indexOf(array, str) >= 0) {
6046 return array;
6047 }
6048 String[] newArray = new String[array.length+1];
6049 System.arraycopy(array, 0, newArray, 0, array.length);
6050 newArray[array.length] = str;
6051 return newArray;
6052 }
6053
6054 private static String[] excludeFromStringArray(String[] array, String str) {
6055 int index = ArrayUtils.indexOf(array, str);
6056 if (index >= 0) {
6057 String[] newArray = new String[array.length-1];
6058 if (index > 0) {
6059 System.arraycopy(array, 0, newArray, 0, index);
6060 }
6061 if (index < array.length-1) {
6062 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6063 }
6064 return newArray;
6065 }
6066 return array;
6067 }
6068
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006069 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006070 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006071
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006072 synchronized (mModemNetworkLock) {
6073 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6074 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6075 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6076 } else {
6077 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6078 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6079 }
6080 }
6081
6082 synchronized (mWifiNetworkLock) {
6083 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6084 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6085 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6086 } else {
6087 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6088 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6089 }
6090 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006091 }
6092
David Chenc8a43242017-10-17 16:23:28 -07006093 public String[] getWifiIfaces() {
6094 synchronized (mWifiNetworkLock) {
6095 return mWifiIfaces;
6096 }
6097 }
6098
6099 public String[] getMobileIfaces() {
6100 synchronized (mModemNetworkLock) {
6101 return mModemIfaces;
6102 }
6103 }
6104
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006105 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6106 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006108
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006109 @Override public int getScreenOnCount(int which) {
6110 return mScreenOnTimer.getCountLocked(which);
6111 }
6112
Mike Mac2f518a2017-09-19 16:06:03 -07006113 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6114 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6115 }
6116
6117 @Override public int getScreenDozeCount(int which) {
6118 return mScreenDozeTimer.getCountLocked(which);
6119 }
6120
Dianne Hackborn617f8772009-03-31 15:04:46 -07006121 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006122 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006123 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006124 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006125 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006126
Kweku Adams87b19ec2017-10-09 12:40:03 -07006127 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6128 return mScreenBrightnessTimer[brightnessBin];
6129 }
6130
Jeff Browne95c3cd2014-05-02 16:59:26 -07006131 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6132 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006133 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006134
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006135 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6136 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006137 }
6138
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006139 @Override public int getPowerSaveModeEnabledCount(int which) {
6140 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6141 }
6142
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006143 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6144 int which) {
6145 switch (mode) {
6146 case DEVICE_IDLE_MODE_LIGHT:
6147 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006148 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006149 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6150 }
6151 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006152 }
6153
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006154 @Override public int getDeviceIdleModeCount(int mode, int which) {
6155 switch (mode) {
6156 case DEVICE_IDLE_MODE_LIGHT:
6157 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006158 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006159 return mDeviceIdleModeFullTimer.getCountLocked(which);
6160 }
6161 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006162 }
6163
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006164 @Override public long getLongestDeviceIdleModeTime(int mode) {
6165 switch (mode) {
6166 case DEVICE_IDLE_MODE_LIGHT:
6167 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006168 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006169 return mLongestFullIdleTime;
6170 }
6171 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006172 }
6173
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006174 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6175 switch (mode) {
6176 case DEVICE_IDLE_MODE_LIGHT:
6177 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006178 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006179 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6180 }
6181 return 0;
6182 }
6183
6184 @Override public int getDeviceIdlingCount(int mode, int which) {
6185 switch (mode) {
6186 case DEVICE_IDLE_MODE_LIGHT:
6187 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006188 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006189 return mDeviceIdlingTimer.getCountLocked(which);
6190 }
6191 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006192 }
6193
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006194 @Override public int getNumConnectivityChange(int which) {
6195 int val = mNumConnectivityChange;
6196 if (which == STATS_CURRENT) {
6197 val -= mLoadedNumConnectivityChange;
6198 } else if (which == STATS_SINCE_UNPLUGGED) {
6199 val -= mUnpluggedNumConnectivityChange;
6200 }
6201 return val;
6202 }
6203
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006204 @Override public long getGpsSignalQualityTime(int strengthBin,
6205 long elapsedRealtimeUs, int which) {
6206 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6207 return 0;
6208 }
6209 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6210 elapsedRealtimeUs, which);
6211 }
6212
6213 @Override public long getGpsBatteryDrainMaMs() {
6214 //TODO: Add GPS power computation (b/67213967)
6215 return 0;
6216 }
6217
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006218 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6219 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006221
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006222 @Override public int getPhoneOnCount(int which) {
6223 return mPhoneOnTimer.getCountLocked(which);
6224 }
6225
Dianne Hackborn627bba72009-03-24 22:32:56 -07006226 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006227 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006228 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006229 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006230 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006231
6232 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006233 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006234 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006235 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006236 }
6237
Kweku Adams87b19ec2017-10-09 12:40:03 -07006238 @Override public Timer getPhoneSignalScanningTimer() {
6239 return mPhoneSignalScanningTimer;
6240 }
6241
Catherine Liufb900812012-07-17 14:12:56 -05006242 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6243 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006244 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006245
Kweku Adams87b19ec2017-10-09 12:40:03 -07006246 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6247 return mPhoneSignalStrengthsTimer[strengthBin];
6248 }
6249
Dianne Hackborn627bba72009-03-24 22:32:56 -07006250 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006251 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006252 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006253 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006254 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006255
Dianne Hackborn617f8772009-03-31 15:04:46 -07006256 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006257 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006258 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006259
Kweku Adams87b19ec2017-10-09 12:40:03 -07006260 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6261 return mPhoneDataConnectionsTimer[dataType];
6262 }
6263
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006264 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6265 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006266 }
6267
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006268 @Override public int getMobileRadioActiveCount(int which) {
6269 return mMobileRadioActiveTimer.getCountLocked(which);
6270 }
6271
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006272 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6273 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6274 }
6275
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006276 @Override public long getMobileRadioActiveUnknownTime(int which) {
6277 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6278 }
6279
6280 @Override public int getMobileRadioActiveUnknownCount(int which) {
6281 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6282 }
6283
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006284 @Override public long getWifiMulticastWakelockTime(
6285 long elapsedRealtimeUs, int which) {
6286 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6287 elapsedRealtimeUs, which);
6288 }
6289
6290 @Override public int getWifiMulticastWakelockCount(int which) {
6291 return mWifiMulticastWakelockTimer.getCountLocked(which);
6292 }
6293
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006294 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6295 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006296 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006297
Siddharth Rayb50a6842017-12-14 15:15:28 -08006298 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6299 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6300 }
6301
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006302 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6303 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006304 }
6305
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006306 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006307 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006308 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006309 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006310 }
6311
6312 @Override public int getWifiStateCount(int wifiState, int which) {
6313 return mWifiStateTimer[wifiState].getCountLocked(which);
6314 }
6315
Kweku Adams87b19ec2017-10-09 12:40:03 -07006316 @Override public Timer getWifiStateTimer(int wifiState) {
6317 return mWifiStateTimer[wifiState];
6318 }
6319
Dianne Hackborn3251b902014-06-20 14:40:53 -07006320 @Override public long getWifiSupplStateTime(int state,
6321 long elapsedRealtimeUs, int which) {
6322 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6323 elapsedRealtimeUs, which);
6324 }
6325
6326 @Override public int getWifiSupplStateCount(int state, int which) {
6327 return mWifiSupplStateTimer[state].getCountLocked(which);
6328 }
6329
Kweku Adams87b19ec2017-10-09 12:40:03 -07006330 @Override public Timer getWifiSupplStateTimer(int state) {
6331 return mWifiSupplStateTimer[state];
6332 }
6333
Dianne Hackborn3251b902014-06-20 14:40:53 -07006334 @Override public long getWifiSignalStrengthTime(int strengthBin,
6335 long elapsedRealtimeUs, int which) {
6336 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6337 elapsedRealtimeUs, which);
6338 }
6339
6340 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6341 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6342 }
6343
Kweku Adams87b19ec2017-10-09 12:40:03 -07006344 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6345 return mWifiSignalStrengthsTimer[strengthBin];
6346 }
6347
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006348 @Override
6349 public ControllerActivityCounter getBluetoothControllerActivity() {
6350 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006351 }
6352
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006353 @Override
6354 public ControllerActivityCounter getWifiControllerActivity() {
6355 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006356 }
6357
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006358 @Override
6359 public ControllerActivityCounter getModemControllerActivity() {
6360 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006361 }
6362
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006363 @Override
6364 public boolean hasBluetoothActivityReporting() {
6365 return mHasBluetoothReporting;
6366 }
6367
6368 @Override
6369 public boolean hasWifiActivityReporting() {
6370 return mHasWifiReporting;
6371 }
6372
6373 @Override
6374 public boolean hasModemActivityReporting() {
6375 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006376 }
6377
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006378 @Override
6379 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006380 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6381 }
6382
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006383 @Override
6384 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006385 return mFlashlightOnTimer.getCountLocked(which);
6386 }
6387
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006388 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006389 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6390 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6391 }
6392
6393 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006394 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6395 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6396 }
6397
6398 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006399 public long getNetworkActivityBytes(int type, int which) {
6400 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6401 return mNetworkByteActivityCounters[type].getCountLocked(which);
6402 } else {
6403 return 0;
6404 }
6405 }
6406
6407 @Override
6408 public long getNetworkActivityPackets(int type, int which) {
6409 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6410 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006411 } else {
6412 return 0;
6413 }
6414 }
6415
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006416 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006417 final long currentTime = System.currentTimeMillis();
6418 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006419 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6420 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006421 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006422 return mStartClockTime;
6423 }
6424
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006425 @Override public String getStartPlatformVersion() {
6426 return mStartPlatformVersion;
6427 }
6428
6429 @Override public String getEndPlatformVersion() {
6430 return mEndPlatformVersion;
6431 }
6432
6433 @Override public int getParcelVersion() {
6434 return VERSION;
6435 }
6436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437 @Override public boolean getIsOnBattery() {
6438 return mOnBattery;
6439 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6442 return mUidStats;
6443 }
6444
Adam Lesinski5f056f62016-07-14 16:56:08 -07006445 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6446 if (timer != null) {
6447 timer.detach();
6448 }
6449 }
6450
6451 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6452 boolean detachIfReset) {
6453 if (timer != null) {
6454 return timer.reset(detachIfReset);
6455 }
6456 return true;
6457 }
6458
Bookatz867c0d72017-03-07 18:23:42 -08006459 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6460 if (timer != null) {
6461 return timer.reset(detachIfReset);
6462 }
6463 return true;
6464 }
6465
Adam Lesinski5f056f62016-07-14 16:56:08 -07006466 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6467 if (counter != null) {
6468 counter.detach();
6469 }
6470 }
6471
6472 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6473 boolean detachIfReset) {
6474 if (counter != null) {
6475 counter.reset(detachIfReset);
6476 }
6477 }
6478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 /**
6480 * The statistics associated with a particular uid.
6481 */
Joe Onoratoabded112016-02-08 16:49:39 -08006482 public static class Uid extends BatteryStats.Uid {
6483 /**
6484 * BatteryStatsImpl that we are associated with.
6485 */
6486 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006489
Bookatz867c0d72017-03-07 18:23:42 -08006490 /** TimeBase for when uid is in background and device is on battery. */
6491 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6492 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006493 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6494 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006495
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006496 boolean mWifiRunning;
6497 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006498
The Android Open Source Project10592532009-03-18 17:39:46 -07006499 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006500 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006501
Nick Pelly6ccaa542012-06-15 15:22:47 -07006502 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006503 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006504
Dianne Hackborn61659e52014-07-09 16:13:01 -07006505 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006506 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6507 StopwatchTimer[] mWifiBatchedScanTimer;
6508
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006509 boolean mWifiMulticastEnabled;
6510 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006511
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006512 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006513 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006514 StopwatchTimer mFlashlightTurnedOnTimer;
6515 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006516 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006517 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006518 /** Total time spent by the uid holding any partial wakelocks. */
6519 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006520 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006521 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006522 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006523 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006524
Dianne Hackborna8d10942015-11-19 17:55:19 -08006525 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006526 StopwatchTimer[] mProcessStateTimer;
6527
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006528 boolean mInForegroundService = false;
6529
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006530 BatchTimer mVibratorOnTimer;
6531
Dianne Hackborn617f8772009-03-31 15:04:46 -07006532 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006533
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006534 LongSamplingCounter[] mNetworkByteActivityCounters;
6535 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006536 LongSamplingCounter mMobileRadioActiveTime;
6537 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006540 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6541 */
6542 private LongSamplingCounter mMobileRadioApWakeupCount;
6543
6544 /**
6545 * How many times this UID woke up the Application Processor due to a Wifi packet.
6546 */
6547 private LongSamplingCounter mWifiRadioApWakeupCount;
6548
6549 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006550 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006551 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006552 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006553 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006554
6555 /**
6556 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006557 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006558 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006559 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6560
6561 /**
6562 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6563 * Can be null if the UID has had no such activity.
6564 */
6565 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006566
6567 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006568 * The CPU times we had at the last history details update.
6569 */
6570 long mLastStepUserTime;
6571 long mLastStepSystemTime;
6572 long mCurStepUserTime;
6573 long mCurStepSystemTime;
6574
Joe Onoratoabded112016-02-08 16:49:39 -08006575 LongSamplingCounter mUserCpuTime;
6576 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006577 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006578 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006579
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006580 LongSamplingCounterArray mCpuFreqTimeMs;
6581 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006582 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006583
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006584 LongSamplingCounterArray[] mProcStateTimeMs;
6585 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6586
6587 IntArray mChildUids;
6588
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006589 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 * The statistics we have collected for this uid's wake locks.
6591 */
Joe Onoratoabded112016-02-08 16:49:39 -08006592 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006593
6594 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006595 * The statistics we have collected for this uid's syncs.
6596 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006597 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006598
6599 /**
6600 * The statistics we have collected for this uid's jobs.
6601 */
Bookatzaa4594a2017-03-24 12:39:56 -07006602 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006603
6604 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006605 * Count of the jobs that have completed and the reasons why they completed.
6606 */
6607 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6608
6609 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 * The statistics we have collected for this uid's sensor activations.
6611 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006612 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613
6614 /**
6615 * The statistics we have collected for this uid's processes.
6616 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006617 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618
6619 /**
6620 * The statistics we have collected for this uid's processes.
6621 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006622 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006623
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006624 /**
6625 * The transient wake stats we have collected for this uid's pids.
6626 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006627 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006628
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00006629 /**
6630 * The list of WorkChains associated with active bluetooth scans.
6631 *
6632 * NOTE: This is a hack and it only needs to exist because there's a "reset" API that is
6633 * supposed to stop and log all WorkChains that were currently active.
6634 */
6635 ArrayList<WorkChain> mAllBluetoothChains = null;
6636 ArrayList<WorkChain> mUnoptimizedBluetoothChains = null;
6637
Joe Onoratoabded112016-02-08 16:49:39 -08006638 public Uid(BatteryStatsImpl bsi, int uid) {
6639 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006641
Bookatz867c0d72017-03-07 18:23:42 -08006642 mOnBatteryBackgroundTimeBase = new TimeBase();
6643 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6644 mBsi.mClocks.elapsedRealtime() * 1000);
6645
Bookatzc8c44962017-05-11 12:12:54 -07006646 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6647 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6648 mBsi.mClocks.elapsedRealtime() * 1000);
6649
Joe Onoratoabded112016-02-08 16:49:39 -08006650 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6651 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006652 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6653 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006654
Dianne Hackborn657153b2016-07-29 14:54:14 -07006655 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006656 @Override public Wakelock instantiateObject() {
6657 return new Wakelock(mBsi, Uid.this);
6658 }
6659 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006660 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6661 @Override public DualTimer instantiateObject() {
6662 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6663 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006664 }
6665 };
Bookatzaa4594a2017-03-24 12:39:56 -07006666 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6667 @Override public DualTimer instantiateObject() {
6668 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6669 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006670 }
6671 };
6672
6673 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6674 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6675 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6676 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006677 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6678 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006679 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006680 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6681 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006682 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 }
6684
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006685 @VisibleForTesting
6686 public void setProcessStateForTest(int procState) {
6687 mProcessState = procState;
6688 }
6689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006691 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006692 return nullIfAllZeros(mCpuFreqTimeMs, which);
6693 }
6694
6695 @Override
6696 public long[] getScreenOffCpuFreqTimes(int which) {
6697 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6698 }
6699
6700 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006701 public long getCpuActiveTime() {
6702 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6703 }
6704
6705 @Override
6706 public long[] getCpuClusterTimes() {
6707 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6708 }
6709
6710
6711 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006712 public long[] getCpuFreqTimes(int which, int procState) {
6713 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006714 return null;
6715 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006716 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006717 return null;
6718 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006719 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6720 mProcStateTimeMs = null;
6721 return null;
6722 }
6723 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6724 }
6725
6726 @Override
6727 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6728 if (which < 0 || which >= NUM_PROCESS_STATE) {
6729 return null;
6730 }
6731 if (mProcStateScreenOffTimeMs == null) {
6732 return null;
6733 }
6734 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6735 mProcStateScreenOffTimeMs = null;
6736 return null;
6737 }
6738 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6739 }
6740
6741 public void addIsolatedUid(int isolatedUid) {
6742 if (mChildUids == null) {
6743 mChildUids = new IntArray();
6744 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6745 return;
6746 }
6747 mChildUids.add(isolatedUid);
6748 }
6749
6750 public void removeIsolatedUid(int isolatedUid) {
6751 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6752 if (idx < 0) {
6753 return;
6754 }
6755 mChildUids.remove(idx);
6756 }
6757
6758 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6759 if (cpuTimesMs == null) {
6760 return null;
6761 }
6762 final long[] counts = cpuTimesMs.getCountsLocked(which);
6763 if (counts == null) {
6764 return null;
6765 }
6766 // Return counts only if at least one of the elements is non-zero.
6767 for (int i = counts.length - 1; i >= 0; --i) {
6768 if (counts[i] != 0) {
6769 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006770 }
6771 }
6772 return null;
6773 }
6774
Sudheer Shankae544d162017-12-28 17:06:20 -08006775 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006776 if (mProcStateTimeMs == null) {
6777 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006778 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006779 if (mProcStateTimeMs[procState] == null
6780 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
6781 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6782 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006783 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006784 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006785 }
6786
Sudheer Shankae544d162017-12-28 17:06:20 -08006787 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6788 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006789 if (mProcStateScreenOffTimeMs == null) {
6790 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006791 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006792 if (mProcStateScreenOffTimeMs[procState] == null
6793 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
6794 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
6795 mBsi.mOnBatteryScreenOffTimeBase);
6796 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006797 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006798 }
6799
6800 @Override
Bookatzc8c44962017-05-11 12:12:54 -07006801 public Timer getAggregatedPartialWakelockTimer() {
6802 return mAggregatedPartialWakelockTimer;
6803 }
6804
6805 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006806 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006807 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006808 }
6809
6810 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07006811 public Timer getMulticastWakelockStats() {
6812 return mWifiMulticastTimer;
6813 }
6814
6815 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006816 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006817 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006818 }
6819
6820 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006821 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006822 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006823 }
6824
6825 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006826 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
6827 return mJobCompletions;
6828 }
6829
6830 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07006831 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006832 return mSensorStats;
6833 }
6834
6835 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006836 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837 return mProcessStats;
6838 }
6839
6840 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006841 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006842 return mPackageStats;
6843 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006844
6845 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006846 public int getUid() {
6847 return mUid;
6848 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006849
6850 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006851 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006852 if (!mWifiRunning) {
6853 mWifiRunning = true;
6854 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006855 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
6856 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006857 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006858 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006859 }
6860 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006861
Dianne Hackborn617f8772009-03-31 15:04:46 -07006862 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006863 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006864 if (mWifiRunning) {
6865 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006866 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006867 }
6868 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006869
Dianne Hackborn617f8772009-03-31 15:04:46 -07006870 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006871 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006872 if (!mFullWifiLockOut) {
6873 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006874 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006875 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
6876 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006877 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006878 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006879 }
6880 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006881
The Android Open Source Project10592532009-03-18 17:39:46 -07006882 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006883 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006884 if (mFullWifiLockOut) {
6885 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006886 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006887 }
6888 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006889
The Android Open Source Project10592532009-03-18 17:39:46 -07006890 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006891 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006892 if (!mWifiScanStarted) {
6893 mWifiScanStarted = true;
6894 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006895 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
6896 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
6897 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006898 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006899 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006900 }
6901 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006902
The Android Open Source Project10592532009-03-18 17:39:46 -07006903 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006904 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006905 if (mWifiScanStarted) {
6906 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006907 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006908 }
6909 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006910
6911 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006912 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006913 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07006914 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006915 csph = csph >> 3;
6916 bin++;
6917 }
6918
6919 if (mWifiBatchedScanBinStarted == bin) return;
6920
6921 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
6922 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006923 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006924 }
6925 mWifiBatchedScanBinStarted = bin;
6926 if (mWifiBatchedScanTimer[bin] == null) {
6927 makeWifiBatchedScanBin(bin, null);
6928 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006929 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006930 }
6931
6932 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006933 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006934 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
6935 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006936 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006937 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6938 }
6939 }
6940
6941 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006942 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006943 if (!mWifiMulticastEnabled) {
6944 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006945 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006946 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6947 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006948 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006949 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08006950 StatsLog.write_non_chained(
6951 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null, 1);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006952 }
6953 }
6954
6955 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006956 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006957 if (mWifiMulticastEnabled) {
6958 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006959 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08006960 StatsLog.write_non_chained(
6961 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null, 0);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006962 }
6963 }
6964
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006965 @Override
6966 public ControllerActivityCounter getWifiControllerActivity() {
6967 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006968 }
6969
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006970 @Override
6971 public ControllerActivityCounter getBluetoothControllerActivity() {
6972 return mBluetoothControllerActivity;
6973 }
6974
6975 @Override
6976 public ControllerActivityCounter getModemControllerActivity() {
6977 return mModemControllerActivity;
6978 }
6979
6980 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
6981 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006982 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006983 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08006984 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006985 return mWifiControllerActivity;
6986 }
6987
6988 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
6989 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006990 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006991 NUM_BT_TX_LEVELS);
6992 }
6993 return mBluetoothControllerActivity;
6994 }
6995
6996 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
6997 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006998 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006999 ModemActivityInfo.TX_POWER_LEVELS);
7000 }
7001 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007002 }
7003
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007004 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7005 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007006 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7007 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007008 }
7009 return mAudioTurnedOnTimer;
7010 }
7011
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007012 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007013 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007014 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null, 1);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007015 }
7016
7017 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7018 if (mAudioTurnedOnTimer != null) {
7019 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007020 if (!mAudioTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007021 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07007022 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007023 }
7024 }
7025
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007026 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7027 if (mAudioTurnedOnTimer != null) {
7028 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007029 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null, 0);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007030 }
7031 }
7032
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007033 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7034 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007035 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7036 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007037 }
7038 return mVideoTurnedOnTimer;
7039 }
7040
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007041 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007042 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007043 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null, 1);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007044 }
7045
7046 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7047 if (mVideoTurnedOnTimer != null) {
7048 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007049 if (!mVideoTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007050 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(),
7051 null, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07007052 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007053 }
7054 }
7055
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007056 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7057 if (mVideoTurnedOnTimer != null) {
7058 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007059 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
7060 0);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007061 }
7062 }
7063
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007064 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7065 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007066 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7067 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007068 }
7069 return mFlashlightTurnedOnTimer;
7070 }
7071
7072 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7073 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007074 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,1);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007075 }
7076
7077 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7078 if (mFlashlightTurnedOnTimer != null) {
7079 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007080 if (!mFlashlightTurnedOnTimer.isRunningLocked()) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08007081 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7082 0);
Bookatzc1a050a2017-10-10 15:49:28 -07007083 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007084 }
7085 }
7086
7087 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7088 if (mFlashlightTurnedOnTimer != null) {
7089 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007090 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null, 0);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007091 }
7092 }
7093
7094 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7095 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007096 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7097 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007098 }
7099 return mCameraTurnedOnTimer;
7100 }
7101
7102 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7103 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007104 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null, 1);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007105 }
7106
7107 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7108 if (mCameraTurnedOnTimer != null) {
7109 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007110 if (!mCameraTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007111 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07007112 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007113 }
7114 }
7115
7116 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7117 if (mCameraTurnedOnTimer != null) {
7118 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007119 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null, 0);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007120 }
7121 }
7122
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007123 public StopwatchTimer createForegroundActivityTimerLocked() {
7124 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007125 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7126 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007127 }
7128 return mForegroundActivityTimer;
7129 }
7130
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007131 public StopwatchTimer createForegroundServiceTimerLocked() {
7132 if (mForegroundServiceTimer == null) {
7133 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7134 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7135 }
7136 return mForegroundServiceTimer;
7137 }
7138
Bookatzc8c44962017-05-11 12:12:54 -07007139 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7140 if (mAggregatedPartialWakelockTimer == null) {
7141 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7142 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7143 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7144 }
7145 return mAggregatedPartialWakelockTimer;
7146 }
7147
Bookatz867c0d72017-03-07 18:23:42 -08007148 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007149 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007150 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7151 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7152 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007153 }
7154 return mBluetoothScanTimer;
7155 }
7156
Bookatzb1f04f32017-05-19 13:57:32 -07007157 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7158 if (mBluetoothUnoptimizedScanTimer == null) {
7159 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7160 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7161 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7162 }
7163 return mBluetoothUnoptimizedScanTimer;
7164 }
7165
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007166 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7167 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007168 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007169 if (isUnoptimized) {
7170 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7171 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007172 }
7173
Bookatz94c5a312017-07-11 16:49:17 -07007174 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007175 if (mBluetoothScanTimer != null) {
7176 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7177 }
Bookatz94c5a312017-07-11 16:49:17 -07007178 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007179 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7180 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007181 }
7182
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007183 public void addBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7184 if (mAllBluetoothChains == null) {
7185 mAllBluetoothChains = new ArrayList<WorkChain>(4);
7186 }
7187
7188 if (isUnoptimized && mUnoptimizedBluetoothChains == null) {
7189 mUnoptimizedBluetoothChains = new ArrayList<WorkChain>(4);
7190 }
7191
7192 mAllBluetoothChains.add(workChain);
7193 if (isUnoptimized) {
7194 mUnoptimizedBluetoothChains.add(workChain);
7195 }
7196 }
7197
7198 public void removeBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7199 if (mAllBluetoothChains != null) {
7200 mAllBluetoothChains.remove(workChain);
7201 }
7202
7203 if (isUnoptimized && mUnoptimizedBluetoothChains != null) {
7204 mUnoptimizedBluetoothChains.remove(workChain);
7205 }
7206 }
7207
7208 public List<WorkChain> getAllBluetoothWorkChains() {
7209 return mAllBluetoothChains;
7210 }
7211
7212 public List<WorkChain> getUnoptimizedBluetoothWorkChains() {
7213 return mUnoptimizedBluetoothChains;
7214 }
7215
7216
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007217 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7218 if (mBluetoothScanTimer != null) {
7219 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7220 }
Bookatzb1f04f32017-05-19 13:57:32 -07007221 if (mBluetoothUnoptimizedScanTimer != null) {
7222 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7223 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007224 }
7225
Bookatz956f36bf2017-04-28 09:48:17 -07007226 public Counter createBluetoothScanResultCounterLocked() {
7227 if (mBluetoothScanResultCounter == null) {
7228 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7229 }
7230 return mBluetoothScanResultCounter;
7231 }
7232
Bookatzb1f04f32017-05-19 13:57:32 -07007233 public Counter createBluetoothScanResultBgCounterLocked() {
7234 if (mBluetoothScanResultBgCounter == null) {
7235 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7236 }
7237 return mBluetoothScanResultBgCounter;
7238 }
7239
Bookatz4ebc0642017-05-11 12:21:19 -07007240 public void noteBluetoothScanResultsLocked(int numNewResults) {
7241 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007242 // Uses background timebase, so the count will only be incremented if uid in background.
7243 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007244 }
7245
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007246 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007247 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007248 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007249 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007250 }
7251
7252 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007253 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007254 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007255 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007256 }
7257 }
7258
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007259 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7260 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7261 }
7262
7263 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7264 if (mForegroundServiceTimer != null) {
7265 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7266 }
7267 }
7268
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007269 public BatchTimer createVibratorOnTimerLocked() {
7270 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007271 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7272 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007273 }
7274 return mVibratorOnTimer;
7275 }
7276
7277 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007278 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007279 }
7280
7281 public void noteVibratorOffLocked() {
7282 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007283 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007284 }
7285 }
7286
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007287 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007288 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007289 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007290 return 0;
7291 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007292 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007293 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007294
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007295 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007296 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007297 if (mFullWifiLockTimer == null) {
7298 return 0;
7299 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007300 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007301 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007302
7303 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007304 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007305 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007306 return 0;
7307 }
Bookatzaa4594a2017-03-24 12:39:56 -07007308 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007309 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007310
7311 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007312 public int getWifiScanCount(int which) {
7313 if (mWifiScanTimer == null) {
7314 return 0;
7315 }
Bookatzaa4594a2017-03-24 12:39:56 -07007316 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007317 }
7318
7319 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007320 public Timer getWifiScanTimer() {
7321 return mWifiScanTimer;
7322 }
7323
7324 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007325 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007326 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007327 return 0;
7328 }
7329 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7330 }
7331
7332 @Override
7333 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7334 if (mWifiScanTimer == null) {
7335 return 0;
7336 }
7337 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007338 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007339 }
7340
7341 @Override
7342 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007343 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007344 return 0;
7345 }
7346 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7347 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007348 }
7349
7350 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007351 public Timer getWifiScanBackgroundTimer() {
7352 if (mWifiScanTimer == null) {
7353 return null;
7354 }
7355 return mWifiScanTimer.getSubTimer();
7356 }
7357
7358 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007359 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007360 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7361 if (mWifiBatchedScanTimer[csphBin] == null) {
7362 return 0;
7363 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007364 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007365 }
7366
7367 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007368 public int getWifiBatchedScanCount(int csphBin, int which) {
7369 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7370 if (mWifiBatchedScanTimer[csphBin] == null) {
7371 return 0;
7372 }
7373 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7374 }
7375
7376 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007377 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007378 if (mWifiMulticastTimer == null) {
7379 return 0;
7380 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007381 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007382 }
7383
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007384 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007385 public Timer getAudioTurnedOnTimer() {
7386 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007387 }
7388
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007389 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007390 public Timer getVideoTurnedOnTimer() {
7391 return mVideoTurnedOnTimer;
7392 }
7393
7394 @Override
7395 public Timer getFlashlightTurnedOnTimer() {
7396 return mFlashlightTurnedOnTimer;
7397 }
7398
7399 @Override
7400 public Timer getCameraTurnedOnTimer() {
7401 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007402 }
7403
Dianne Hackborn617f8772009-03-31 15:04:46 -07007404 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007405 public Timer getForegroundActivityTimer() {
7406 return mForegroundActivityTimer;
7407 }
7408
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007409 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007410 public Timer getForegroundServiceTimer() {
7411 return mForegroundServiceTimer;
7412 }
7413
7414 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007415 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007416 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007417 }
7418
7419 @Override
7420 public Timer getBluetoothScanBackgroundTimer() {
7421 if (mBluetoothScanTimer == null) {
7422 return null;
7423 }
7424 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007425 }
7426
Bookatz956f36bf2017-04-28 09:48:17 -07007427 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007428 public Timer getBluetoothUnoptimizedScanTimer() {
7429 return mBluetoothUnoptimizedScanTimer;
7430 }
7431
7432 @Override
7433 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7434 if (mBluetoothUnoptimizedScanTimer == null) {
7435 return null;
7436 }
7437 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7438 }
7439
7440 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007441 public Counter getBluetoothScanResultCounter() {
7442 return mBluetoothScanResultCounter;
7443 }
7444
Bookatzb1f04f32017-05-19 13:57:32 -07007445 @Override
7446 public Counter getBluetoothScanResultBgCounter() {
7447 return mBluetoothScanResultBgCounter;
7448 }
7449
Dianne Hackborn61659e52014-07-09 16:13:01 -07007450 void makeProcessState(int i, Parcel in) {
7451 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7452
7453 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007454 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7455 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007456 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007457 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7458 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007459 }
7460 }
7461
7462 @Override
7463 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7464 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7465 if (mProcessStateTimer[state] == null) {
7466 return 0;
7467 }
7468 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7469 }
7470
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007471 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007472 public Timer getProcessStateTimer(int state) {
7473 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7474 return mProcessStateTimer[state];
7475 }
7476
7477 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007478 public Timer getVibratorOnTimer() {
7479 return mVibratorOnTimer;
7480 }
7481
7482 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007483 public void noteUserActivityLocked(int type) {
7484 if (mUserActivityCounters == null) {
7485 initUserActivityLocked();
7486 }
Jeff Browndf693de2012-07-27 12:03:38 -07007487 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7488 mUserActivityCounters[type].stepAtomic();
7489 } else {
7490 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7491 new Throwable());
7492 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007493 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007494
Dianne Hackborn617f8772009-03-31 15:04:46 -07007495 @Override
7496 public boolean hasUserActivity() {
7497 return mUserActivityCounters != null;
7498 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007499
Dianne Hackborn617f8772009-03-31 15:04:46 -07007500 @Override
7501 public int getUserActivityCount(int type, int which) {
7502 if (mUserActivityCounters == null) {
7503 return 0;
7504 }
Evan Millarc64edde2009-04-18 12:26:32 -07007505 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007506 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007507
Robert Greenwalta029ea12013-09-25 16:38:12 -07007508 void makeWifiBatchedScanBin(int i, Parcel in) {
7509 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7510
Joe Onoratoabded112016-02-08 16:49:39 -08007511 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007512 if (collected == null) {
7513 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007514 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007515 }
7516 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007517 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7518 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007519 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007520 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7521 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007522 }
7523 }
7524
7525
Dianne Hackborn617f8772009-03-31 15:04:46 -07007526 void initUserActivityLocked() {
7527 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7528 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007529 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007530 }
7531 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007532
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007533 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7534 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007535 initNetworkActivityLocked();
7536 }
7537 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007538 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7539 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007540 } else {
7541 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7542 new Throwable());
7543 }
7544 }
7545
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007546 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7547 if (mNetworkByteActivityCounters == null) {
7548 initNetworkActivityLocked();
7549 }
7550 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7551 mMobileRadioActiveCount.addCountLocked(1);
7552 }
7553
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007554 @Override
7555 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007556 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007557 }
7558
7559 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007560 public long getNetworkActivityBytes(int type, int which) {
7561 if (mNetworkByteActivityCounters != null && type >= 0
7562 && type < mNetworkByteActivityCounters.length) {
7563 return mNetworkByteActivityCounters[type].getCountLocked(which);
7564 } else {
7565 return 0;
7566 }
7567 }
7568
7569 @Override
7570 public long getNetworkActivityPackets(int type, int which) {
7571 if (mNetworkPacketActivityCounters != null && type >= 0
7572 && type < mNetworkPacketActivityCounters.length) {
7573 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007574 } else {
7575 return 0;
7576 }
7577 }
7578
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007579 @Override
7580 public long getMobileRadioActiveTime(int which) {
7581 return mMobileRadioActiveTime != null
7582 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7583 }
7584
7585 @Override
7586 public int getMobileRadioActiveCount(int which) {
7587 return mMobileRadioActiveCount != null
7588 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7589 }
7590
Adam Lesinskie08af192015-03-25 16:42:59 -07007591 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007592 public long getUserCpuTimeUs(int which) {
7593 return mUserCpuTime.getCountLocked(which);
7594 }
7595
7596 @Override
7597 public long getSystemCpuTimeUs(int which) {
7598 return mSystemCpuTime.getCountLocked(which);
7599 }
7600
7601 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007602 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007603 if (mCpuClusterSpeedTimesUs != null) {
7604 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7605 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7606 if (cpuSpeedTimesUs != null) {
7607 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7608 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007609 if (c != null) {
7610 return c.getCountLocked(which);
7611 }
7612 }
7613 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007614 }
7615 }
7616 return 0;
7617 }
7618
Adam Lesinski5f056f62016-07-14 16:56:08 -07007619 public void noteMobileRadioApWakeupLocked() {
7620 if (mMobileRadioApWakeupCount == null) {
7621 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7622 }
7623 mMobileRadioApWakeupCount.addCountLocked(1);
7624 }
7625
7626 @Override
7627 public long getMobileRadioApWakeupCount(int which) {
7628 if (mMobileRadioApWakeupCount != null) {
7629 return mMobileRadioApWakeupCount.getCountLocked(which);
7630 }
7631 return 0;
7632 }
7633
7634 public void noteWifiRadioApWakeupLocked() {
7635 if (mWifiRadioApWakeupCount == null) {
7636 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7637 }
7638 mWifiRadioApWakeupCount.addCountLocked(1);
7639 }
7640
7641 @Override
7642 public long getWifiRadioApWakeupCount(int which) {
7643 if (mWifiRadioApWakeupCount != null) {
7644 return mWifiRadioApWakeupCount.getCountLocked(which);
7645 }
7646 return 0;
7647 }
7648
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007649 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007650 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7651 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007652 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007653 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7654 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007655 }
Joe Onoratoabded112016-02-08 16:49:39 -08007656 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7657 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007658 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007659
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007660 /**
7661 * Clear all stats for this uid. Returns true if the uid is completely
7662 * inactive so can be dropped.
7663 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007664 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007665 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007666 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007667
Bookatz993a0be2017-07-21 09:03:23 -07007668 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7669 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7670
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007671 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007672 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007673 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007674 }
7675 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007676 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007677 active |= mFullWifiLockOut;
7678 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007679 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007680 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007681 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007682 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007683 if (mWifiBatchedScanTimer != null) {
7684 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7685 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007686 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007687 }
7688 }
7689 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7690 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007691 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007692 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007693 active |= mWifiMulticastEnabled;
7694 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007695
7696 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7697 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7698 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7699 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7700 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007701 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007702 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007703 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007704 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007705 if (mBluetoothScanResultCounter != null) {
7706 mBluetoothScanResultCounter.reset(false);
7707 }
Bookatzb1f04f32017-05-19 13:57:32 -07007708 if (mBluetoothScanResultBgCounter != null) {
7709 mBluetoothScanResultBgCounter.reset(false);
7710 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007711
Dianne Hackborn61659e52014-07-09 16:13:01 -07007712 if (mProcessStateTimer != null) {
7713 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7714 if (mProcessStateTimer[i] != null) {
7715 active |= !mProcessStateTimer[i].reset(false);
7716 }
7717 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007718 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007719 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007720 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007721 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007722 mVibratorOnTimer.detach();
7723 mVibratorOnTimer = null;
7724 } else {
7725 active = true;
7726 }
7727 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007728
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007729 if (mUserActivityCounters != null) {
7730 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7731 mUserActivityCounters[i].reset(false);
7732 }
7733 }
7734
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007735 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007736 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007737 mNetworkByteActivityCounters[i].reset(false);
7738 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007739 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007740 mMobileRadioActiveTime.reset(false);
7741 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007742 }
7743
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007744 if (mWifiControllerActivity != null) {
7745 mWifiControllerActivity.reset(false);
7746 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007747
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007748 if (mBluetoothControllerActivity != null) {
7749 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007750 }
7751
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007752 if (mModemControllerActivity != null) {
7753 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007754 }
7755
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007756 mUserCpuTime.reset(false);
7757 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007758
Sudheer Shankaaf857412017-07-21 00:14:24 -07007759 if (mCpuClusterSpeedTimesUs != null) {
7760 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007761 if (speeds != null) {
7762 for (LongSamplingCounter speed : speeds) {
7763 if (speed != null) {
7764 speed.reset(false);
7765 }
7766 }
7767 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007768 }
7769 }
7770
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007771 if (mCpuFreqTimeMs != null) {
7772 mCpuFreqTimeMs.reset(false);
7773 }
7774 if (mScreenOffCpuFreqTimeMs != null) {
7775 mScreenOffCpuFreqTimeMs.reset(false);
7776 }
7777
Mike Ma3d422c32017-10-25 11:08:57 -07007778 mCpuActiveTimeMs.reset(false);
7779 mCpuClusterTimesMs.reset(false);
7780
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007781 if (mProcStateTimeMs != null) {
7782 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7783 if (counters != null) {
7784 counters.reset(false);
7785 }
7786 }
7787 }
7788 if (mProcStateScreenOffTimeMs != null) {
7789 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7790 if (counters != null) {
7791 counters.reset(false);
7792 }
7793 }
7794 }
7795
Adam Lesinski5f056f62016-07-14 16:56:08 -07007796 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
7797 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
7798
Dianne Hackbornd953c532014-08-16 18:17:38 -07007799 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7800 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
7801 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007802 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007803 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007804 } else {
7805 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007806 }
7807 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007808 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07007809 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007810 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07007811 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007812 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007813 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007814 timer.detach();
7815 } else {
7816 active = true;
7817 }
7818 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007819 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07007820 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007821 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07007822 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007823 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007824 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007825 timer.detach();
7826 } else {
7827 active = true;
7828 }
7829 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007830 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007831 mJobCompletions.clear();
Dianne Hackborn61659e52014-07-09 16:13:01 -07007832 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
7833 Sensor s = mSensorStats.valueAt(ise);
7834 if (s.reset()) {
7835 mSensorStats.removeAt(ise);
7836 } else {
7837 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007838 }
7839 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07007840 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
7841 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08007842 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007843 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007844 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007845 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007846 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007847 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007848 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007849 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007850 } else {
7851 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007852 }
7853 }
7854 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007855 if (mPackageStats.size() > 0) {
7856 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
7857 while (it.hasNext()) {
7858 Map.Entry<String, Pkg> pkgEntry = it.next();
7859 Pkg p = pkgEntry.getValue();
7860 p.detach();
7861 if (p.mServiceStats.size() > 0) {
7862 Iterator<Map.Entry<String, Pkg.Serv>> it2
7863 = p.mServiceStats.entrySet().iterator();
7864 while (it2.hasNext()) {
7865 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
7866 servEntry.getValue().detach();
7867 }
7868 }
7869 }
7870 mPackageStats.clear();
7871 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007872
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08007873 mLastStepUserTime = mLastStepSystemTime = 0;
7874 mCurStepUserTime = mCurStepSystemTime = 0;
7875
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007876 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007877 if (mWifiRunningTimer != null) {
7878 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007879 }
7880 if (mFullWifiLockTimer != null) {
7881 mFullWifiLockTimer.detach();
7882 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007883 if (mWifiScanTimer != null) {
7884 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007885 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007886 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7887 if (mWifiBatchedScanTimer[i] != null) {
7888 mWifiBatchedScanTimer[i].detach();
7889 }
7890 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007891 if (mWifiMulticastTimer != null) {
7892 mWifiMulticastTimer.detach();
7893 }
7894 if (mAudioTurnedOnTimer != null) {
7895 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007896 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007897 }
7898 if (mVideoTurnedOnTimer != null) {
7899 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007900 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007901 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007902 if (mFlashlightTurnedOnTimer != null) {
7903 mFlashlightTurnedOnTimer.detach();
7904 mFlashlightTurnedOnTimer = null;
7905 }
7906 if (mCameraTurnedOnTimer != null) {
7907 mCameraTurnedOnTimer.detach();
7908 mCameraTurnedOnTimer = null;
7909 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007910 if (mForegroundActivityTimer != null) {
7911 mForegroundActivityTimer.detach();
7912 mForegroundActivityTimer = null;
7913 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007914 if (mForegroundServiceTimer != null) {
7915 mForegroundServiceTimer.detach();
7916 mForegroundServiceTimer = null;
7917 }
Bookatzc8c44962017-05-11 12:12:54 -07007918 if (mAggregatedPartialWakelockTimer != null) {
7919 mAggregatedPartialWakelockTimer.detach();
7920 mAggregatedPartialWakelockTimer = null;
7921 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007922 if (mBluetoothScanTimer != null) {
7923 mBluetoothScanTimer.detach();
7924 mBluetoothScanTimer = null;
7925 }
Bookatzb1f04f32017-05-19 13:57:32 -07007926 if (mBluetoothUnoptimizedScanTimer != null) {
7927 mBluetoothUnoptimizedScanTimer.detach();
7928 mBluetoothUnoptimizedScanTimer = null;
7929 }
Bookatz956f36bf2017-04-28 09:48:17 -07007930 if (mBluetoothScanResultCounter != null) {
7931 mBluetoothScanResultCounter.detach();
7932 mBluetoothScanResultCounter = null;
7933 }
Bookatzb1f04f32017-05-19 13:57:32 -07007934 if (mBluetoothScanResultBgCounter != null) {
7935 mBluetoothScanResultBgCounter.detach();
7936 mBluetoothScanResultBgCounter = null;
7937 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007938 if (mUserActivityCounters != null) {
7939 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7940 mUserActivityCounters[i].detach();
7941 }
7942 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007943 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007944 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007945 mNetworkByteActivityCounters[i].detach();
7946 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007947 }
7948 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007949
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007950 if (mWifiControllerActivity != null) {
7951 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07007952 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007953
7954 if (mBluetoothControllerActivity != null) {
7955 mBluetoothControllerActivity.detach();
7956 }
7957
7958 if (mModemControllerActivity != null) {
7959 mModemControllerActivity.detach();
7960 }
7961
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007962 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007963
7964 mUserCpuTime.detach();
7965 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07007966
Sudheer Shankaaf857412017-07-21 00:14:24 -07007967 if (mCpuClusterSpeedTimesUs != null) {
7968 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007969 if (cpuSpeeds != null) {
7970 for (LongSamplingCounter c : cpuSpeeds) {
7971 if (c != null) {
7972 c.detach();
7973 }
7974 }
7975 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007976 }
7977 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007978
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007979 if (mCpuFreqTimeMs != null) {
7980 mCpuFreqTimeMs.detach();
7981 }
7982 if (mScreenOffCpuFreqTimeMs != null) {
7983 mScreenOffCpuFreqTimeMs.detach();
7984 }
Mike Ma3d422c32017-10-25 11:08:57 -07007985 mCpuActiveTimeMs.detach();
7986 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007987
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007988 if (mProcStateTimeMs != null) {
7989 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7990 if (counters != null) {
7991 counters.detach();
7992 }
7993 }
7994 }
7995 if (mProcStateScreenOffTimeMs != null) {
7996 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7997 if (counters != null) {
7998 counters.detach();
7999 }
8000 }
8001 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008002 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8003 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008004 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008005
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008006 return !active;
8007 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008008
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008009 void writeJobCompletionsToParcelLocked(Parcel out) {
8010 int NJC = mJobCompletions.size();
8011 out.writeInt(NJC);
8012 for (int ijc=0; ijc<NJC; ijc++) {
8013 out.writeString(mJobCompletions.keyAt(ijc));
8014 SparseIntArray types = mJobCompletions.valueAt(ijc);
8015 int NT = types.size();
8016 out.writeInt(NT);
8017 for (int it=0; it<NT; it++) {
8018 out.writeInt(types.keyAt(it));
8019 out.writeInt(types.valueAt(it));
8020 }
8021 }
8022 }
8023
Bookatz867c0d72017-03-07 18:23:42 -08008024 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8025 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008026 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008027
Dianne Hackbornd953c532014-08-16 18:17:38 -07008028 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8029 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008030 out.writeInt(NW);
8031 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008032 out.writeString(wakeStats.keyAt(iw));
8033 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008034 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 }
8036
Bookatz2bffb5b2017-04-13 11:59:33 -07008037 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008038 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008039 out.writeInt(NS);
8040 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008041 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008042 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008043 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8044 }
8045
Bookatzaa4594a2017-03-24 12:39:56 -07008046 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008047 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008048 out.writeInt(NJ);
8049 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008050 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008051 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008052 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8053 }
8054
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008055 writeJobCompletionsToParcelLocked(out);
8056
Dianne Hackborn61659e52014-07-09 16:13:01 -07008057 int NSE = mSensorStats.size();
8058 out.writeInt(NSE);
8059 for (int ise=0; ise<NSE; ise++) {
8060 out.writeInt(mSensorStats.keyAt(ise));
8061 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008062 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008063 }
8064
Dianne Hackborn61659e52014-07-09 16:13:01 -07008065 int NP = mProcessStats.size();
8066 out.writeInt(NP);
8067 for (int ip=0; ip<NP; ip++) {
8068 out.writeString(mProcessStats.keyAt(ip));
8069 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 proc.writeToParcelLocked(out);
8071 }
8072
8073 out.writeInt(mPackageStats.size());
8074 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8075 out.writeString(pkgEntry.getKey());
8076 Uid.Pkg pkg = pkgEntry.getValue();
8077 pkg.writeToParcelLocked(out);
8078 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008079
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008080 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008081 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008082 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008083 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008084 out.writeInt(0);
8085 }
8086 if (mFullWifiLockTimer != null) {
8087 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008088 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008089 } else {
8090 out.writeInt(0);
8091 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008092 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008093 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008094 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008095 } else {
8096 out.writeInt(0);
8097 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008098 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8099 if (mWifiBatchedScanTimer[i] != null) {
8100 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008101 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008102 } else {
8103 out.writeInt(0);
8104 }
8105 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008106 if (mWifiMulticastTimer != null) {
8107 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008108 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008109 } else {
8110 out.writeInt(0);
8111 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008112
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008113 if (mAudioTurnedOnTimer != null) {
8114 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008115 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008116 } else {
8117 out.writeInt(0);
8118 }
8119 if (mVideoTurnedOnTimer != null) {
8120 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008121 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008122 } else {
8123 out.writeInt(0);
8124 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008125 if (mFlashlightTurnedOnTimer != null) {
8126 out.writeInt(1);
8127 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8128 } else {
8129 out.writeInt(0);
8130 }
8131 if (mCameraTurnedOnTimer != null) {
8132 out.writeInt(1);
8133 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8134 } else {
8135 out.writeInt(0);
8136 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008137 if (mForegroundActivityTimer != null) {
8138 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008139 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008140 } else {
8141 out.writeInt(0);
8142 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008143 if (mForegroundServiceTimer != null) {
8144 out.writeInt(1);
8145 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8146 } else {
8147 out.writeInt(0);
8148 }
Bookatzc8c44962017-05-11 12:12:54 -07008149 if (mAggregatedPartialWakelockTimer != null) {
8150 out.writeInt(1);
8151 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8152 } else {
8153 out.writeInt(0);
8154 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008155 if (mBluetoothScanTimer != null) {
8156 out.writeInt(1);
8157 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8158 } else {
8159 out.writeInt(0);
8160 }
Bookatzb1f04f32017-05-19 13:57:32 -07008161 if (mBluetoothUnoptimizedScanTimer != null) {
8162 out.writeInt(1);
8163 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8164 } else {
8165 out.writeInt(0);
8166 }
Bookatz956f36bf2017-04-28 09:48:17 -07008167 if (mBluetoothScanResultCounter != null) {
8168 out.writeInt(1);
8169 mBluetoothScanResultCounter.writeToParcel(out);
8170 } else {
8171 out.writeInt(0);
8172 }
Bookatzb1f04f32017-05-19 13:57:32 -07008173 if (mBluetoothScanResultBgCounter != null) {
8174 out.writeInt(1);
8175 mBluetoothScanResultBgCounter.writeToParcel(out);
8176 } else {
8177 out.writeInt(0);
8178 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008179 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8180 if (mProcessStateTimer[i] != null) {
8181 out.writeInt(1);
8182 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8183 } else {
8184 out.writeInt(0);
8185 }
8186 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008187 if (mVibratorOnTimer != null) {
8188 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008189 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008190 } else {
8191 out.writeInt(0);
8192 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008193 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008194 out.writeInt(1);
8195 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8196 mUserActivityCounters[i].writeToParcel(out);
8197 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008198 } else {
8199 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008200 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008201 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008202 out.writeInt(1);
8203 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008204 mNetworkByteActivityCounters[i].writeToParcel(out);
8205 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008206 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008207 mMobileRadioActiveTime.writeToParcel(out);
8208 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008209 } else {
8210 out.writeInt(0);
8211 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008212
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008213 if (mWifiControllerActivity != null) {
8214 out.writeInt(1);
8215 mWifiControllerActivity.writeToParcel(out, 0);
8216 } else {
8217 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008218 }
8219
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008220 if (mBluetoothControllerActivity != null) {
8221 out.writeInt(1);
8222 mBluetoothControllerActivity.writeToParcel(out, 0);
8223 } else {
8224 out.writeInt(0);
8225 }
8226
8227 if (mModemControllerActivity != null) {
8228 out.writeInt(1);
8229 mModemControllerActivity.writeToParcel(out, 0);
8230 } else {
8231 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008232 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008233
8234 mUserCpuTime.writeToParcel(out);
8235 mSystemCpuTime.writeToParcel(out);
8236
Sudheer Shankaaf857412017-07-21 00:14:24 -07008237 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008238 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008239 out.writeInt(mCpuClusterSpeedTimesUs.length);
8240 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008241 if (cpuSpeeds != null) {
8242 out.writeInt(1);
8243 out.writeInt(cpuSpeeds.length);
8244 for (LongSamplingCounter c : cpuSpeeds) {
8245 if (c != null) {
8246 out.writeInt(1);
8247 c.writeToParcel(out);
8248 } else {
8249 out.writeInt(0);
8250 }
8251 }
8252 } else {
8253 out.writeInt(0);
8254 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008255 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008256 } else {
8257 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008258 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008259
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008260 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8261 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008262
8263 mCpuActiveTimeMs.writeToParcel(out);
8264 mCpuClusterTimesMs.writeToParcel(out);
8265
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008266 if (mProcStateTimeMs != null) {
8267 out.writeInt(mProcStateTimeMs.length);
8268 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8269 LongSamplingCounterArray.writeToParcel(out, counters);
8270 }
8271 } else {
8272 out.writeInt(0);
8273 }
8274 if (mProcStateScreenOffTimeMs != null) {
8275 out.writeInt(mProcStateScreenOffTimeMs.length);
8276 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8277 LongSamplingCounterArray.writeToParcel(out, counters);
8278 }
8279 } else {
8280 out.writeInt(0);
8281 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008282
Adam Lesinski5f056f62016-07-14 16:56:08 -07008283 if (mMobileRadioApWakeupCount != null) {
8284 out.writeInt(1);
8285 mMobileRadioApWakeupCount.writeToParcel(out);
8286 } else {
8287 out.writeInt(0);
8288 }
8289
8290 if (mWifiRadioApWakeupCount != null) {
8291 out.writeInt(1);
8292 mWifiRadioApWakeupCount.writeToParcel(out);
8293 } else {
8294 out.writeInt(0);
8295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 }
8297
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008298 void readJobCompletionsFromParcelLocked(Parcel in) {
8299 int numJobCompletions = in.readInt();
8300 mJobCompletions.clear();
8301 for (int j = 0; j < numJobCompletions; j++) {
8302 String jobName = in.readString();
8303 int numTypes = in.readInt();
8304 if (numTypes > 0) {
8305 SparseIntArray types = new SparseIntArray();
8306 for (int k = 0; k < numTypes; k++) {
8307 int type = in.readInt();
8308 int count = in.readInt();
8309 types.put(type, count);
8310 }
8311 mJobCompletions.put(jobName, types);
8312 }
8313 }
8314 }
8315
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008316 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008317 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008318 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 int numWakelocks = in.readInt();
8321 mWakelockStats.clear();
8322 for (int j = 0; j < numWakelocks; j++) {
8323 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008324 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008325 wakelock.readFromParcelLocked(
8326 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008327 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008328 }
8329
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008330 int numSyncs = in.readInt();
8331 mSyncStats.clear();
8332 for (int j = 0; j < numSyncs; j++) {
8333 String syncName = in.readString();
8334 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008335 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8336 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008337 }
8338 }
8339
8340 int numJobs = in.readInt();
8341 mJobStats.clear();
8342 for (int j = 0; j < numJobs; j++) {
8343 String jobName = in.readString();
8344 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008345 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8346 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008347 }
8348 }
8349
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008350 readJobCompletionsFromParcelLocked(in);
8351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 int numSensors = in.readInt();
8353 mSensorStats.clear();
8354 for (int k = 0; k < numSensors; k++) {
8355 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008356 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008357 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8358 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008359 mSensorStats.put(sensorNumber, sensor);
8360 }
8361
8362 int numProcs = in.readInt();
8363 mProcessStats.clear();
8364 for (int k = 0; k < numProcs; k++) {
8365 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008366 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008367 proc.readFromParcelLocked(in);
8368 mProcessStats.put(processName, proc);
8369 }
8370
8371 int numPkgs = in.readInt();
8372 mPackageStats.clear();
8373 for (int l = 0; l < numPkgs; l++) {
8374 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008375 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008376 pkg.readFromParcelLocked(in);
8377 mPackageStats.put(packageName, pkg);
8378 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008379
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008380 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008381 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008382 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8383 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008384 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008385 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008386 }
8387 mFullWifiLockOut = false;
8388 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008389 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8390 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008391 } else {
8392 mFullWifiLockTimer = null;
8393 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008394 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008395 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008396 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8397 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8398 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008399 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008400 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008401 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008402 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8403 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8404 if (in.readInt() != 0) {
8405 makeWifiBatchedScanBin(i, in);
8406 } else {
8407 mWifiBatchedScanTimer[i] = null;
8408 }
8409 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008410 mWifiMulticastEnabled = false;
8411 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008412 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8413 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008414 } else {
8415 mWifiMulticastTimer = null;
8416 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008417 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008418 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8419 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008420 } else {
8421 mAudioTurnedOnTimer = null;
8422 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008423 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008424 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8425 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008426 } else {
8427 mVideoTurnedOnTimer = null;
8428 }
8429 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008430 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8431 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008432 } else {
8433 mFlashlightTurnedOnTimer = null;
8434 }
8435 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008436 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8437 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008438 } else {
8439 mCameraTurnedOnTimer = null;
8440 }
8441 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008442 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8443 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008444 } else {
8445 mForegroundActivityTimer = null;
8446 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008447 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008448 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8449 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8450 } else {
8451 mForegroundServiceTimer = null;
8452 }
8453 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008454 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8455 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8456 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8457 in);
8458 } else {
8459 mAggregatedPartialWakelockTimer = null;
8460 }
8461 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008462 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8463 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8464 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008465 } else {
8466 mBluetoothScanTimer = null;
8467 }
Bookatz956f36bf2017-04-28 09:48:17 -07008468 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008469 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8470 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8471 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8472 } else {
8473 mBluetoothUnoptimizedScanTimer = null;
8474 }
8475 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008476 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8477 } else {
8478 mBluetoothScanResultCounter = null;
8479 }
Bookatzb1f04f32017-05-19 13:57:32 -07008480 if (in.readInt() != 0) {
8481 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8482 } else {
8483 mBluetoothScanResultBgCounter = null;
8484 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008485 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008486 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8487 if (in.readInt() != 0) {
8488 makeProcessState(i, in);
8489 } else {
8490 mProcessStateTimer[i] = null;
8491 }
8492 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008493 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008494 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8495 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008496 } else {
8497 mVibratorOnTimer = null;
8498 }
8499 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008500 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8501 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008502 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008503 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008504 } else {
8505 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008506 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008507 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008508 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8509 mNetworkPacketActivityCounters
8510 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008511 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008512 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008513 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008514 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008515 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008516 }
Joe Onoratoabded112016-02-08 16:49:39 -08008517 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8518 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008519 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008520 mNetworkByteActivityCounters = null;
8521 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008522 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008523
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008524 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008525 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008526 NUM_WIFI_TX_LEVELS, in);
8527 } else {
8528 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008529 }
8530
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008531 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008532 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008533 NUM_BT_TX_LEVELS, in);
8534 } else {
8535 mBluetoothControllerActivity = null;
8536 }
8537
8538 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008539 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008540 ModemActivityInfo.TX_POWER_LEVELS, in);
8541 } else {
8542 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008543 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008544
Joe Onoratoabded112016-02-08 16:49:39 -08008545 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8546 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008547
Adam Lesinski6832f392015-09-05 18:05:40 -07008548 if (in.readInt() != 0) {
8549 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008550 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008551 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008552 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008553
Sudheer Shankaaf857412017-07-21 00:14:24 -07008554 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008555 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8556 if (in.readInt() != 0) {
8557 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008558 if (mBsi.mPowerProfile != null &&
8559 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008560 throw new ParcelFormatException("Incompatible number of cpu speeds");
8561 }
8562
8563 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008564 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008565 for (int speed = 0; speed < numSpeeds; speed++) {
8566 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008567 cpuSpeeds[speed] = new LongSamplingCounter(
8568 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008569 }
8570 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008571 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008572 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008573 }
8574 }
8575 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008576 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008577 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008578
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008579 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8580 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8581 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008582
Mike Ma3d422c32017-10-25 11:08:57 -07008583 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8584 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8585
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008586 int length = in.readInt();
8587 if (length == NUM_PROCESS_STATE) {
8588 mProcStateTimeMs = new LongSamplingCounterArray[length];
8589 for (int procState = 0; procState < length; ++procState) {
8590 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8591 in, mBsi.mOnBatteryTimeBase);
8592 }
8593 } else {
8594 mProcStateTimeMs = null;
8595 }
8596 length = in.readInt();
8597 if (length == NUM_PROCESS_STATE) {
8598 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8599 for (int procState = 0; procState < length; ++procState) {
8600 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8601 in, mBsi.mOnBatteryScreenOffTimeBase);
8602 }
8603 } else {
8604 mProcStateScreenOffTimeMs = null;
8605 }
8606
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008607 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008608 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8609 } else {
8610 mMobileRadioApWakeupCount = null;
8611 }
8612
8613 if (in.readInt() != 0) {
8614 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8615 } else {
8616 mWifiRadioApWakeupCount = null;
8617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008618 }
8619
8620 /**
8621 * The statistics associated with a particular wake lock.
8622 */
Joe Onoratoabded112016-02-08 16:49:39 -08008623 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8624 /**
8625 * BatteryStatsImpl that we are associated with.
8626 */
8627 protected BatteryStatsImpl mBsi;
8628
8629 /**
8630 * BatteryStatsImpl that we are associated with.
8631 */
8632 protected Uid mUid;
8633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634 /**
8635 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008636 * 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 -08008637 */
Bookatz5b5ec322017-05-26 09:40:38 -07008638 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008639
8640 /**
8641 * How long (in ms) this uid has been keeping the device fully awake.
8642 */
Evan Millarc64edde2009-04-18 12:26:32 -07008643 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644
8645 /**
8646 * How long (in ms) this uid has had a window keeping the device awake.
8647 */
Evan Millarc64edde2009-04-18 12:26:32 -07008648 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008649
8650 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008651 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008652 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008653 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008654
Joe Onoratoabded112016-02-08 16:49:39 -08008655 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8656 mBsi = bsi;
8657 mUid = uid;
8658 }
8659
Adam Lesinski9425fe22015-06-19 12:02:13 -07008660 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8662 * proper timer pool from the given BatteryStatsImpl object.
8663 *
8664 * @param in the Parcel to be read from.
8665 * return a new Timer, or null.
8666 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008667 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8668 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008669 if (in.readInt() == 0) {
8670 return null;
8671 }
8672
Joe Onoratoabded112016-02-08 16:49:39 -08008673 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008674 }
8675
Joe Onorato92fd23f2016-07-25 11:18:42 -07008676 /**
8677 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8678 * proper timer pool from the given BatteryStatsImpl object.
8679 *
8680 * @param in the Parcel to be read from.
8681 * return a new Timer, or null.
8682 */
Bookatz5b5ec322017-05-26 09:40:38 -07008683 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8684 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008685 if (in.readInt() == 0) {
8686 return null;
8687 }
8688
Bookatz5b5ec322017-05-26 09:40:38 -07008689 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008690 }
8691
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008692 boolean reset() {
8693 boolean wlactive = false;
8694 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008695 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008696 }
8697 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008698 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008699 }
8700 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008701 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008702 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008703 if (mTimerDraw != null) {
8704 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008705 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008706 if (!wlactive) {
8707 if (mTimerFull != null) {
8708 mTimerFull.detach();
8709 mTimerFull = null;
8710 }
8711 if (mTimerPartial != null) {
8712 mTimerPartial.detach();
8713 mTimerPartial = null;
8714 }
8715 if (mTimerWindow != null) {
8716 mTimerWindow.detach();
8717 mTimerWindow = null;
8718 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008719 if (mTimerDraw != null) {
8720 mTimerDraw.detach();
8721 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008722 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008723 }
8724 return !wlactive;
8725 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008726
Bookatz5b5ec322017-05-26 09:40:38 -07008727 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
8728 TimeBase screenOffBgTimeBase, Parcel in) {
8729 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
8730 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008731 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
8732 mBsi.mFullTimers, timeBase, in);
8733 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
8734 mBsi.mWindowTimers, timeBase, in);
8735 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
8736 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 }
8738
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008739 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
8740 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
8741 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
8742 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008743 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008744 }
8745
8746 @Override
8747 public Timer getWakeTime(int type) {
8748 switch (type) {
8749 case WAKE_TYPE_FULL: return mTimerFull;
8750 case WAKE_TYPE_PARTIAL: return mTimerPartial;
8751 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008752 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008753 default: throw new IllegalArgumentException("type = " + type);
8754 }
8755 }
8756 }
8757
Joe Onoratoabded112016-02-08 16:49:39 -08008758 public static class Sensor extends BatteryStats.Uid.Sensor {
8759 /**
8760 * BatteryStatsImpl that we are associated with.
8761 */
8762 protected BatteryStatsImpl mBsi;
8763
8764 /**
Bookatz867c0d72017-03-07 18:23:42 -08008765 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08008766 */
8767 protected Uid mUid;
8768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08008770 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008771
Joe Onoratoabded112016-02-08 16:49:39 -08008772 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
8773 mBsi = bsi;
8774 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008775 mHandle = handle;
8776 }
8777
Bookatz867c0d72017-03-07 18:23:42 -08008778 private DualTimer readTimersFromParcel(
8779 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008780 if (in.readInt() == 0) {
8781 return null;
8782 }
8783
Joe Onoratoabded112016-02-08 16:49:39 -08008784 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07008786 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08008787 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788 }
Bookatz867c0d72017-03-07 18:23:42 -08008789 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008790 }
8791
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008792 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008793 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008794 mTimer = null;
8795 return true;
8796 }
8797 return false;
8798 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008799
Bookatz867c0d72017-03-07 18:23:42 -08008800 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
8801 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008802 }
8803
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008804 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07008805 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008806 }
8807
8808 @Override
8809 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07008810 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008811 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008812
8813 @Override
Bookatz867c0d72017-03-07 18:23:42 -08008814 public Timer getSensorBackgroundTime() {
8815 if (mTimer == null) {
8816 return null;
8817 }
8818 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008819 }
8820
8821 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008822 public int getHandle() {
8823 return mHandle;
8824 }
8825 }
8826
8827 /**
8828 * The statistics associated with a particular process.
8829 */
Joe Onoratoabded112016-02-08 16:49:39 -08008830 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
8831 /**
8832 * BatteryStatsImpl that we are associated with.
8833 */
8834 protected BatteryStatsImpl mBsi;
8835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008837 * The name of this process.
8838 */
8839 final String mName;
8840
8841 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08008842 * Remains true until removed from the stats.
8843 */
8844 boolean mActive = true;
8845
8846 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008847 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008848 */
8849 long mUserTime;
8850
8851 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008852 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 */
8854 long mSystemTime;
8855
8856 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008857 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008858 */
8859 long mForegroundTime;
8860
8861 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008862 * Number of times the process has been started.
8863 */
8864 int mStarts;
8865
8866 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008867 * Number of times the process has crashed.
8868 */
8869 int mNumCrashes;
8870
8871 /**
8872 * Number of times the process has had an ANR.
8873 */
8874 int mNumAnrs;
8875
8876 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008877 * The amount of user time loaded from a previous save.
8878 */
8879 long mLoadedUserTime;
8880
8881 /**
8882 * The amount of system time loaded from a previous save.
8883 */
8884 long mLoadedSystemTime;
8885
8886 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008887 * The amount of foreground time loaded from a previous save.
8888 */
8889 long mLoadedForegroundTime;
8890
8891 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008892 * The number of times the process has started from a previous save.
8893 */
8894 int mLoadedStarts;
8895
8896 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008897 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008898 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008899 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008900
8901 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008902 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008903 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008904 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008905
8906 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 * The amount of user time when last unplugged.
8908 */
8909 long mUnpluggedUserTime;
8910
8911 /**
8912 * The amount of system time when last unplugged.
8913 */
8914 long mUnpluggedSystemTime;
8915
8916 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008917 * The amount of foreground time since unplugged.
8918 */
8919 long mUnpluggedForegroundTime;
8920
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008921 /**
8922 * The number of times the process has started before unplugged.
8923 */
8924 int mUnpluggedStarts;
8925
Dianne Hackborn61659e52014-07-09 16:13:01 -07008926 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008927 * Number of times the process has crashed before unplugged.
8928 */
8929 int mUnpluggedNumCrashes;
8930
8931 /**
8932 * Number of times the process has had an ANR before unplugged.
8933 */
8934 int mUnpluggedNumAnrs;
8935
Dianne Hackborn287952c2010-09-22 22:34:31 -07008936 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008937
Joe Onoratoabded112016-02-08 16:49:39 -08008938 public Proc(BatteryStatsImpl bsi, String name) {
8939 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008940 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08008941 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008942 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07008943
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008944 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 mUnpluggedUserTime = mUserTime;
8946 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008947 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008948 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008949 mUnpluggedNumCrashes = mNumCrashes;
8950 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008951 }
8952
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008953 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008954 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008955
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008956 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08008957 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08008958 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008959 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008960
Dianne Hackborn287952c2010-09-22 22:34:31 -07008961 public int countExcessivePowers() {
8962 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008963 }
8964
Dianne Hackborn287952c2010-09-22 22:34:31 -07008965 public ExcessivePower getExcessivePower(int i) {
8966 if (mExcessivePower != null) {
8967 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008968 }
8969 return null;
8970 }
8971
Dianne Hackborn287952c2010-09-22 22:34:31 -07008972 public void addExcessiveCpu(long overTime, long usedTime) {
8973 if (mExcessivePower == null) {
8974 mExcessivePower = new ArrayList<ExcessivePower>();
8975 }
8976 ExcessivePower ew = new ExcessivePower();
8977 ew.type = ExcessivePower.TYPE_CPU;
8978 ew.overTime = overTime;
8979 ew.usedTime = usedTime;
8980 mExcessivePower.add(ew);
8981 }
8982
8983 void writeExcessivePowerToParcelLocked(Parcel out) {
8984 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008985 out.writeInt(0);
8986 return;
8987 }
8988
Dianne Hackborn287952c2010-09-22 22:34:31 -07008989 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008990 out.writeInt(N);
8991 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008992 ExcessivePower ew = mExcessivePower.get(i);
8993 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008994 out.writeLong(ew.overTime);
8995 out.writeLong(ew.usedTime);
8996 }
8997 }
8998
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07008999 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009000 final int N = in.readInt();
9001 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009002 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009003 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009004 }
9005
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009006 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009007 throw new ParcelFormatException(
9008 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009009 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009010
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009011 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009012 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009013 ExcessivePower ew = new ExcessivePower();
9014 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009015 ew.overTime = in.readLong();
9016 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009017 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009018 }
9019 }
9020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009021 void writeToParcelLocked(Parcel out) {
9022 out.writeLong(mUserTime);
9023 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009024 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009026 out.writeInt(mNumCrashes);
9027 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 out.writeLong(mLoadedUserTime);
9029 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009030 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009032 out.writeInt(mLoadedNumCrashes);
9033 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009034 out.writeLong(mUnpluggedUserTime);
9035 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009036 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009037 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009038 out.writeInt(mUnpluggedNumCrashes);
9039 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009040 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009041 }
9042
9043 void readFromParcelLocked(Parcel in) {
9044 mUserTime = in.readLong();
9045 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009046 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009047 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009048 mNumCrashes = in.readInt();
9049 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009050 mLoadedUserTime = in.readLong();
9051 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009052 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009053 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009054 mLoadedNumCrashes = in.readInt();
9055 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009056 mUnpluggedUserTime = in.readLong();
9057 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009058 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009059 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009060 mUnpluggedNumCrashes = in.readInt();
9061 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009062 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009063 }
9064
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009065 public void addCpuTimeLocked(int utime, int stime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009066 mUserTime += utime;
9067 mSystemTime += stime;
9068 }
9069
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009070 public void addForegroundTimeLocked(long ttime) {
9071 mForegroundTime += ttime;
9072 }
9073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009074 public void incStartsLocked() {
9075 mStarts++;
9076 }
9077
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009078 public void incNumCrashesLocked() {
9079 mNumCrashes++;
9080 }
9081
9082 public void incNumAnrsLocked() {
9083 mNumAnrs++;
9084 }
9085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009086 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009087 public boolean isActive() {
9088 return mActive;
9089 }
9090
9091 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009093 long val = mUserTime;
9094 if (which == STATS_CURRENT) {
9095 val -= mLoadedUserTime;
9096 } else if (which == STATS_SINCE_UNPLUGGED) {
9097 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009098 }
9099 return val;
9100 }
9101
9102 @Override
9103 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009104 long val = mSystemTime;
9105 if (which == STATS_CURRENT) {
9106 val -= mLoadedSystemTime;
9107 } else if (which == STATS_SINCE_UNPLUGGED) {
9108 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 }
9110 return val;
9111 }
9112
9113 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009114 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009115 long val = mForegroundTime;
9116 if (which == STATS_CURRENT) {
9117 val -= mLoadedForegroundTime;
9118 } else if (which == STATS_SINCE_UNPLUGGED) {
9119 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009120 }
9121 return val;
9122 }
9123
9124 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009125 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009126 int val = mStarts;
9127 if (which == STATS_CURRENT) {
9128 val -= mLoadedStarts;
9129 } else if (which == STATS_SINCE_UNPLUGGED) {
9130 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009131 }
9132 return val;
9133 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009134
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009135 @Override
9136 public int getNumCrashes(int which) {
9137 int val = mNumCrashes;
9138 if (which == STATS_CURRENT) {
9139 val -= mLoadedNumCrashes;
9140 } else if (which == STATS_SINCE_UNPLUGGED) {
9141 val -= mUnpluggedNumCrashes;
9142 }
9143 return val;
9144 }
9145
9146 @Override
9147 public int getNumAnrs(int which) {
9148 int val = mNumAnrs;
9149 if (which == STATS_CURRENT) {
9150 val -= mLoadedNumAnrs;
9151 } else if (which == STATS_SINCE_UNPLUGGED) {
9152 val -= mUnpluggedNumAnrs;
9153 }
9154 return val;
9155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009156 }
9157
9158 /**
9159 * The statistics associated with a particular package.
9160 */
Joe Onoratoabded112016-02-08 16:49:39 -08009161 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9162 /**
9163 * BatteryStatsImpl that we are associated with.
9164 */
9165 protected BatteryStatsImpl mBsi;
9166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009167 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009168 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009169 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009170 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009171 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009172
9173 /**
9174 * The statics we have collected for this package's services.
9175 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009176 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009177
Joe Onoratoabded112016-02-08 16:49:39 -08009178 public Pkg(BatteryStatsImpl bsi) {
9179 mBsi = bsi;
9180 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009182
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009183 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009184 }
9185
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009186 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009187 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009188
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009189 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009190 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009191 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009194 int numWA = in.readInt();
9195 mWakeupAlarms.clear();
9196 for (int i=0; i<numWA; i++) {
9197 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009198 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009200
9201 int numServs = in.readInt();
9202 mServiceStats.clear();
9203 for (int m = 0; m < numServs; m++) {
9204 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009205 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009206 mServiceStats.put(serviceName, serv);
9207
9208 serv.readFromParcelLocked(in);
9209 }
9210 }
9211
9212 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009213 int numWA = mWakeupAlarms.size();
9214 out.writeInt(numWA);
9215 for (int i=0; i<numWA; i++) {
9216 out.writeString(mWakeupAlarms.keyAt(i));
9217 mWakeupAlarms.valueAt(i).writeToParcel(out);
9218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009219
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009220 final int NS = mServiceStats.size();
9221 out.writeInt(NS);
9222 for (int i=0; i<NS; i++) {
9223 out.writeString(mServiceStats.keyAt(i));
9224 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009225 serv.writeToParcelLocked(out);
9226 }
9227 }
9228
9229 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009230 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9231 return mWakeupAlarms;
9232 }
9233
9234 public void noteWakeupAlarmLocked(String tag) {
9235 Counter c = mWakeupAlarms.get(tag);
9236 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009237 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009238 mWakeupAlarms.put(tag, c);
9239 }
9240 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009241 }
9242
9243 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009244 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9245 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009246 }
9247
9248 /**
9249 * The statistics associated with a particular service.
9250 */
Joe Onoratoabded112016-02-08 16:49:39 -08009251 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9252 /**
9253 * BatteryStatsImpl that we are associated with.
9254 */
9255 protected BatteryStatsImpl mBsi;
9256
9257 /**
9258 * The android package in which this service resides.
9259 */
9260 protected Pkg mPkg;
9261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009262 /**
9263 * Total time (ms in battery uptime) the service has been left started.
9264 */
Joe Onoratoabded112016-02-08 16:49:39 -08009265 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266
9267 /**
9268 * If service has been started and not yet stopped, this is
9269 * when it was started.
9270 */
Joe Onoratoabded112016-02-08 16:49:39 -08009271 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009272
9273 /**
9274 * True if we are currently running.
9275 */
Joe Onoratoabded112016-02-08 16:49:39 -08009276 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009277
9278 /**
9279 * Total number of times startService() has been called.
9280 */
Joe Onoratoabded112016-02-08 16:49:39 -08009281 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009282
9283 /**
9284 * Total time (ms in battery uptime) the service has been left launched.
9285 */
Joe Onoratoabded112016-02-08 16:49:39 -08009286 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009287
9288 /**
9289 * If service has been launched and not yet exited, this is
9290 * when it was launched (ms in battery uptime).
9291 */
Joe Onoratoabded112016-02-08 16:49:39 -08009292 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009293
9294 /**
9295 * True if we are currently launched.
9296 */
Joe Onoratoabded112016-02-08 16:49:39 -08009297 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009298
9299 /**
9300 * Total number times the service has been launched.
9301 */
Joe Onoratoabded112016-02-08 16:49:39 -08009302 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303
9304 /**
9305 * The amount of time spent started loaded from a previous save
9306 * (ms in battery uptime).
9307 */
Joe Onoratoabded112016-02-08 16:49:39 -08009308 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009309
9310 /**
9311 * The number of starts loaded from a previous save.
9312 */
Joe Onoratoabded112016-02-08 16:49:39 -08009313 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009314
9315 /**
9316 * The number of launches loaded from a previous save.
9317 */
Joe Onoratoabded112016-02-08 16:49:39 -08009318 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009319
9320 /**
9321 * The amount of time spent started as of the last run (ms
9322 * in battery uptime).
9323 */
Joe Onoratoabded112016-02-08 16:49:39 -08009324 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009325
9326 /**
9327 * The number of starts as of the last run.
9328 */
Joe Onoratoabded112016-02-08 16:49:39 -08009329 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009330
9331 /**
9332 * The number of launches as of the last run.
9333 */
Joe Onoratoabded112016-02-08 16:49:39 -08009334 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009335
9336 /**
9337 * The amount of time spent started when last unplugged (ms
9338 * in battery uptime).
9339 */
Joe Onoratoabded112016-02-08 16:49:39 -08009340 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009341
9342 /**
9343 * The number of starts when last unplugged.
9344 */
Joe Onoratoabded112016-02-08 16:49:39 -08009345 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346
9347 /**
9348 * The number of launches when last unplugged.
9349 */
Joe Onoratoabded112016-02-08 16:49:39 -08009350 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009351
Joe Onoratoabded112016-02-08 16:49:39 -08009352 /**
9353 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9354 */
9355 public Serv(BatteryStatsImpl bsi) {
9356 mBsi = bsi;
9357 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009358 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009359
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009360 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9361 long baseRealtime) {
9362 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009363 mUnpluggedStarts = mStarts;
9364 mUnpluggedLaunches = mLaunches;
9365 }
9366
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009367 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9368 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009369 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009370
Joe Onoratoabded112016-02-08 16:49:39 -08009371 /**
9372 * Remove this Serv as a listener from the time base.
9373 */
9374 public void detach() {
9375 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009376 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009377
Joe Onoratoabded112016-02-08 16:49:39 -08009378 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009379 mStartTime = in.readLong();
9380 mRunningSince = in.readLong();
9381 mRunning = in.readInt() != 0;
9382 mStarts = in.readInt();
9383 mLaunchedTime = in.readLong();
9384 mLaunchedSince = in.readLong();
9385 mLaunched = in.readInt() != 0;
9386 mLaunches = in.readInt();
9387 mLoadedStartTime = in.readLong();
9388 mLoadedStarts = in.readInt();
9389 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009390 mLastStartTime = 0;
9391 mLastStarts = 0;
9392 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009393 mUnpluggedStartTime = in.readLong();
9394 mUnpluggedStarts = in.readInt();
9395 mUnpluggedLaunches = in.readInt();
9396 }
9397
Joe Onoratoabded112016-02-08 16:49:39 -08009398 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009399 out.writeLong(mStartTime);
9400 out.writeLong(mRunningSince);
9401 out.writeInt(mRunning ? 1 : 0);
9402 out.writeInt(mStarts);
9403 out.writeLong(mLaunchedTime);
9404 out.writeLong(mLaunchedSince);
9405 out.writeInt(mLaunched ? 1 : 0);
9406 out.writeInt(mLaunches);
9407 out.writeLong(mLoadedStartTime);
9408 out.writeInt(mLoadedStarts);
9409 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009410 out.writeLong(mUnpluggedStartTime);
9411 out.writeInt(mUnpluggedStarts);
9412 out.writeInt(mUnpluggedLaunches);
9413 }
9414
Joe Onoratoabded112016-02-08 16:49:39 -08009415 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009416 if (!mLaunched) return mLaunchedTime;
9417 return mLaunchedTime + batteryUptime - mLaunchedSince;
9418 }
9419
Joe Onoratoabded112016-02-08 16:49:39 -08009420 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009421 if (!mRunning) return mStartTime;
9422 return mStartTime + batteryUptime - mRunningSince;
9423 }
9424
9425 public void startLaunchedLocked() {
9426 if (!mLaunched) {
9427 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009428 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009429 mLaunched = true;
9430 }
9431 }
9432
9433 public void stopLaunchedLocked() {
9434 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009435 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436 if (time > 0) {
9437 mLaunchedTime += time;
9438 } else {
9439 mLaunches--;
9440 }
9441 mLaunched = false;
9442 }
9443 }
9444
9445 public void startRunningLocked() {
9446 if (!mRunning) {
9447 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009448 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009449 mRunning = true;
9450 }
9451 }
9452
9453 public void stopRunningLocked() {
9454 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009455 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009456 if (time > 0) {
9457 mStartTime += time;
9458 } else {
9459 mStarts--;
9460 }
9461 mRunning = false;
9462 }
9463 }
9464
9465 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009466 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009467 }
9468
9469 @Override
9470 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009471 int val = mLaunches;
9472 if (which == STATS_CURRENT) {
9473 val -= mLoadedLaunches;
9474 } else if (which == STATS_SINCE_UNPLUGGED) {
9475 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009477 return val;
9478 }
9479
9480 @Override
9481 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009482 long val = getStartTimeToNowLocked(now);
9483 if (which == STATS_CURRENT) {
9484 val -= mLoadedStartTime;
9485 } else if (which == STATS_SINCE_UNPLUGGED) {
9486 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009488 return val;
9489 }
9490
9491 @Override
9492 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009493 int val = mStarts;
9494 if (which == STATS_CURRENT) {
9495 val -= mLoadedStarts;
9496 } else if (which == STATS_SINCE_UNPLUGGED) {
9497 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009498 }
9499
9500 return val;
9501 }
9502 }
9503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009504 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009505 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009506 }
9507 }
9508
9509 /**
9510 * Retrieve the statistics object for a particular process, creating
9511 * if needed.
9512 */
9513 public Proc getProcessStatsLocked(String name) {
9514 Proc ps = mProcessStats.get(name);
9515 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009516 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009517 mProcessStats.put(name, ps);
9518 }
9519
9520 return ps;
9521 }
9522
Dianne Hackborna8d10942015-11-19 17:55:19 -08009523 public void updateUidProcessStateLocked(int procState) {
9524 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009525 // Make special note of Foreground Services
9526 final boolean userAwareService =
9527 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009528 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009529
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009530 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9531 return;
9532 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009533
Bookatz867c0d72017-03-07 18:23:42 -08009534 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009535 if (mProcessState != uidRunningState) {
9536 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009537
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009538 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9539 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009540
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009541 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009542 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009543 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9544 mBsi.mOnBatteryTimeBase.isRunning(),
9545 mBsi.mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009546 }
9547 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9548 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9549 mBsi.mPendingUids.put(mUid, mProcessState);
9550 }
9551 } else {
9552 mBsi.mPendingUids.clear();
9553 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009554 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009555 mProcessState = uidRunningState;
9556 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9557 if (mProcessStateTimer[uidRunningState] == null) {
9558 makeProcessState(uidRunningState, null);
9559 }
9560 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9561 }
9562
9563 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9564 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009565 }
Bookatz867c0d72017-03-07 18:23:42 -08009566
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009567 if (userAwareService != mInForegroundService) {
9568 if (userAwareService) {
9569 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9570 } else {
9571 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9572 }
9573 mInForegroundService = userAwareService;
9574 }
Bookatz867c0d72017-03-07 18:23:42 -08009575 }
9576
Bookatzc8c44962017-05-11 12:12:54 -07009577 /** Whether to consider Uid to be in the background for background timebase purposes. */
9578 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009579 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9580 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009581 return mProcessState >= PROCESS_STATE_BACKGROUND;
9582 }
9583
9584 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9585 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9586 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9587 }
9588
9589 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9590 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9591 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009592 }
9593
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009594 public SparseArray<? extends Pid> getPidStats() {
9595 return mPids;
9596 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009597
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009598 public Pid getPidStatsLocked(int pid) {
9599 Pid p = mPids.get(pid);
9600 if (p == null) {
9601 p = new Pid();
9602 mPids.put(pid, p);
9603 }
9604 return p;
9605 }
9606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009607 /**
9608 * Retrieve the statistics object for a particular service, creating
9609 * if needed.
9610 */
9611 public Pkg getPackageStatsLocked(String name) {
9612 Pkg ps = mPackageStats.get(name);
9613 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009614 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009615 mPackageStats.put(name, ps);
9616 }
9617
9618 return ps;
9619 }
9620
9621 /**
9622 * Retrieve the statistics object for a particular service, creating
9623 * if needed.
9624 */
9625 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9626 Pkg ps = getPackageStatsLocked(pkg);
9627 Pkg.Serv ss = ps.mServiceStats.get(serv);
9628 if (ss == null) {
9629 ss = ps.newServiceStatsLocked();
9630 ps.mServiceStats.put(serv, ss);
9631 }
9632
9633 return ss;
9634 }
9635
Dianne Hackbornd953c532014-08-16 18:17:38 -07009636 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009637 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009638 timer.readSummaryFromParcelLocked(in);
9639 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009640 }
9641
Dianne Hackbornd953c532014-08-16 18:17:38 -07009642 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009643 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009644 timer.readSummaryFromParcelLocked(in);
9645 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009646 }
9647
Dianne Hackbornd953c532014-08-16 18:17:38 -07009648 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009649 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009650 mWakelockStats.add(wlName, wl);
9651 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009652 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009653 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009654 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009655 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009656 }
9657 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009658 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009659 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009660 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009661 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009663 }
9664
Bookatz867c0d72017-03-07 18:23:42 -08009665 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009666 Sensor se = mSensorStats.get(sensor);
9667 if (se == null) {
9668 if (!create) {
9669 return null;
9670 }
Joe Onoratoabded112016-02-08 16:49:39 -08009671 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009672 mSensorStats.put(sensor, se);
9673 }
Bookatz867c0d72017-03-07 18:23:42 -08009674 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009675 if (t != null) {
9676 return t;
9677 }
Joe Onoratoabded112016-02-08 16:49:39 -08009678 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009680 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009681 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009682 }
Bookatz867c0d72017-03-07 18:23:42 -08009683 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9684 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009685 se.mTimer = t;
9686 return t;
9687 }
9688
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009689 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009690 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009691 if (t != null) {
9692 t.startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08009693 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name, 1);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009694 }
9695 }
9696
9697 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009698 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009699 if (t != null) {
9700 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009701 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08009702 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07009703 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009704 }
9705 }
9706
9707 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009708 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009709 if (t != null) {
9710 t.startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08009711 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
9712 name, 1);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009713 }
9714 }
9715
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009716 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07009717 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009718 if (t != null) {
9719 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009720 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08009721 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
9722 name, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07009723 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009724 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009725 if (mBsi.mOnBatteryTimeBase.isRunning()) {
9726 SparseIntArray types = mJobCompletions.get(name);
9727 if (types == null) {
9728 types = new SparseIntArray();
9729 mJobCompletions.put(name, types);
9730 }
9731 int last = types.get(stopReason, 0);
9732 types.put(stopReason, last + 1);
9733 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009734 }
9735
Bookatz5b5ec322017-05-26 09:40:38 -07009736 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
9737 if (wl == null) {
9738 return null;
9739 }
9740 switch (type) {
9741 case WAKE_TYPE_PARTIAL: {
9742 DualTimer t = wl.mTimerPartial;
9743 if (t == null) {
9744 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
9745 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
9746 mOnBatteryScreenOffBackgroundTimeBase);
9747 wl.mTimerPartial = t;
9748 }
9749 return t;
9750 }
9751 case WAKE_TYPE_FULL: {
9752 StopwatchTimer t = wl.mTimerFull;
9753 if (t == null) {
9754 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
9755 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
9756 wl.mTimerFull = t;
9757 }
9758 return t;
9759 }
9760 case WAKE_TYPE_WINDOW: {
9761 StopwatchTimer t = wl.mTimerWindow;
9762 if (t == null) {
9763 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
9764 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
9765 wl.mTimerWindow = t;
9766 }
9767 return t;
9768 }
9769 case WAKE_TYPE_DRAW: {
9770 StopwatchTimer t = wl.mTimerDraw;
9771 if (t == null) {
9772 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
9773 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
9774 wl.mTimerDraw = t;
9775 }
9776 return t;
9777 }
9778 default:
9779 throw new IllegalArgumentException("type=" + type);
9780 }
9781 }
9782
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009783 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009784 Wakelock wl = mWakelockStats.startObject(name);
9785 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07009786 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009787 }
Bookatzc8c44962017-05-11 12:12:54 -07009788 if (type == WAKE_TYPE_PARTIAL) {
9789 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
9790 if (pid >= 0) {
9791 Pid p = getPidStatsLocked(pid);
9792 if (p.mWakeNesting++ == 0) {
9793 p.mWakeStartMs = elapsedRealtimeMs;
9794 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -07009795 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009797 }
9798
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009799 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009800 Wakelock wl = mWakelockStats.stopObject(name);
9801 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -07009802 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
9803 wlt.stopRunningLocked(elapsedRealtimeMs);
9804 if (!wlt.isRunningLocked()) { // only tell statsd if truly stopped
Bookatzd6746242017-10-24 18:39:35 -07009805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009806 }
Bookatzc8c44962017-05-11 12:12:54 -07009807 if (type == WAKE_TYPE_PARTIAL) {
9808 if (mAggregatedPartialWakelockTimer != null) {
9809 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
9810 }
9811 if (pid >= 0) {
9812 Pid p = mPids.get(pid);
9813 if (p != null && p.mWakeNesting > 0) {
9814 if (p.mWakeNesting-- == 1) {
9815 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
9816 p.mWakeStartMs = 0;
9817 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08009818 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009819 }
9820 }
9821 }
9822
Dianne Hackborn287952c2010-09-22 22:34:31 -07009823 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
9824 Proc p = getProcessStatsLocked(proc);
9825 if (p != null) {
9826 p.addExcessiveCpu(overTime, usedTime);
9827 }
9828 }
9829
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009830 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009831 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -08009832 t.startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009833 if (sensor == Sensor.GPS) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08009834 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, getUid(), null, 1);
Bookatzc1a050a2017-10-10 15:49:28 -07009835 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08009836 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null, sensor,
9837 1);
Bookatzc1a050a2017-10-10 15:49:28 -07009838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009839 }
9840
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009841 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009842 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -08009843 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009844 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009845 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009846 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Bookatzc1a050a2017-10-10 15:49:28 -07009847 if (sensor == Sensor.GPS) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08009848 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, getUid(), null,
9849 0);
Bookatzc1a050a2017-10-10 15:49:28 -07009850 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08009851 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null,
9852 sensor, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07009853 }
9854 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009856 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009857
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009858 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009859 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009860 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009861
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009862 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009863 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009864 }
9865
9866 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009867 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009868 }
9869 }
9870
Sudheer Shanka9b735c52017-05-09 18:26:18 -07009871 public long[] getCpuFreqs() {
9872 return mCpuFreqs;
9873 }
9874
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009875 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
9876 UserInfoProvider userInfoProvider) {
9877 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009878 }
9879
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009880 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
9881 PlatformIdleStateCallback cb,
9882 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -08009883 init(clocks);
9884
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009885 if (systemDir != null) {
9886 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
9887 new File(systemDir, "batterystats.bin.tmp"));
9888 } else {
9889 mFile = null;
9890 }
9891 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009892 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -08009893 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009894 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009895 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -08009896 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -07009897 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07009898 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009899 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009900 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009901 }
Joe Onoratoabded112016-02-08 16:49:39 -08009902 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
9903 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
9904 mOnBatteryTimeBase);
9905 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
9906 mOnBatteryTimeBase);
9907 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
9908 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
9909 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
9910 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
9911 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
9912 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
9913 mOnBatteryTimeBase);
9914 }
9915 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
9916 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009917 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009918 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009919 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009920 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009921 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009922 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
9923 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009924 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009925 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
9926 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
9927 NUM_BT_TX_LEVELS);
9928 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
9929 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -08009930 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
9931 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
9932 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009933 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009934 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
9935 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08009936 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
9937 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08009938 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
9939 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08009940 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009941 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -07009942 mOnBatteryTimeBase);
9943 }
Joe Onoratoabded112016-02-08 16:49:39 -08009944 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9945 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
9946 mOnBatteryTimeBase);
9947 }
9948 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9949 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
9950 mOnBatteryTimeBase);
9951 }
Siddharth Rayb50a6842017-12-14 15:15:28 -08009952 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08009953 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
9954 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
9955 mOnBatteryTimeBase);
9956 }
Joe Onoratoabded112016-02-08 16:49:39 -08009957 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
9958 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
9959 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
9960 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
9961 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009962 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -07009963 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -08009964 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
9965 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009966 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009967 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009968 long uptime = mClocks.uptimeMillis() * 1000;
9969 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009970 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009971 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -07009972 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009973 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009974 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -07009975 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009976 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009977 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009978 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009979 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009980 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009981 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009982 }
9983
9984 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -08009985 this(new SystemClocks(), p);
9986 }
9987
9988 public BatteryStatsImpl(Clocks clocks, Parcel p) {
9989 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07009990 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009991 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009992 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07009993 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009994 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009995 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009996 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009997 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009998 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009999 }
10000
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010001 public void setPowerProfileLocked(PowerProfile profile) {
10002 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010003
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010004 // We need to initialize the KernelCpuSpeedReaders to read from
10005 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10006 // information.
10007 final int numClusters = mPowerProfile.getNumCpuClusters();
10008 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10009 int firstCpuOfCluster = 0;
10010 for (int i = 0; i < numClusters; i++) {
10011 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10012 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10013 numSpeedSteps);
10014 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10015 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010016
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010017 if (mEstimatedBatteryCapacity == -1) {
10018 // Initialize the estimated battery capacity to a known preset one.
10019 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010020 }
10021 }
10022
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010023 public void setCallback(BatteryCallback cb) {
10024 mCallback = cb;
10025 }
10026
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010027 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010028 if (mPhoneSignalScanningTimer != null) {
10029 mPhoneSignalScanningTimer.setTimeout(timeout);
10030 }
10031 }
10032
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010033 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10034 mExternalSync = sync;
10035 }
10036
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010037 public void updateDailyDeadlineLocked() {
10038 // Get the current time.
10039 long currentTime = mDailyStartTime = System.currentTimeMillis();
10040 Calendar calDeadline = Calendar.getInstance();
10041 calDeadline.setTimeInMillis(currentTime);
10042
10043 // Move time up to the next day, ranging from 1am to 3pm.
10044 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10045 calDeadline.set(Calendar.MILLISECOND, 0);
10046 calDeadline.set(Calendar.SECOND, 0);
10047 calDeadline.set(Calendar.MINUTE, 0);
10048 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10049 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10050 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10051 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10052 }
10053
10054 public void recordDailyStatsIfNeededLocked(boolean settled) {
10055 long currentTime = System.currentTimeMillis();
10056 if (currentTime >= mNextMaxDailyDeadline) {
10057 recordDailyStatsLocked();
10058 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10059 recordDailyStatsLocked();
10060 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10061 recordDailyStatsLocked();
10062 }
10063 }
10064
10065 public void recordDailyStatsLocked() {
10066 DailyItem item = new DailyItem();
10067 item.mStartTime = mDailyStartTime;
10068 item.mEndTime = System.currentTimeMillis();
10069 boolean hasData = false;
10070 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10071 hasData = true;
10072 item.mDischargeSteps = new LevelStepTracker(
10073 mDailyDischargeStepTracker.mNumStepDurations,
10074 mDailyDischargeStepTracker.mStepDurations);
10075 }
10076 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10077 hasData = true;
10078 item.mChargeSteps = new LevelStepTracker(
10079 mDailyChargeStepTracker.mNumStepDurations,
10080 mDailyChargeStepTracker.mStepDurations);
10081 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010082 if (mDailyPackageChanges != null) {
10083 hasData = true;
10084 item.mPackageChanges = mDailyPackageChanges;
10085 mDailyPackageChanges = null;
10086 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010087 mDailyDischargeStepTracker.init();
10088 mDailyChargeStepTracker.init();
10089 updateDailyDeadlineLocked();
10090
10091 if (hasData) {
10092 mDailyItems.add(item);
10093 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10094 mDailyItems.remove(0);
10095 }
10096 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10097 try {
10098 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010099 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010100 writeDailyItemsLocked(out);
10101 BackgroundThread.getHandler().post(new Runnable() {
10102 @Override
10103 public void run() {
10104 synchronized (mCheckinFile) {
10105 FileOutputStream stream = null;
10106 try {
10107 stream = mDailyFile.startWrite();
10108 memStream.writeTo(stream);
10109 stream.flush();
10110 FileUtils.sync(stream);
10111 stream.close();
10112 mDailyFile.finishWrite(stream);
10113 } catch (IOException e) {
10114 Slog.w("BatteryStats",
10115 "Error writing battery daily items", e);
10116 mDailyFile.failWrite(stream);
10117 }
10118 }
10119 }
10120 });
10121 } catch (IOException e) {
10122 }
10123 }
10124 }
10125
10126 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10127 StringBuilder sb = new StringBuilder(64);
10128 out.startDocument(null, true);
10129 out.startTag(null, "daily-items");
10130 for (int i=0; i<mDailyItems.size(); i++) {
10131 final DailyItem dit = mDailyItems.get(i);
10132 out.startTag(null, "item");
10133 out.attribute(null, "start", Long.toString(dit.mStartTime));
10134 out.attribute(null, "end", Long.toString(dit.mEndTime));
10135 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10136 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010137 if (dit.mPackageChanges != null) {
10138 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10139 PackageChange pc = dit.mPackageChanges.get(j);
10140 if (pc.mUpdate) {
10141 out.startTag(null, "upd");
10142 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010143 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010144 out.endTag(null, "upd");
10145 } else {
10146 out.startTag(null, "rem");
10147 out.attribute(null, "pkg", pc.mPackageName);
10148 out.endTag(null, "rem");
10149 }
10150 }
10151 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010152 out.endTag(null, "item");
10153 }
10154 out.endTag(null, "daily-items");
10155 out.endDocument();
10156 }
10157
10158 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10159 StringBuilder tmpBuilder) throws IOException {
10160 if (steps != null) {
10161 out.startTag(null, tag);
10162 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10163 for (int i=0; i<steps.mNumStepDurations; i++) {
10164 out.startTag(null, "s");
10165 tmpBuilder.setLength(0);
10166 steps.encodeEntryAt(i, tmpBuilder);
10167 out.attribute(null, "v", tmpBuilder.toString());
10168 out.endTag(null, "s");
10169 }
10170 out.endTag(null, tag);
10171 }
10172 }
10173
10174 public void readDailyStatsLocked() {
10175 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10176 mDailyItems.clear();
10177 FileInputStream stream;
10178 try {
10179 stream = mDailyFile.openRead();
10180 } catch (FileNotFoundException e) {
10181 return;
10182 }
10183 try {
10184 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010185 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010186 readDailyItemsLocked(parser);
10187 } catch (XmlPullParserException e) {
10188 } finally {
10189 try {
10190 stream.close();
10191 } catch (IOException e) {
10192 }
10193 }
10194 }
10195
10196 private void readDailyItemsLocked(XmlPullParser parser) {
10197 try {
10198 int type;
10199 while ((type = parser.next()) != XmlPullParser.START_TAG
10200 && type != XmlPullParser.END_DOCUMENT) {
10201 ;
10202 }
10203
10204 if (type != XmlPullParser.START_TAG) {
10205 throw new IllegalStateException("no start tag found");
10206 }
10207
10208 int outerDepth = parser.getDepth();
10209 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10210 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10211 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10212 continue;
10213 }
10214
10215 String tagName = parser.getName();
10216 if (tagName.equals("item")) {
10217 readDailyItemTagLocked(parser);
10218 } else {
10219 Slog.w(TAG, "Unknown element under <daily-items>: "
10220 + parser.getName());
10221 XmlUtils.skipCurrentTag(parser);
10222 }
10223 }
10224
10225 } catch (IllegalStateException e) {
10226 Slog.w(TAG, "Failed parsing daily " + e);
10227 } catch (NullPointerException e) {
10228 Slog.w(TAG, "Failed parsing daily " + e);
10229 } catch (NumberFormatException e) {
10230 Slog.w(TAG, "Failed parsing daily " + e);
10231 } catch (XmlPullParserException e) {
10232 Slog.w(TAG, "Failed parsing daily " + e);
10233 } catch (IOException e) {
10234 Slog.w(TAG, "Failed parsing daily " + e);
10235 } catch (IndexOutOfBoundsException e) {
10236 Slog.w(TAG, "Failed parsing daily " + e);
10237 }
10238 }
10239
10240 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10241 XmlPullParserException, IOException {
10242 DailyItem dit = new DailyItem();
10243 String attr = parser.getAttributeValue(null, "start");
10244 if (attr != null) {
10245 dit.mStartTime = Long.parseLong(attr);
10246 }
10247 attr = parser.getAttributeValue(null, "end");
10248 if (attr != null) {
10249 dit.mEndTime = Long.parseLong(attr);
10250 }
10251 int outerDepth = parser.getDepth();
10252 int type;
10253 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10254 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10255 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10256 continue;
10257 }
10258
10259 String tagName = parser.getName();
10260 if (tagName.equals("dis")) {
10261 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10262 } else if (tagName.equals("chg")) {
10263 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010264 } else if (tagName.equals("upd")) {
10265 if (dit.mPackageChanges == null) {
10266 dit.mPackageChanges = new ArrayList<>();
10267 }
10268 PackageChange pc = new PackageChange();
10269 pc.mUpdate = true;
10270 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10271 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010272 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010273 dit.mPackageChanges.add(pc);
10274 XmlUtils.skipCurrentTag(parser);
10275 } else if (tagName.equals("rem")) {
10276 if (dit.mPackageChanges == null) {
10277 dit.mPackageChanges = new ArrayList<>();
10278 }
10279 PackageChange pc = new PackageChange();
10280 pc.mUpdate = false;
10281 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10282 dit.mPackageChanges.add(pc);
10283 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010284 } else {
10285 Slog.w(TAG, "Unknown element under <item>: "
10286 + parser.getName());
10287 XmlUtils.skipCurrentTag(parser);
10288 }
10289 }
10290 mDailyItems.add(dit);
10291 }
10292
10293 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10294 String tag)
10295 throws NumberFormatException, XmlPullParserException, IOException {
10296 final String numAttr = parser.getAttributeValue(null, "n");
10297 if (numAttr == null) {
10298 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10299 XmlUtils.skipCurrentTag(parser);
10300 return;
10301 }
10302 final int num = Integer.parseInt(numAttr);
10303 LevelStepTracker steps = new LevelStepTracker(num);
10304 if (isCharge) {
10305 dit.mChargeSteps = steps;
10306 } else {
10307 dit.mDischargeSteps = steps;
10308 }
10309 int i = 0;
10310 int outerDepth = parser.getDepth();
10311 int type;
10312 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10313 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10314 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10315 continue;
10316 }
10317
10318 String tagName = parser.getName();
10319 if ("s".equals(tagName)) {
10320 if (i < num) {
10321 String valueAttr = parser.getAttributeValue(null, "v");
10322 if (valueAttr != null) {
10323 steps.decodeEntryAt(i, valueAttr);
10324 i++;
10325 }
10326 }
10327 } else {
10328 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10329 + parser.getName());
10330 XmlUtils.skipCurrentTag(parser);
10331 }
10332 }
10333 steps.mNumStepDurations = i;
10334 }
10335
10336 @Override
10337 public DailyItem getDailyItemLocked(int daysAgo) {
10338 int index = mDailyItems.size()-1-daysAgo;
10339 return index >= 0 ? mDailyItems.get(index) : null;
10340 }
10341
10342 @Override
10343 public long getCurrentDailyStartTime() {
10344 return mDailyStartTime;
10345 }
10346
10347 @Override
10348 public long getNextMinDailyDeadline() {
10349 return mNextMinDailyDeadline;
10350 }
10351
10352 @Override
10353 public long getNextMaxDailyDeadline() {
10354 return mNextMaxDailyDeadline;
10355 }
10356
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010357 @Override
10358 public boolean startIteratingOldHistoryLocked() {
10359 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10360 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010361 if ((mHistoryIterator = mHistory) == null) {
10362 return false;
10363 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010364 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010365 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010366 mReadOverflow = false;
10367 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010368 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010369 }
10370
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010371 @Override
10372 public boolean getNextOldHistoryLocked(HistoryItem out) {
10373 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10374 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010375 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010376 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010377 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010378 HistoryItem cur = mHistoryIterator;
10379 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010380 if (!mReadOverflow && !end) {
10381 Slog.w(TAG, "Old history ends before new history!");
10382 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010383 return false;
10384 }
10385 out.setTo(cur);
10386 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010387 if (!mReadOverflow) {
10388 if (end) {
10389 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010390 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010391 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010392 pw.println("Histories differ!");
10393 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010394 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010395 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010396 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10397 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010398 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010399 }
10400 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010401 return true;
10402 }
10403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010404 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010405 public void finishIteratingOldHistoryLocked() {
10406 mIteratingHistory = false;
10407 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010408 mHistoryIterator = null;
10409 }
10410
10411 public int getHistoryTotalSize() {
10412 return MAX_HISTORY_BUFFER;
10413 }
10414
10415 public int getHistoryUsedSize() {
10416 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010417 }
10418
10419 @Override
10420 public boolean startIteratingHistoryLocked() {
10421 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10422 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010423 if (mHistoryBuffer.dataSize() <= 0) {
10424 return false;
10425 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010426 mHistoryBuffer.setDataPosition(0);
10427 mReadOverflow = false;
10428 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010429 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10430 mReadHistoryUids = new int[mHistoryTagPool.size()];
10431 mReadHistoryChars = 0;
10432 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10433 final HistoryTag tag = ent.getKey();
10434 final int idx = ent.getValue();
10435 mReadHistoryStrings[idx] = tag.string;
10436 mReadHistoryUids[idx] = tag.uid;
10437 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010438 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010439 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010440 }
10441
10442 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010443 public int getHistoryStringPoolSize() {
10444 return mReadHistoryStrings.length;
10445 }
10446
10447 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010448 public int getHistoryStringPoolBytes() {
10449 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10450 // Each string character is 2 bytes.
10451 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10452 }
10453
10454 @Override
10455 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010456 return mReadHistoryStrings[index];
10457 }
10458
10459 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010460 public int getHistoryTagPoolUid(int index) {
10461 return mReadHistoryUids[index];
10462 }
10463
10464 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010465 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010466 final int pos = mHistoryBuffer.dataPosition();
10467 if (pos == 0) {
10468 out.clear();
10469 }
10470 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010471 if (end) {
10472 return false;
10473 }
10474
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010475 final long lastRealtime = out.time;
10476 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010477 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010478 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10479 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010480 out.currentTime = lastWalltime + (out.time - lastRealtime);
10481 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010482 return true;
10483 }
10484
10485 @Override
10486 public void finishIteratingHistoryLocked() {
10487 mIteratingHistory = false;
10488 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010489 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010490 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010491
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010492 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010493 public long getHistoryBaseTime() {
10494 return mHistoryBaseTime;
10495 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010496
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010497 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010498 public int getStartCount() {
10499 return mStartCount;
10500 }
10501
10502 public boolean isOnBattery() {
10503 return mOnBattery;
10504 }
10505
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010506 public boolean isCharging() {
10507 return mCharging;
10508 }
10509
Mike Mac2f518a2017-09-19 16:06:03 -070010510 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010511 return state == Display.STATE_ON || state == Display.STATE_VR
10512 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010513 }
10514
10515 public boolean isScreenOff(int state) {
10516 return state == Display.STATE_OFF;
10517 }
10518
10519 public boolean isScreenDoze(int state) {
10520 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010521 }
10522
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010523 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010524 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010525 mOnBatteryTimeBase.init(uptime, realtime);
10526 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010527 mRealtime = 0;
10528 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010529 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010530 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010531 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010532
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010533 void initDischarge() {
10534 mLowDischargeAmountSinceCharge = 0;
10535 mHighDischargeAmountSinceCharge = 0;
10536 mDischargeAmountScreenOn = 0;
10537 mDischargeAmountScreenOnSinceCharge = 0;
10538 mDischargeAmountScreenOff = 0;
10539 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010540 mDischargeAmountScreenDoze = 0;
10541 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010542 mDischargeStepTracker.init();
10543 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010544 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010545 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010546 mDischargeLightDozeCounter.reset(false);
10547 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010548 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010549 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010550
10551 public void resetAllStatsCmdLocked() {
10552 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010553 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010554 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010555 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010556 long realtime = mSecRealtime * 1000;
10557 mDischargeStartLevel = mHistoryCur.batteryLevel;
10558 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010559 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010560 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10561 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010562 mOnBatteryTimeBase.reset(uptime, realtime);
10563 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10564 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010565 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010566 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010567 mDischargeScreenDozeUnplugLevel = 0;
10568 mDischargeScreenOffUnplugLevel = 0;
10569 } else if (isScreenDoze(mScreenState)) {
10570 mDischargeScreenOnUnplugLevel = 0;
10571 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010572 mDischargeScreenOffUnplugLevel = 0;
10573 } else {
10574 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010575 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010576 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10577 }
10578 mDischargeAmountScreenOn = 0;
10579 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010580 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010581 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010582 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010583 }
10584
10585 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010586 final long uptimeMillis = mClocks.uptimeMillis();
10587 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010588 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010589 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010590 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010591 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010592 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010593 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010594 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010595
10596 if (mPowerProfile != null) {
10597 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10598 } else {
10599 mEstimatedBatteryCapacity = -1;
10600 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010601 mMinLearnedBatteryCapacity = -1;
10602 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010603 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010604 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010605 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010606 mLongestLightIdleTime = 0;
10607 mLongestFullIdleTime = 0;
10608 mDeviceIdleModeLightTimer.reset(false);
10609 mDeviceIdleModeFullTimer.reset(false);
10610 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010611 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010612 mPhoneOnTimer.reset(false);
10613 mAudioOnTimer.reset(false);
10614 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010615 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010616 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010617 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010618 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010619 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010620 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010621 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010622 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010623 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010624 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010625 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010626 mNetworkByteActivityCounters[i].reset(false);
10627 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010628 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010629 mMobileRadioActiveTimer.reset(false);
10630 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010631 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010632 mMobileRadioActiveUnknownTime.reset(false);
10633 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010634 mWifiOnTimer.reset(false);
10635 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010636 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010637 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010638 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010639 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10640 mWifiSupplStateTimer[i].reset(false);
10641 }
10642 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10643 mWifiSignalStrengthsTimer[i].reset(false);
10644 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010645 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010646 mWifiActiveTimer.reset(false);
10647 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010648 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10649 mGpsSignalQualityTimer[i].reset(false);
10650 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010651 mBluetoothActivity.reset(false);
10652 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010653 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010654
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010655 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010656 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010657 mUidStats.remove(mUidStats.keyAt(i));
10658 i--;
10659 }
10660 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010661
Bookatz50df7112017-08-04 14:53:26 -070010662 if (mRpmStats.size() > 0) {
10663 for (SamplingTimer timer : mRpmStats.values()) {
10664 mOnBatteryTimeBase.remove(timer);
10665 }
10666 mRpmStats.clear();
10667 }
10668 if (mScreenOffRpmStats.size() > 0) {
10669 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10670 mOnBatteryScreenOffTimeBase.remove(timer);
10671 }
10672 mScreenOffRpmStats.clear();
10673 }
10674
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010675 if (mKernelWakelockStats.size() > 0) {
10676 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010677 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010678 }
10679 mKernelWakelockStats.clear();
10680 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010681
James Carr3a226052016-07-01 14:49:52 -070010682 if (mKernelMemoryStats.size() > 0) {
10683 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10684 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10685 }
10686 mKernelMemoryStats.clear();
10687 }
10688
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010689 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010690 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10691 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010692 }
10693 mWakeupReasonStats.clear();
10694 }
10695
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010696 mLastHistoryStepDetails = null;
10697 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10698 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10699 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10700 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10701 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10702 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10703 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
10704 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
10705 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
10706 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
10707
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010708 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010709
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010710 clearHistoryLocked();
10711 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010712
Dianne Hackborn40c87252014-03-19 16:55:40 -070010713 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010714 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010715 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
10716 // Not recording process starts/stops.
10717 continue;
10718 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010719 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010720 if (active == null) {
10721 continue;
10722 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010723 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
10724 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010725 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070010726 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
10727 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010728 }
10729 }
10730 }
10731 }
10732
Mike Mac2f518a2017-09-19 16:06:03 -070010733 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
10734 updateOldDischargeScreenLevelLocked(oldState);
10735 updateNewDischargeScreenLevelLocked(newState);
10736 }
10737
10738 private void updateOldDischargeScreenLevelLocked(int state) {
10739 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010740 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
10741 if (diff > 0) {
10742 mDischargeAmountScreenOn += diff;
10743 mDischargeAmountScreenOnSinceCharge += diff;
10744 }
Mike Mac2f518a2017-09-19 16:06:03 -070010745 } else if (isScreenDoze(state)) {
10746 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
10747 if (diff > 0) {
10748 mDischargeAmountScreenDoze += diff;
10749 mDischargeAmountScreenDozeSinceCharge += diff;
10750 }
10751 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010752 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
10753 if (diff > 0) {
10754 mDischargeAmountScreenOff += diff;
10755 mDischargeAmountScreenOffSinceCharge += diff;
10756 }
10757 }
Mike Mac2f518a2017-09-19 16:06:03 -070010758 }
10759
10760 private void updateNewDischargeScreenLevelLocked(int state) {
10761 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010762 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
10763 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010764 mDischargeScreenDozeUnplugLevel = 0;
10765 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010766 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010767 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
10768 mDischargeScreenOffUnplugLevel = 0;
10769 } else if (isScreenOff(state)) {
10770 mDischargeScreenOnUnplugLevel = 0;
10771 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010772 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
10773 }
10774 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010775
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010776 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010777 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070010778 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010779 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010780 }
10781
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010782 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
10783 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
10784
10785 private final Object mWifiNetworkLock = new Object();
10786
10787 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010788 private String[] mWifiIfaces = EmptyArray.STRING;
10789
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010790 @GuardedBy("mWifiNetworkLock")
10791 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010792
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010793 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010794
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010795 @GuardedBy("mModemNetworkLock")
10796 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010797
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010798 @GuardedBy("mModemNetworkLock")
10799 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
10800
10801 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
10802 try {
10803 if (!ArrayUtils.isEmpty(ifaces)) {
10804 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
10805 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
10806 }
10807 } catch (IOException e) {
10808 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010809 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010810 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010811 }
10812
10813 /**
10814 * Distribute WiFi energy info and network traffic to apps.
10815 * @param info The energy information from the WiFi controller.
10816 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010817 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010818 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010819 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010820 }
10821
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010822 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070010823 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010824 synchronized (mWifiNetworkLock) {
10825 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
10826 if (latestStats != null) {
10827 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
10828 mNetworkStatsPool.acquire());
10829 mNetworkStatsPool.release(mLastWifiNetworkStats);
10830 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070010831 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010832 }
10833
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010834 synchronized (this) {
10835 if (!mOnBatteryInternal) {
10836 if (delta != null) {
10837 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010838 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010839 return;
10840 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010841
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010842 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
10843 SparseLongArray rxPackets = new SparseLongArray();
10844 SparseLongArray txPackets = new SparseLongArray();
10845 long totalTxPackets = 0;
10846 long totalRxPackets = 0;
10847 if (delta != null) {
10848 NetworkStats.Entry entry = new NetworkStats.Entry();
10849 final int size = delta.size();
10850 for (int i = 0; i < size; i++) {
10851 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010852
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010853 if (DEBUG_ENERGY) {
10854 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
10855 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
10856 + " txPackets=" + entry.txPackets);
10857 }
10858
10859 if (entry.rxBytes == 0 && entry.txBytes == 0) {
10860 // Skip the lookup below since there is no work to do.
10861 continue;
10862 }
10863
10864 final Uid u = getUidStatsLocked(mapUid(entry.uid));
10865 if (entry.rxBytes != 0) {
10866 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080010867 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010868 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10869 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
10870 entry.rxPackets);
10871 }
10872 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
10873 entry.rxBytes);
10874 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
10875 entry.rxPackets);
10876
10877 rxPackets.put(u.getUid(), entry.rxPackets);
10878
10879 // Sum the total number of packets so that the Rx Power can
10880 // be evenly distributed amongst the apps.
10881 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080010882 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010883
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010884 if (entry.txBytes != 0) {
10885 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080010886 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010887 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10888 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
10889 entry.txPackets);
10890 }
10891 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
10892 entry.txBytes);
10893 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
10894 entry.txPackets);
10895
10896 txPackets.put(u.getUid(), entry.txPackets);
10897
10898 // Sum the total number of packets so that the Tx Power can
10899 // be evenly distributed amongst the apps.
10900 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080010901 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080010902 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010903 mNetworkStatsPool.release(delta);
10904 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070010905 }
10906
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010907 if (info != null) {
10908 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070010909
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010910 // Measured in mAms
10911 final long txTimeMs = info.getControllerTxTimeMillis();
10912 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080010913 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010914 final long idleTimeMs = info.getControllerIdleTimeMillis();
10915 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070010916
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010917 long leftOverRxTimeMs = rxTimeMs;
10918 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070010919
Adam Lesinskie08af192015-03-25 16:42:59 -070010920 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010921 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
10922 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
10923 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
10924 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
10925 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080010926 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070010927 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010928
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010929 long totalWifiLockTimeMs = 0;
10930 long totalScanTimeMs = 0;
10931
10932 // On the first pass, collect some totals so that we can normalize power
10933 // calculations if we need to.
10934 final int uidStatsSize = mUidStats.size();
10935 for (int i = 0; i < uidStatsSize; i++) {
10936 final Uid uid = mUidStats.valueAt(i);
10937
10938 // Sum the total scan power for all apps.
10939 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
10940 elapsedRealtimeMs * 1000) / 1000;
10941
10942 // Sum the total time holding wifi lock for all apps.
10943 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
10944 elapsedRealtimeMs * 1000) / 1000;
10945 }
10946
10947 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
10948 Slog.d(TAG,
10949 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
10950 + rxTimeMs + " ms). Normalizing scan time.");
10951 }
10952 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
10953 Slog.d(TAG,
10954 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
10955 + txTimeMs + " ms). Normalizing scan time.");
10956 }
10957
10958 // Actually assign and distribute power usage to apps.
10959 for (int i = 0; i < uidStatsSize; i++) {
10960 final Uid uid = mUidStats.valueAt(i);
10961
10962 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
10963 elapsedRealtimeMs * 1000) / 1000;
10964 if (scanTimeSinceMarkMs > 0) {
10965 // Set the new mark so that next time we get new data since this point.
10966 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
10967
10968 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
10969 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
10970
10971 // Our total scan time is more than the reported Tx/Rx time.
10972 // This is possible because the cost of a scan is approximate.
10973 // Let's normalize the result so that we evenly blame each app
10974 // scanning.
10975 //
10976 // This means that we may have apps that transmitted/received packets not be
10977 // blamed for this, but this is fine as scans are relatively more expensive.
10978 if (totalScanTimeMs > rxTimeMs) {
10979 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
10980 totalScanTimeMs;
10981 }
10982 if (totalScanTimeMs > txTimeMs) {
10983 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
10984 totalScanTimeMs;
10985 }
10986
10987 if (DEBUG_ENERGY) {
10988 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
10989 + scanRxTimeSinceMarkMs + " ms Tx:"
10990 + scanTxTimeSinceMarkMs + " ms)");
10991 }
10992
10993 ControllerActivityCounterImpl activityCounter =
10994 uid.getOrCreateWifiControllerActivityLocked();
10995 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
10996 activityCounter.getTxTimeCounters()[0].addCountLocked(
10997 scanTxTimeSinceMarkMs);
10998 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
10999 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11000 }
11001
11002 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11003 // lock.
11004 final long wifiLockTimeSinceMarkMs =
11005 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11006 elapsedRealtimeMs * 1000) / 1000;
11007 if (wifiLockTimeSinceMarkMs > 0) {
11008 // Set the new mark so that next time we get new data since this point.
11009 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11010
11011 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11012 / totalWifiLockTimeMs;
11013 if (DEBUG_ENERGY) {
11014 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11015 + myIdleTimeMs + " ms");
11016 }
11017 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11018 .addCountLocked(myIdleTimeMs);
11019 }
11020 }
11021
Adam Lesinskie08af192015-03-25 16:42:59 -070011022 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011023 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11024 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011025 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011026
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011027 // Distribute the remaining Tx power appropriately between all apps that transmitted
11028 // packets.
11029 for (int i = 0; i < txPackets.size(); i++) {
11030 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11031 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11032 / totalTxPackets;
11033 if (DEBUG_ENERGY) {
11034 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11035 }
11036 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11037 .addCountLocked(myTxTimeMs);
11038 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011039
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011040 // Distribute the remaining Rx power appropriately between all apps that received
11041 // packets.
11042 for (int i = 0; i < rxPackets.size(); i++) {
11043 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11044 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11045 / totalRxPackets;
11046 if (DEBUG_ENERGY) {
11047 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11048 }
11049 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11050 .addCountLocked(myRxTimeMs);
11051 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011052
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011053 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11054
11055
11056 // Update WiFi controller stats.
11057 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11058 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11059 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011060 mWifiActivity.getScanTimeCounter().addCountLocked(
11061 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011062 mWifiActivity.getIdleTimeCounter().addCountLocked(
11063 info.getControllerIdleTimeMillis());
11064
11065 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11066 final double opVolt = mPowerProfile.getAveragePower(
11067 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11068 if (opVolt != 0) {
11069 // We store the power drain as mAms.
11070 mWifiActivity.getPowerCounter().addCountLocked(
11071 (long) (info.getControllerEnergyUsed() / opVolt));
11072 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011073 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011074 }
11075 }
11076
11077 /**
11078 * Distribute Cell radio energy info and network traffic to apps.
11079 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011080 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011081 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011082 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011083 }
11084
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011085 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011086 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011087 synchronized (mModemNetworkLock) {
11088 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11089 if (latestStats != null) {
11090 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11091 mNetworkStatsPool.acquire());
11092 mNetworkStatsPool.release(mLastModemNetworkStats);
11093 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011094 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011095 }
11096
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011097 synchronized (this) {
11098 if (!mOnBatteryInternal) {
11099 if (delta != null) {
11100 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011101 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011102 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011103 }
11104
Siddharth Ray2038af82018-01-17 17:40:26 -080011105 if (activityInfo != null) {
11106 mHasModemReporting = true;
11107 mModemActivity.getIdleTimeCounter().addCountLocked(
11108 activityInfo.getIdleTimeMillis());
11109 mModemActivity.getRxTimeCounter().addCountLocked(activityInfo.getRxTimeMillis());
11110 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11111 mModemActivity.getTxTimeCounters()[lvl]
11112 .addCountLocked(activityInfo.getTxTimeMillis()[lvl]);
11113 }
11114
11115 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11116 final double opVolt = mPowerProfile.getAveragePower(
11117 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11118 if (opVolt != 0) {
11119 double energyUsed =
11120 activityInfo.getSleepTimeMillis() *
11121 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
11122 + activityInfo.getIdleTimeMillis() *
11123 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
11124 + activityInfo.getRxTimeMillis() *
11125 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
11126 int[] txCurrentMa = activityInfo.getTxTimeMillis();
11127 for (int i = 0; i < Math.min(txCurrentMa.length,
11128 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
11129 energyUsed += txCurrentMa[i] * mPowerProfile.getAveragePower(
11130 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
11131 }
11132
11133 // We store the power drain as mAms.
11134 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11135 }
11136 }
11137
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011138 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011139 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11140 elapsedRealtimeMs * 1000);
11141 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11142
11143 long totalRxPackets = 0;
11144 long totalTxPackets = 0;
11145 if (delta != null) {
11146 NetworkStats.Entry entry = new NetworkStats.Entry();
11147 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011148 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011149 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011150 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11151 continue;
11152 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011153
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011154 if (DEBUG_ENERGY) {
11155 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11156 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11157 + " txPackets=" + entry.txPackets);
11158 }
11159
11160 totalRxPackets += entry.rxPackets;
11161 totalTxPackets += entry.txPackets;
11162
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011163 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011164 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11165 entry.rxPackets);
11166 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11167 entry.txPackets);
11168 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11169 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11170 entry.rxBytes, entry.rxPackets);
11171 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11172 entry.txBytes, entry.txPackets);
11173 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011174
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011175 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11176 entry.rxBytes);
11177 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11178 entry.txBytes);
11179 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11180 entry.rxPackets);
11181 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11182 entry.txPackets);
11183 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011184
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011185 // Now distribute proportional blame to the apps that did networking.
11186 long totalPackets = totalRxPackets + totalTxPackets;
11187 if (totalPackets > 0) {
11188 for (int i = 0; i < size; i++) {
11189 entry = delta.getValues(i, entry);
11190 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11191 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011192 }
11193
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011194 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11195
11196 // Distribute total radio active time in to this app.
11197 final long appPackets = entry.rxPackets + entry.txPackets;
11198 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11199 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11200
11201 // Remove this app from the totals, so that we don't lose any time
11202 // due to rounding.
11203 radioTime -= appRadioTime;
11204 totalPackets -= appPackets;
11205
11206 if (activityInfo != null) {
11207 ControllerActivityCounterImpl activityCounter =
11208 u.getOrCreateModemControllerActivityLocked();
11209 if (totalRxPackets > 0 && entry.rxPackets > 0) {
11210 final long rxMs = (entry.rxPackets * activityInfo.getRxTimeMillis())
11211 / totalRxPackets;
11212 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11213 }
11214
11215 if (totalTxPackets > 0 && entry.txPackets > 0) {
11216 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11217 long txMs =
11218 entry.txPackets * activityInfo.getTxTimeMillis()[lvl];
11219 txMs /= totalTxPackets;
11220 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11221 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011222 }
11223 }
11224 }
11225 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011226
11227 if (radioTime > 0) {
11228 // Whoops, there is some radio time we can't blame on an app!
11229 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11230 mMobileRadioActiveUnknownCount.addCountLocked(1);
11231 }
11232
11233 mNetworkStatsPool.release(delta);
11234 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011235 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011236 }
11237 }
11238
11239 /**
11240 * Distribute Bluetooth energy info and network traffic to apps.
11241 * @param info The energy information from the bluetooth controller.
11242 */
11243 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011244 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011245 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011246 }
11247
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011248 if (info == null || !mOnBatteryInternal) {
11249 return;
11250 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011251
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011252 mHasBluetoothReporting = true;
11253
Bookatz867c0d72017-03-07 18:23:42 -080011254 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011255 final long rxTimeMs = info.getControllerRxTimeMillis();
11256 final long txTimeMs = info.getControllerTxTimeMillis();
11257
11258 if (DEBUG_ENERGY) {
11259 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11260 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11261 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11262 Slog.d(TAG, " Idle Time: " + info.getControllerIdleTimeMillis() + " ms");
11263 }
11264
11265 long totalScanTimeMs = 0;
11266
11267 final int uidCount = mUidStats.size();
11268 for (int i = 0; i < uidCount; i++) {
11269 final Uid u = mUidStats.valueAt(i);
11270 if (u.mBluetoothScanTimer == null) {
11271 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011272 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011273
Bookatzaa4594a2017-03-24 12:39:56 -070011274 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011275 elapsedRealtimeMs * 1000) / 1000;
11276 }
11277
11278 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11279 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11280
11281 if (DEBUG_ENERGY) {
11282 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11283 + " TX=" + normalizeScanTxTime);
11284 }
11285
11286 long leftOverRxTimeMs = rxTimeMs;
11287 long leftOverTxTimeMs = txTimeMs;
11288
11289 for (int i = 0; i < uidCount; i++) {
11290 final Uid u = mUidStats.valueAt(i);
11291 if (u.mBluetoothScanTimer == null) {
11292 continue;
11293 }
11294
Bookatzaa4594a2017-03-24 12:39:56 -070011295 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011296 elapsedRealtimeMs * 1000) / 1000;
11297 if (scanTimeSinceMarkMs > 0) {
11298 // Set the new mark so that next time we get new data since this point.
11299 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11300
11301 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11302 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11303
11304 if (normalizeScanRxTime) {
11305 // Scan time is longer than the total rx time in the controller,
11306 // so distribute the scan time proportionately. This means regular traffic
11307 // will not blamed, but scans are more expensive anyways.
11308 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11309 }
11310
11311 if (normalizeScanTxTime) {
11312 // Scan time is longer than the total tx time in the controller,
11313 // so distribute the scan time proportionately. This means regular traffic
11314 // will not blamed, but scans are more expensive anyways.
11315 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11316 }
11317
11318 final ControllerActivityCounterImpl counter =
11319 u.getOrCreateBluetoothControllerActivityLocked();
11320 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11321 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11322
11323 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11324 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11325 }
11326 }
11327
11328 if (DEBUG_ENERGY) {
11329 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs
11330 + " TX=" + leftOverTxTimeMs);
11331 }
11332
11333 //
11334 // Now distribute blame to apps that did bluetooth traffic.
11335 //
11336
11337 long totalTxBytes = 0;
11338 long totalRxBytes = 0;
11339
11340 final UidTraffic[] uidTraffic = info.getUidTraffic();
11341 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11342 for (int i = 0; i < numUids; i++) {
11343 final UidTraffic traffic = uidTraffic[i];
11344
11345 // Add to the global counters.
11346 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(
11347 traffic.getRxBytes());
11348 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(
11349 traffic.getTxBytes());
11350
11351 // Add to the UID counters.
11352 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
11353 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, traffic.getRxBytes(), 0);
11354 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, traffic.getTxBytes(), 0);
11355
11356 // Calculate the total traffic.
11357 totalTxBytes += traffic.getTxBytes();
11358 totalRxBytes += traffic.getRxBytes();
11359 }
11360
11361 if ((totalTxBytes != 0 || totalRxBytes != 0) &&
11362 (leftOverRxTimeMs != 0 || leftOverTxTimeMs != 0)) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011363 for (int i = 0; i < numUids; i++) {
11364 final UidTraffic traffic = uidTraffic[i];
11365
Adam Lesinski50e47602015-12-04 17:04:54 -080011366 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011367 final ControllerActivityCounterImpl counter =
11368 u.getOrCreateBluetoothControllerActivityLocked();
11369
11370 if (totalRxBytes > 0 && traffic.getRxBytes() > 0) {
11371 final long timeRxMs = (leftOverRxTimeMs * traffic.getRxBytes()) / totalRxBytes;
11372
11373 if (DEBUG_ENERGY) {
11374 Slog.d(TAG, "UID=" + traffic.getUid() + " rx_bytes=" + traffic.getRxBytes()
11375 + " rx_time=" + timeRxMs);
11376 }
11377 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11378 leftOverRxTimeMs -= timeRxMs;
11379 }
11380
11381 if (totalTxBytes > 0 && traffic.getTxBytes() > 0) {
11382 final long timeTxMs = (leftOverTxTimeMs * traffic.getTxBytes()) / totalTxBytes;
11383
11384 if (DEBUG_ENERGY) {
11385 Slog.d(TAG, "UID=" + traffic.getUid() + " tx_bytes=" + traffic.getTxBytes()
11386 + " tx_time=" + timeTxMs);
11387 }
11388
11389 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11390 leftOverTxTimeMs -= timeTxMs;
11391 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011392 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011393 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011394
11395 mBluetoothActivity.getRxTimeCounter().addCountLocked(
11396 info.getControllerRxTimeMillis());
11397 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(
11398 info.getControllerTxTimeMillis());
11399 mBluetoothActivity.getIdleTimeCounter().addCountLocked(
11400 info.getControllerIdleTimeMillis());
11401
11402 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11403 final double opVolt = mPowerProfile.getAveragePower(
11404 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11405 if (opVolt != 0) {
11406 // We store the power drain as mAms.
11407 mBluetoothActivity.getPowerCounter().addCountLocked(
11408 (long) (info.getControllerEnergyUsed() / opVolt));
11409 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011410 }
11411
11412 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011413 * Read and record Resource Power Manager (RPM) state and voter times.
11414 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11415 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011416 */
11417 public void updateRpmStatsLocked() {
11418 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011419 long now = SystemClock.elapsedRealtime();
11420 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11421 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11422 mLastRpmStatsUpdateTimeMs = now;
11423 }
Bookatz50df7112017-08-04 14:53:26 -070011424
11425 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11426 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11427
11428 // Update values for this platform state.
11429 final String pName = pstate.getKey();
11430 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11431 final int pCount = pstate.getValue().mCount;
11432 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011433 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11434 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11435 }
Bookatz50df7112017-08-04 14:53:26 -070011436
11437 // Update values for each voter of this platform state.
11438 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11439 : pstate.getValue().mVoters.entrySet()) {
11440 final String vName = pName + "." + voter.getKey();
11441 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11442 final int vCount = voter.getValue().mCount;
11443 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011444 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11445 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11446 }
Bookatz50df7112017-08-04 14:53:26 -070011447 }
11448 }
11449
11450 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11451 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11452
11453 final String subsysName = subsys.getKey();
11454 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11455 : subsys.getValue().mStates.entrySet()) {
11456 final String name = subsysName + "." + sstate.getKey();
11457 final long timeUs = sstate.getValue().mTimeMs * 1000;
11458 final int count = sstate.getValue().mCount;
11459 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011460 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11461 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11462 }
Bookatz50df7112017-08-04 14:53:26 -070011463 }
11464 }
11465 }
11466
11467 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011468 * Read and distribute kernel wake lock use across apps.
11469 */
11470 public void updateKernelWakelocksLocked() {
11471 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11472 mTmpWakelockStats);
11473 if (wakelockStats == null) {
11474 // Not crashing might make board bringup easier.
11475 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11476 return;
11477 }
11478
11479 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11480 String name = ent.getKey();
11481 KernelWakelockStats.Entry kws = ent.getValue();
11482
11483 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11484 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011485 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011486 mKernelWakelockStats.put(name, kwlt);
11487 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011488
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011489 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011490 kwlt.setUpdateVersion(kws.mVersion);
11491 }
11492
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011493 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011494 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11495 // this time.
11496 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11497 SamplingTimer st = ent.getValue();
11498 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11499 st.endSample();
11500 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011501 }
11502 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011503
Adam Lesinskid84ad302016-05-17 18:31:02 -070011504 // Record whether we've seen a non-zero time (for debugging b/22716723).
11505 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011506 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11507 }
11508
11509 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11510 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11511 wakelockStats.kernelWakelockVersion);
11512 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011513 }
11514
Adam Lesinski72478f02015-06-17 15:39:43 -070011515 // We use an anonymous class to access these variables,
11516 // so they can't live on the stack or they'd have to be
11517 // final MutableLong objects (more allocations).
11518 // Used in updateCpuTimeLocked().
11519 long mTempTotalCpuUserTimeUs;
11520 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011521 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011522
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011523 /**
James Carr3a226052016-07-01 14:49:52 -070011524 * Reads the newest memory stats from the kernel.
11525 */
11526 public void updateKernelMemoryBandwidthLocked() {
11527 mKernelMemoryBandwidthStats.updateStats();
11528 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11529 final int bandwidthEntryCount = bandwidthEntries.size();
11530 int index;
11531 for (int i = 0; i < bandwidthEntryCount; i++) {
11532 SamplingTimer timer;
11533 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11534 timer = mKernelMemoryStats.valueAt(index);
11535 } else {
11536 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11537 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11538 }
11539 timer.update(bandwidthEntries.valueAt(i), 1);
11540 if (DEBUG_MEMORY) {
11541 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11542 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11543 mKernelMemoryStats.get(
11544 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11545 mKernelMemoryStats.size()));
11546 }
11547 }
11548 }
11549
11550 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011551 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11552 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11553 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011554 */
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011555 public void updateCpuTimeLocked() {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011556 if (mPowerProfile == null) {
11557 return;
11558 }
11559
Adam Lesinski72478f02015-06-17 15:39:43 -070011560 if (DEBUG_ENERGY_CPU) {
11561 Slog.d(TAG, "!Cpu updating!");
11562 }
11563
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011564 if (mCpuFreqs == null) {
11565 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11566 }
11567
Sudheer Shanka38383232017-07-25 09:55:03 -070011568 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11569 // usually holding the wakelock on behalf of an app.
11570 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11571 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Adam Lesinski72478f02015-06-17 15:39:43 -070011572 if (mOnBatteryScreenOffTimeBase.isRunning()) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011573 partialTimersToConsider = new ArrayList<>();
11574 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011575 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011576 // Since the collection and blaming of wakelocks can be scheduled to run after
11577 // some delay, the mPartialTimers list may have new entries. We can't blame
11578 // the newly added timer for past cpu time, so we only consider timers that
11579 // were present for one round of collection. Once a timer has gone through
11580 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011581 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011582 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011583 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011584 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011585 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011586 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011587
Sudheer Shanka38383232017-07-25 09:55:03 -070011588 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11589 // need to take the snapshots.
11590 if (!mOnBatteryInternal) {
11591 mKernelUidCpuTimeReader.readDelta(null);
11592 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Mafae87da2018-01-19 20:07:20 -080011593 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11594 mKernelUidCpuActiveTimeReader.readDelta(null);
11595 mKernelUidCpuClusterTimeReader.readDelta(null);
11596 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011597 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
11598 mKernelCpuSpeedReaders[cluster].readDelta();
11599 }
11600 return;
11601 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011602
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011603 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011604 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
11605 ? null : new SparseLongArray();
Sudheer Shanka38383232017-07-25 09:55:03 -070011606 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011607 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
11608 // freqs, so no need to approximate these values.
11609 if (updatedUids != null) {
11610 updateClusterSpeedTimes(updatedUids);
Sudheer Shanka671985f2017-05-19 11:33:42 -070011611 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011612 readKernelUidCpuFreqTimesLocked(partialTimersToConsider);
Mike Mafae87da2018-01-19 20:07:20 -080011613 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11614 readKernelUidCpuActiveTimesLocked();
11615 readKernelUidCpuClusterTimesLocked();
11616 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011617 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011618
Sudheer Shanka38383232017-07-25 09:55:03 -070011619 /**
11620 * Mark the current partial timers as gone through a collection so that they will be
11621 * considered in the next cpu times distribution to wakelock holders.
11622 */
11623 @VisibleForTesting
11624 public void markPartialTimersAsEligible() {
11625 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
11626 // No difference, so each timer is now considered for the next collection.
11627 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
11628 mPartialTimers.get(i).mInList = true;
11629 }
11630 } else {
11631 // The lists are different, meaning we added (or removed a timer) since the last
11632 // collection.
11633 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
11634 mLastPartialTimers.get(i).mInList = false;
11635 }
11636 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070011637
Sudheer Shanka38383232017-07-25 09:55:03 -070011638 // Mark the current timers as gone through a collection.
11639 final int numPartialTimers = mPartialTimers.size();
11640 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011641 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011642 timer.mInList = true;
11643 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070011644 }
11645 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011646 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011647
Sudheer Shanka38383232017-07-25 09:55:03 -070011648 /**
11649 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
11650 * calculate cpu times spent by each uid at different frequencies.
11651 *
11652 * @param updatedUids The uids for which times spent at different frequencies are calculated.
11653 */
11654 @VisibleForTesting
11655 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011656 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011657 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070011658 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011659 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011660 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
11661 if (clusterSpeedTimesMs[cluster] != null) {
11662 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
11663 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011664 }
11665 }
11666 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011667 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011668 // We have cpu times per freq aggregated over all uids but we need the times per uid.
11669 // So, we distribute total time spent by an uid to different cpu freqs based on the
11670 // amount of time cpu was running at that freq.
11671 final int updatedUidsCount = updatedUids.size();
11672 for (int i = 0; i < updatedUidsCount; ++i) {
11673 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070011674 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011675 // Add the cpu speeds to this UID.
11676 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070011677 if (u.mCpuClusterSpeedTimesUs == null ||
11678 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011679 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011680 }
11681
Sudheer Shankaaf857412017-07-21 00:14:24 -070011682 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
11683 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
11684 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
11685 u.mCpuClusterSpeedTimesUs[cluster].length) {
11686 u.mCpuClusterSpeedTimesUs[cluster]
11687 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011688 }
11689
Sudheer Shankaaf857412017-07-21 00:14:24 -070011690 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011691 for (int speed = 0; speed < speedsInCluster; speed++) {
11692 if (cpuSpeeds[speed] == null) {
11693 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11694 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011695 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
11696 * clusterSpeedTimesMs[cluster][speed]
11697 / totalCpuClustersTimeMs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011698 }
11699 }
11700 }
11701 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011702 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011703
Sudheer Shanka38383232017-07-25 09:55:03 -070011704 /**
11705 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
11706 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
11707 * wakelock holders.
11708 *
11709 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
11710 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
11711 */
11712 @VisibleForTesting
11713 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
11714 @Nullable SparseLongArray updatedUids) {
11715 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
11716 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11717 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070011718
Sudheer Shanka38383232017-07-25 09:55:03 -070011719 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
11720 uid = mapUid(uid);
11721 if (Process.isIsolated(uid)) {
11722 // This could happen if the isolated uid mapping was removed before that process
11723 // was actually killed.
11724 mKernelUidCpuTimeReader.removeUid(uid);
11725 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
11726 return;
11727 }
11728 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11729 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
11730 mKernelUidCpuTimeReader.removeUid(uid);
11731 return;
11732 }
11733 final Uid u = getUidStatsLocked(uid);
11734
11735 // Accumulate the total system and user time.
11736 mTempTotalCpuUserTimeUs += userTimeUs;
11737 mTempTotalCpuSystemTimeUs += systemTimeUs;
11738
11739 StringBuilder sb = null;
11740 if (DEBUG_ENERGY_CPU) {
11741 sb = new StringBuilder();
11742 sb.append(" got time for uid=").append(u.mUid).append(": u=");
11743 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11744 sb.append(" s=");
11745 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11746 sb.append("\n");
11747 }
11748
11749 if (numWakelocks > 0) {
11750 // We have wakelocks being held, so only give a portion of the
11751 // time to the process. The rest will be distributed among wakelock
11752 // holders.
11753 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
11754 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
11755 }
11756
11757 if (sb != null) {
11758 sb.append(" adding to uid=").append(u.mUid).append(": u=");
11759 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11760 sb.append(" s=");
11761 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11762 Slog.d(TAG, sb.toString());
11763 }
11764
11765 u.mUserCpuTime.addCountLocked(userTimeUs);
11766 u.mSystemCpuTime.addCountLocked(systemTimeUs);
11767 if (updatedUids != null) {
11768 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
11769 }
11770 });
11771
11772 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11773 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11774 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
11775 }
11776
11777 if (numWakelocks > 0) {
11778 // Distribute a portion of the total cpu time to wakelock holders.
11779 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11780 mTempTotalCpuSystemTimeUs =
11781 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11782
11783 for (int i = 0; i < numWakelocks; ++i) {
11784 final StopwatchTimer timer = partialTimers.get(i);
11785 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
11786 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
11787
11788 if (DEBUG_ENERGY_CPU) {
11789 final StringBuilder sb = new StringBuilder();
11790 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
11791 .append(": u=");
11792 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11793 sb.append(" s=");
11794 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11795 Slog.d(TAG, sb.toString());
11796 }
11797
11798 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs);
11799 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs);
11800 if (updatedUids != null) {
11801 final int uid = timer.mUid.getUid();
11802 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
11803 }
11804
11805 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
11806 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000);
11807
11808 mTempTotalCpuUserTimeUs -= userTimeUs;
11809 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011810 }
11811 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011812 }
11813
Sudheer Shanka38383232017-07-25 09:55:03 -070011814 /**
11815 * Take a snapshot of the cpu times spent by each uid in each freq and update the
11816 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011817 *
11818 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070011819 */
11820 @VisibleForTesting
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011821 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers) {
11822 final boolean perClusterTimesAvailable =
11823 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
11824 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11825 final int numClusters = mPowerProfile.getNumCpuClusters();
11826 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080011827 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011828 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
11829 uid = mapUid(uid);
11830 if (Process.isIsolated(uid)) {
11831 mKernelUidCpuFreqTimeReader.removeUid(uid);
11832 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
11833 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070011834 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011835 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11836 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
11837 mKernelUidCpuFreqTimeReader.removeUid(uid);
11838 return;
11839 }
11840 final Uid u = getUidStatsLocked(uid);
11841 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
11842 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
11843 }
11844 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
11845 if (u.mScreenOffCpuFreqTimeMs == null ||
11846 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
11847 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
11848 mOnBatteryScreenOffTimeBase);
11849 }
11850 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011851
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011852 if (perClusterTimesAvailable) {
11853 if (u.mCpuClusterSpeedTimesUs == null ||
11854 u.mCpuClusterSpeedTimesUs.length != numClusters) {
11855 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070011856 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011857 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
11858 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070011859 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011860
11861 int freqIndex = 0;
11862 for (int cluster = 0; cluster < numClusters; ++cluster) {
11863 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
11864 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
11865 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
11866 u.mCpuClusterSpeedTimesUs[cluster]
11867 = new LongSamplingCounter[speedsInCluster];
11868 }
11869 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
11870 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
11871 }
11872 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
11873 for (int speed = 0; speed < speedsInCluster; ++speed) {
11874 if (cpuTimesUs[speed] == null) {
11875 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11876 }
11877 final long appAllocationUs;
11878 if (mWakeLockAllocationsUs != null) {
11879 appAllocationUs =
11880 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
11881 mWakeLockAllocationsUs[cluster][speed] +=
11882 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
11883 } else {
11884 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
11885 }
11886 cpuTimesUs[speed].addCountLocked(appAllocationUs);
11887 freqIndex++;
11888 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011889 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011890 }
11891 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011892
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080011893 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11894 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11895 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
11896 }
11897
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011898 if (mWakeLockAllocationsUs != null) {
11899 for (int i = 0; i < numWakelocks; ++i) {
11900 final Uid u = partialTimers.get(i).mUid;
11901 if (u.mCpuClusterSpeedTimesUs == null ||
11902 u.mCpuClusterSpeedTimesUs.length != numClusters) {
11903 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
11904 }
11905
11906 for (int cluster = 0; cluster < numClusters; ++cluster) {
11907 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
11908 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
11909 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
11910 u.mCpuClusterSpeedTimesUs[cluster]
11911 = new LongSamplingCounter[speedsInCluster];
11912 }
11913 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
11914 for (int speed = 0; speed < speedsInCluster; ++speed) {
11915 if (cpuTimeUs[speed] == null) {
11916 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11917 }
11918 final long allocationUs =
11919 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
11920 cpuTimeUs[speed].addCountLocked(allocationUs);
11921 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
11922 }
11923 }
11924 }
11925 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011926 }
11927
Mike Ma3d422c32017-10-25 11:08:57 -070011928 /**
11929 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
11930 * counters.
11931 */
11932 @VisibleForTesting
11933 public void readKernelUidCpuActiveTimesLocked() {
11934 final long startTimeMs = mClocks.uptimeMillis();
11935 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesUs) -> {
11936 uid = mapUid(uid);
11937 if (Process.isIsolated(uid)) {
11938 mKernelUidCpuActiveTimeReader.removeUid(uid);
11939 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
11940 return;
11941 }
11942 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11943 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
11944 mKernelUidCpuActiveTimeReader.removeUid(uid);
11945 return;
11946 }
11947 final Uid u = getUidStatsLocked(uid);
11948 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesUs);
11949 });
11950
11951 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11952 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11953 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
11954 }
11955 }
11956
11957 /**
11958 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
11959 * counters.
11960 */
11961 @VisibleForTesting
11962 public void readKernelUidCpuClusterTimesLocked() {
11963 final long startTimeMs = mClocks.uptimeMillis();
11964 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesUs) -> {
11965 uid = mapUid(uid);
11966 if (Process.isIsolated(uid)) {
11967 mKernelUidCpuClusterTimeReader.removeUid(uid);
11968 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
11969 return;
11970 }
11971 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11972 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
11973 mKernelUidCpuClusterTimeReader.removeUid(uid);
11974 return;
11975 }
11976 final Uid u = getUidStatsLocked(uid);
11977 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesUs);
11978 });
11979
11980 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11981 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11982 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
11983 }
11984 }
11985
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011986 boolean setChargingLocked(boolean charging) {
11987 if (mCharging != charging) {
11988 mCharging = charging;
11989 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070011990 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011991 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070011992 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011993 }
11994 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
11995 return true;
11996 }
11997 return false;
11998 }
11999
Mike Mac2f518a2017-09-19 16:06:03 -070012000 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12001 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012002 boolean doWrite = false;
12003 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12004 m.arg1 = onBattery ? 1 : 0;
12005 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012006
Dianne Hackborn40c87252014-03-19 16:55:40 -070012007 final long uptime = mSecUptime * 1000;
12008 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012009 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012010 if (onBattery) {
12011 // We will reset our status if we are unplugging after the
12012 // battery was last full, or the level is at 100, or
12013 // we have gone through a significant charge (from a very low
12014 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012015 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012016 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012017 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012018 || (mDischargeCurrentLevel < 20 && level >= 80)
12019 || (getHighDischargeAmountSinceCharge() >= 200
12020 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012021 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012022 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012023 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12024 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012025 // Before we write, collect a snapshot of the final aggregated
12026 // stats to be reported in the next checkin. Only do this if we have
12027 // a sufficient amount of data to make it interesting.
12028 if (getLowDischargeAmountSinceCharge() >= 20) {
12029 final Parcel parcel = Parcel.obtain();
12030 writeSummaryToParcel(parcel, true);
12031 BackgroundThread.getHandler().post(new Runnable() {
12032 @Override public void run() {
12033 synchronized (mCheckinFile) {
12034 FileOutputStream stream = null;
12035 try {
12036 stream = mCheckinFile.startWrite();
12037 stream.write(parcel.marshall());
12038 stream.flush();
12039 FileUtils.sync(stream);
12040 stream.close();
12041 mCheckinFile.finishWrite(stream);
12042 } catch (IOException e) {
12043 Slog.w("BatteryStats",
12044 "Error writing checkin battery statistics", e);
12045 mCheckinFile.failWrite(stream);
12046 } finally {
12047 parcel.recycle();
12048 }
12049 }
12050 }
12051 });
12052 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012053 doWrite = true;
12054 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012055 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012056 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012057 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012058 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012059 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012060 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012061 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012062 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012063 if (mCharging) {
12064 setChargingLocked(false);
12065 }
12066 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012067 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012068 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012069 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012070 mDischargeStepTracker.clearTime();
12071 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012072 mInitStepMode = mCurStepMode;
12073 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012074 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012075 mHistoryCur.batteryLevel = (byte)level;
12076 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12077 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12078 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012079 if (reset) {
12080 mRecordingHistory = true;
12081 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12082 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012083 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012084 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012085 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012086 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012087 mDischargeScreenDozeUnplugLevel = 0;
12088 mDischargeScreenOffUnplugLevel = 0;
12089 } else if (isScreenDoze(screenState)) {
12090 mDischargeScreenOnUnplugLevel = 0;
12091 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012092 mDischargeScreenOffUnplugLevel = 0;
12093 } else {
12094 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012095 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012096 mDischargeScreenOffUnplugLevel = level;
12097 }
12098 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012099 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012100 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012101 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012102 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012103 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012104 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012105 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012106 mHistoryCur.batteryLevel = (byte)level;
12107 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12108 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12109 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012110 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012111 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012112 if (level < mDischargeUnplugLevel) {
12113 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12114 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12115 }
Mike Mac2f518a2017-09-19 16:06:03 -070012116 updateDischargeScreenLevelsLocked(screenState, screenState);
12117 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012118 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012119 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012120 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012121 mInitStepMode = mCurStepMode;
12122 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012123 }
12124 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12125 if (mFile != null) {
12126 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012127 }
12128 }
12129 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012130
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012131 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12132 boolean reset) {
12133 mRecordingHistory = true;
12134 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn37de0982014-05-09 09:32:18 -070012135 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs,
12136 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012137 mHistoryCur);
12138 mHistoryCur.currentTime = 0;
12139 if (reset) {
12140 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12141 }
12142 }
12143
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012144 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12145 final long uptimeMs) {
12146 if (mRecordingHistory) {
12147 mHistoryCur.currentTime = currentTime;
12148 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_CURRENT_TIME,
12149 mHistoryCur);
12150 mHistoryCur.currentTime = 0;
12151 }
12152 }
12153
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012154 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12155 if (mRecordingHistory) {
12156 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012157 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_SHUTDOWN,
12158 mHistoryCur);
12159 mHistoryCur.currentTime = 0;
12160 }
12161 }
12162
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012163 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012164 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012165 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012166 }
12167 }
12168
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012169 // This should probably be exposed in the API, though it's not critical
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012170 public static final int BATTERY_PLUGGED_NONE = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012171
Bookatz8c6571b2017-10-24 15:04:41 -070012172 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12173 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12174 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012175 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12176 temp = Math.max(0, temp);
12177
Bookatz8c6571b2017-10-24 15:04:41 -070012178 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
12179 status, plugType, level, temp);
12180
Todd Poynor1acf06a2017-12-07 19:19:35 -080012181 final boolean onBattery =
12182 plugType == BATTERY_PLUGGED_NONE &&
12183 status != BatteryManager.BATTERY_STATUS_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080012184 final long uptime = mClocks.uptimeMillis();
12185 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012186 if (!mHaveBatteryLevel) {
12187 mHaveBatteryLevel = true;
12188 // We start out assuming that the device is plugged in (not
12189 // on battery). If our first report is now that we are indeed
12190 // plugged in, then twiddle our state to correctly reflect that
12191 // since we won't be going through the full setOnBattery().
12192 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012193 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012194 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012195 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012196 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012197 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012198 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012199 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012200 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012201 mHistoryCur.batteryStatus = (byte)status;
12202 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012203 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012204 mMaxChargeStepLevel = mMinDischargeStepLevel =
12205 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012206 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012207 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12208 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12209 }
12210 int oldStatus = mHistoryCur.batteryStatus;
12211 if (onBattery) {
12212 mDischargeCurrentLevel = level;
12213 if (!mRecordingHistory) {
12214 mRecordingHistory = true;
12215 startRecordingHistory(elapsedRealtime, uptime, true);
12216 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012217 } else if (level < 96 &&
12218 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012219 if (!mRecordingHistory) {
12220 mRecordingHistory = true;
12221 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012222 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012223 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012224 mCurrentBatteryLevel = level;
12225 if (mDischargePlugLevel < 0) {
12226 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012227 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012228
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012229 if (onBattery != mOnBattery) {
12230 mHistoryCur.batteryLevel = (byte)level;
12231 mHistoryCur.batteryStatus = (byte)status;
12232 mHistoryCur.batteryHealth = (byte)health;
12233 mHistoryCur.batteryPlugType = (byte)plugType;
12234 mHistoryCur.batteryTemperature = (short)temp;
12235 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012236 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12237 // Only record discharges
12238 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12239 mDischargeCounter.addCountLocked(chargeDiff);
12240 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012241 if (isScreenDoze(mScreenState)) {
12242 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12243 }
Mike Ma15313c92017-11-15 17:58:21 -080012244 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12245 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12246 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12247 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12248 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012249 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012250 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012251 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012252 } else {
12253 boolean changed = false;
12254 if (mHistoryCur.batteryLevel != level) {
12255 mHistoryCur.batteryLevel = (byte)level;
12256 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012257
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012258 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12259 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012260 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070012261 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012262 if (mHistoryCur.batteryStatus != status) {
12263 mHistoryCur.batteryStatus = (byte)status;
12264 changed = true;
12265 }
12266 if (mHistoryCur.batteryHealth != health) {
12267 mHistoryCur.batteryHealth = (byte)health;
12268 changed = true;
12269 }
12270 if (mHistoryCur.batteryPlugType != plugType) {
12271 mHistoryCur.batteryPlugType = (byte)plugType;
12272 changed = true;
12273 }
12274 if (temp >= (mHistoryCur.batteryTemperature+10)
12275 || temp <= (mHistoryCur.batteryTemperature-10)) {
12276 mHistoryCur.batteryTemperature = (short)temp;
12277 changed = true;
12278 }
12279 if (volt > (mHistoryCur.batteryVoltage+20)
12280 || volt < (mHistoryCur.batteryVoltage-20)) {
12281 mHistoryCur.batteryVoltage = (char)volt;
12282 changed = true;
12283 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012284 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12285 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012286 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12287 // Only record discharges
12288 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12289 mDischargeCounter.addCountLocked(chargeDiff);
12290 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012291 if (isScreenDoze(mScreenState)) {
12292 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12293 }
Mike Ma15313c92017-11-15 17:58:21 -080012294 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12295 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12296 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12297 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12298 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012299 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012300 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012301 changed = true;
12302 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012303 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12304 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12305 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12306 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012307 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012308 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12309 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12310 modeBits, elapsedRealtime);
12311 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12312 modeBits, elapsedRealtime);
12313 mLastDischargeStepLevel = level;
12314 mMinDischargeStepLevel = level;
12315 mInitStepMode = mCurStepMode;
12316 mModStepMode = 0;
12317 }
12318 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012319 if (level >= 90) {
12320 // If the battery level is at least 90%, always consider the device to be
12321 // charging even if it happens to go down a level.
12322 changed |= setChargingLocked(true);
12323 mLastChargeStepLevel = level;
12324 } if (!mCharging) {
12325 if (mLastChargeStepLevel < level) {
12326 // We have not reporting that we are charging, but the level has now
12327 // gone up, so consider the state to be charging.
12328 changed |= setChargingLocked(true);
12329 mLastChargeStepLevel = level;
12330 }
12331 } else {
12332 if (mLastChargeStepLevel > level) {
12333 // We had reported that the device was charging, but here we are with
12334 // power connected and the level going down. Looks like the current
12335 // power supplied isn't enough, so consider the device to now be
12336 // discharging.
12337 changed |= setChargingLocked(false);
12338 mLastChargeStepLevel = level;
12339 }
12340 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012341 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12342 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12343 modeBits, elapsedRealtime);
12344 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12345 modeBits, elapsedRealtime);
12346 mLastChargeStepLevel = level;
12347 mMaxChargeStepLevel = level;
12348 mInitStepMode = mCurStepMode;
12349 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012350 }
12351 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012352 if (changed) {
12353 addHistoryRecordLocked(elapsedRealtime, uptime);
12354 }
Evan Millarc64edde2009-04-18 12:26:32 -070012355 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012356 if (!onBattery &&
12357 (status == BatteryManager.BATTERY_STATUS_FULL ||
12358 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12359 // We don't record history while we are plugged in and fully charged
12360 // (or when battery is not present). The next time we are
12361 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012362 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012363 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012364
Jocelyn Dangc627d102017-04-14 13:15:14 -070012365 if (mMinLearnedBatteryCapacity == -1) {
12366 mMinLearnedBatteryCapacity = chargeFullUAh;
12367 } else {
12368 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012369 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012370 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012371 }
12372
Bookatz8c6571b2017-10-24 15:04:41 -070012373 // Inform StatsLog of setBatteryState changes.
12374 // If this is the first reporting, pass in recentPast == null.
12375 private void reportChangesToStatsLog(HistoryItem recentPast,
12376 final int status, final int plugType, final int level, final int temp) {
12377
12378 if (recentPast == null || recentPast.batteryStatus != status) {
12379 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12380 }
12381 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12382 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12383 }
12384 if (recentPast == null || recentPast.batteryLevel != level) {
12385 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12386 }
12387 // Let's just always print the temperature, regardless of whether it changed.
12388 StatsLog.write(StatsLog.DEVICE_TEMPERATURE_REPORTED, temp);
12389 }
12390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012391 public long getAwakeTimeBattery() {
12392 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12393 }
12394
12395 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012396 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012397 }
12398
12399 @Override
12400 public long computeUptime(long curTime, int which) {
12401 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012402 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012403 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012404 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012405 }
12406 return 0;
12407 }
12408
12409 @Override
12410 public long computeRealtime(long curTime, int which) {
12411 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012412 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012413 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012414 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012415 }
12416 return 0;
12417 }
12418
12419 @Override
12420 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012421 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012422 }
12423
12424 @Override
12425 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012426 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012427 }
12428
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012429 @Override
12430 public long computeBatteryScreenOffUptime(long curTime, int which) {
12431 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12432 }
12433
12434 @Override
12435 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12436 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012437 }
12438
Dianne Hackborn260c5022014-04-29 11:23:16 -070012439 private long computeTimePerLevel(long[] steps, int numSteps) {
12440 // For now we'll do a simple average across all steps.
12441 if (numSteps <= 0) {
12442 return -1;
12443 }
12444 long total = 0;
12445 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012446 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012447 }
12448 return total / numSteps;
12449 /*
12450 long[] buckets = new long[numSteps];
12451 int numBuckets = 0;
12452 int numToAverage = 4;
12453 int i = 0;
12454 while (i < numSteps) {
12455 long totalTime = 0;
12456 int num = 0;
12457 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012458 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012459 num++;
12460 }
12461 buckets[numBuckets] = totalTime / num;
12462 numBuckets++;
12463 numToAverage *= 2;
12464 i += num;
12465 }
12466 if (numBuckets < 1) {
12467 return -1;
12468 }
12469 long averageTime = buckets[numBuckets-1];
12470 for (i=numBuckets-2; i>=0; i--) {
12471 averageTime = (averageTime + buckets[i]) / 2;
12472 }
12473 return averageTime;
12474 */
12475 }
12476
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012477 @Override
12478 public long computeBatteryTimeRemaining(long curTime) {
12479 if (!mOnBattery) {
12480 return -1;
12481 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012482 /* Simple implementation just looks at the average discharge per level across the
12483 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012484 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12485 if (discharge < 2) {
12486 return -1;
12487 }
12488 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12489 if (duration < 1000*1000) {
12490 return -1;
12491 }
12492 long usPerLevel = duration/discharge;
12493 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012494 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012495 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012496 return -1;
12497 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012498 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012499 if (msPerLevel <= 0) {
12500 return -1;
12501 }
12502 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012503 }
12504
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012505 @Override
12506 public LevelStepTracker getDischargeLevelStepTracker() {
12507 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012508 }
12509
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012510 @Override
12511 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12512 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012513 }
12514
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012515 @Override
12516 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012517 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012518 // Not yet working.
12519 return -1;
12520 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012521 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012522 int curLevel = mCurrentBatteryLevel;
12523 int plugLevel = mDischargePlugLevel;
12524 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12525 return -1;
12526 }
12527 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12528 if (duration < 1000*1000) {
12529 return -1;
12530 }
12531 long usPerLevel = duration/(curLevel-plugLevel);
12532 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012533 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012534 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012535 return -1;
12536 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012537 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012538 if (msPerLevel <= 0) {
12539 return -1;
12540 }
12541 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012542 }
12543
Siddharth Raya1fd0572017-11-13 14:20:47 -080012544 /*@hide */
12545 public CellularBatteryStats getCellularBatteryStats() {
12546 CellularBatteryStats s = new CellularBatteryStats();
12547 final int which = STATS_SINCE_CHARGED;
12548 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12549 final ControllerActivityCounter counter = getModemControllerActivity();
12550 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12551 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12552 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12553 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12554 for (int i = 0; i < timeInRatMs.length; i++) {
12555 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12556 }
12557 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12558 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12559 timeInRxSignalStrengthLevelMs[i]
12560 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12561 }
12562 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12563 counter.getTxTimeCounters().length)];
12564 long totalTxTimeMs = 0;
12565 for (int i = 0; i < txTimeMs.length; i++) {
12566 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12567 totalTxTimeMs += txTimeMs[i];
12568 }
12569 final long totalControllerActivityTimeMs
12570 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12571 final long sleepTimeMs
12572 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + totalTxTimeMs);
12573 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12574 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12575 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12576 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12577 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12578 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
12579 s.setSleepTimeMs(sleepTimeMs);
12580 s.setIdleTimeMs(idleTimeMs);
12581 s.setRxTimeMs(rxTimeMs);
12582 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12583 s.setTimeInRatMs(timeInRatMs);
12584 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
12585 s.setTxTimeMs(txTimeMs);
12586 return s;
12587 }
12588
Siddharth Rayb50a6842017-12-14 15:15:28 -080012589 /*@hide */
12590 public WifiBatteryStats getWifiBatteryStats() {
12591 WifiBatteryStats s = new WifiBatteryStats();
12592 final int which = STATS_SINCE_CHARGED;
12593 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12594 final ControllerActivityCounter counter = getWifiControllerActivity();
12595 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12596 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
12597 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12598 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
12599 final long totalControllerActivityTimeMs
12600 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12601 final long sleepTimeMs
12602 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
12603 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12604 long numAppScanRequest = 0;
12605 for (int i = 0; i < mUidStats.size(); i++) {
12606 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
12607 }
12608 long[] timeInStateMs = new long[NUM_WIFI_STATES];
12609 for (int i=0; i<NUM_WIFI_STATES; i++) {
12610 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
12611 }
12612 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
12613 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12614 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
12615 }
12616 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
12617 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12618 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
12619 }
12620 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12621 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
12622 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
12623 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
12624 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
12625 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
12626 s.setSleepTimeMs(sleepTimeMs);
12627 s.setIdleTimeMs(idleTimeMs);
12628 s.setRxTimeMs(rxTimeMs);
12629 s.setTxTimeMs(txTimeMs);
12630 s.setScanTimeMs(scanTimeMs);
12631 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12632 s.setNumAppScanRequest(numAppScanRequest);
12633 s.setTimeInStateMs(timeInStateMs);
12634 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
12635 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
12636 return s;
12637 }
12638
Siddharth Ray78ccaf52017-12-23 16:16:21 -080012639 /*@hide */
12640 public GpsBatteryStats getGpsBatteryStats() {
12641 GpsBatteryStats s = new GpsBatteryStats();
12642 final int which = STATS_SINCE_CHARGED;
12643 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12644 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12645 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
12646 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
12647 for (int i=0; i<time.length; i++) {
12648 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
12649 }
12650 s.setTimeInGpsSignalQualityLevel(time);
12651 return s;
12652 }
12653
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012654 @Override
12655 public LevelStepTracker getChargeLevelStepTracker() {
12656 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012657 }
12658
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012659 @Override
12660 public LevelStepTracker getDailyChargeLevelStepTracker() {
12661 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012662 }
12663
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012664 @Override
12665 public ArrayList<PackageChange> getDailyPackageChanges() {
12666 return mDailyPackageChanges;
12667 }
12668
Joe Onoratoe1acd632016-02-23 13:25:10 -080012669 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012670 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012671 }
12672
12673 @Override
12674 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012675 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012676 }
12677
12678 @Override
12679 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012680 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012681 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070012682
The Android Open Source Project10592532009-03-18 17:39:46 -070012683 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012684 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012685 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012686 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012687 }
12688 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012689
Evan Millar633a1742009-04-02 16:36:33 -070012690 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012691 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012692 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012693
The Android Open Source Project10592532009-03-18 17:39:46 -070012694 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012695 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012696 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012697 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012698 }
12699 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012700
Evan Millar633a1742009-04-02 16:36:33 -070012701 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012702 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012704
Amith Yamasanie43530a2009-08-21 13:11:37 -070012705 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012706 public int getLowDischargeAmountSinceCharge() {
12707 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012708 int val = mLowDischargeAmountSinceCharge;
12709 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12710 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
12711 }
12712 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012713 }
12714 }
12715
12716 @Override
12717 public int getHighDischargeAmountSinceCharge() {
12718 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012719 int val = mHighDischargeAmountSinceCharge;
12720 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12721 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
12722 }
12723 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012724 }
12725 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012726
12727 @Override
12728 public int getDischargeAmount(int which) {
12729 int dischargeAmount = which == STATS_SINCE_CHARGED
12730 ? getHighDischargeAmountSinceCharge()
12731 : (getDischargeStartLevel() - getDischargeCurrentLevel());
12732 if (dischargeAmount < 0) {
12733 dischargeAmount = 0;
12734 }
12735 return dischargeAmount;
12736 }
12737
Mike Mac2f518a2017-09-19 16:06:03 -070012738 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012739 public int getDischargeAmountScreenOn() {
12740 synchronized(this) {
12741 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070012742 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012743 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12744 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12745 }
12746 return val;
12747 }
12748 }
12749
Mike Mac2f518a2017-09-19 16:06:03 -070012750 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012751 public int getDischargeAmountScreenOnSinceCharge() {
12752 synchronized(this) {
12753 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070012754 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012755 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12756 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12757 }
12758 return val;
12759 }
12760 }
12761
Mike Mac2f518a2017-09-19 16:06:03 -070012762 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012763 public int getDischargeAmountScreenOff() {
12764 synchronized(this) {
12765 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070012766 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012767 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12768 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12769 }
Mike Mac2f518a2017-09-19 16:06:03 -070012770 // For backward compatibility, doze discharge is counted into screen off.
12771 return val + getDischargeAmountScreenDoze();
12772 }
12773 }
12774
12775 @Override
12776 public int getDischargeAmountScreenOffSinceCharge() {
12777 synchronized(this) {
12778 int val = mDischargeAmountScreenOffSinceCharge;
12779 if (mOnBattery && isScreenOff(mScreenState)
12780 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12781 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12782 }
12783 // For backward compatibility, doze discharge is counted into screen off.
12784 return val + getDischargeAmountScreenDozeSinceCharge();
12785 }
12786 }
12787
12788 @Override
12789 public int getDischargeAmountScreenDoze() {
12790 synchronized(this) {
12791 int val = mDischargeAmountScreenDoze;
12792 if (mOnBattery && isScreenDoze(mScreenState)
12793 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
12794 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
12795 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012796 return val;
12797 }
12798 }
12799
Mike Mac2f518a2017-09-19 16:06:03 -070012800 @Override
12801 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012802 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070012803 int val = mDischargeAmountScreenDozeSinceCharge;
12804 if (mOnBattery && isScreenDoze(mScreenState)
12805 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
12806 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012807 }
12808 return val;
12809 }
12810 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012812 /**
12813 * Retrieve the statistics object for a particular uid, creating if needed.
12814 */
12815 public Uid getUidStatsLocked(int uid) {
12816 Uid u = mUidStats.get(uid);
12817 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080012818 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012819 mUidStats.put(uid, u);
12820 }
12821 return u;
12822 }
12823
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012824 /**
12825 * Retrieve the statistics object for a particular uid. Returns null if the object is not
12826 * available.
12827 */
12828 public Uid getAvailableUidStatsLocked(int uid) {
12829 Uid u = mUidStats.get(uid);
12830 return u;
12831 }
12832
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012833 public void onCleanupUserLocked(int userId) {
12834 final int firstUidForUser = UserHandle.getUid(userId, 0);
12835 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
12836 mKernelUidCpuFreqTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
12837 mKernelUidCpuTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012838 if (mKernelSingleUidTimeReader != null) {
12839 mKernelSingleUidTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
12840 }
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012841 }
12842
12843 public void onUserRemovedLocked(int userId) {
12844 final int firstUidForUser = UserHandle.getUid(userId, 0);
12845 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
12846 mUidStats.put(firstUidForUser, null);
12847 mUidStats.put(lastUidForUser, null);
12848 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
12849 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
12850 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
12851 }
12852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012853 /**
12854 * Remove the statistics object for a particular uid.
12855 */
12856 public void removeUidStatsLocked(int uid) {
Adam Lesinskib83ffee2015-05-12 14:43:47 -070012857 mKernelUidCpuTimeReader.removeUid(uid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -070012858 mKernelUidCpuFreqTimeReader.removeUid(uid);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012859 if (mKernelSingleUidTimeReader != null) {
12860 mKernelSingleUidTimeReader.removeUid(uid);
12861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012862 mUidStats.remove(uid);
12863 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070012864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012865 /**
12866 * Retrieve the statistics object for a particular process, creating
12867 * if needed.
12868 */
12869 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012870 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012871 Uid u = getUidStatsLocked(uid);
12872 return u.getProcessStatsLocked(name);
12873 }
12874
12875 /**
12876 * Retrieve the statistics object for a particular process, creating
12877 * if needed.
12878 */
12879 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012880 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012881 Uid u = getUidStatsLocked(uid);
12882 return u.getPackageStatsLocked(pkg);
12883 }
12884
12885 /**
12886 * Retrieve the statistics object for a particular service, creating
12887 * if needed.
12888 */
12889 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012890 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012891 Uid u = getUidStatsLocked(uid);
12892 return u.getServiceStatsLocked(pkg, name);
12893 }
12894
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012895 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012896 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012897 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012898 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012899 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012900
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012901 public boolean trackPerProcStateCpuTimes() {
12902 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
12903 }
12904
12905 public void systemServicesReady(Context context) {
12906 mConstants.startObserving(context.getContentResolver());
12907 }
12908
12909 @VisibleForTesting
12910 public final class Constants extends ContentObserver {
12911 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
12912 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080012913 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
12914 = "track_cpu_active_cluster_time";
12915 public static final String KEY_READ_BINARY_CPU_TIME
12916 = "read_binary_cpu_time";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012917
12918 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080012919 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
12920 private static final boolean DEFAULT_READ_BINARY_CPU_TIME = false;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012921
12922 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080012923 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
12924 // Not used right now.
12925 public boolean READ_BINARY_CPU_TIME = DEFAULT_READ_BINARY_CPU_TIME;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012926
12927 private ContentResolver mResolver;
12928 private final KeyValueListParser mParser = new KeyValueListParser(',');
12929
12930 public Constants(Handler handler) {
12931 super(handler);
12932 }
12933
12934 public void startObserving(ContentResolver resolver) {
12935 mResolver = resolver;
12936 mResolver.registerContentObserver(
12937 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
12938 false /* notifyForDescendants */, this);
12939 updateConstants();
12940 }
12941
12942 @Override
12943 public void onChange(boolean selfChange, Uri uri) {
12944 updateConstants();
12945 }
12946
12947 private void updateConstants() {
12948 synchronized (BatteryStatsImpl.this) {
12949 try {
12950 mParser.setString(Settings.Global.getString(mResolver,
12951 Settings.Global.BATTERY_STATS_CONSTANTS));
12952 } catch (IllegalArgumentException e) {
12953 // Failed to parse the settings string, log this and move on
12954 // with defaults.
12955 Slog.e(TAG, "Bad batterystats settings", e);
12956 }
12957
12958 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
12959 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
12960 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080012961 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
12962 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
12963 READ_BINARY_CPU_TIME = mParser.getBoolean(
12964 KEY_READ_BINARY_CPU_TIME, DEFAULT_READ_BINARY_CPU_TIME);
12965
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012966 }
12967 }
12968
12969 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
12970 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
12971 if (isEnabled && !wasEnabled) {
12972 mKernelSingleUidTimeReader.markDataAsStale(true);
12973 mExternalSync.scheduleCpuSyncDueToSettingChange();
12974 }
12975 }
12976
12977 public void dumpLocked(PrintWriter pw) {
12978 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
12979 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080012980 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
12981 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
12982 pw.print(KEY_READ_BINARY_CPU_TIME); pw.print("=");
12983 pw.println(READ_BINARY_CPU_TIME);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012984 }
12985 }
12986
12987 public void dumpConstantsLocked(PrintWriter pw) {
12988 mConstants.dumpLocked(pw);
12989 }
12990
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012991 Parcel mPendingWrite = null;
12992 final ReentrantLock mWriteLock = new ReentrantLock();
12993
12994 public void writeAsyncLocked() {
12995 writeLocked(false);
12996 }
12997
12998 public void writeSyncLocked() {
12999 writeLocked(true);
13000 }
13001
13002 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013003 if (mFile == null) {
13004 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013005 return;
13006 }
13007
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013008 if (mShuttingDown) {
13009 return;
13010 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013011
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013012 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013013 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013014 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013015
13016 if (mPendingWrite != null) {
13017 mPendingWrite.recycle();
13018 }
13019 mPendingWrite = out;
13020
13021 if (sync) {
13022 commitPendingDataToDisk();
13023 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013024 BackgroundThread.getHandler().post(new Runnable() {
13025 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013026 commitPendingDataToDisk();
13027 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013028 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013029 }
13030 }
13031
13032 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013033 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013034 synchronized (this) {
13035 next = mPendingWrite;
13036 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013037 if (next == null) {
13038 return;
13039 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013040 }
13041
Amith Yamasanid2450862017-02-07 15:58:24 -080013042 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013043 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013044 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013045 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013046 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013047 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013048 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013049 mFile.commit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013050 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013051 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013052 mFile.rollback();
13053 } finally {
13054 next.recycle();
13055 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013057 }
13058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013059 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013060 if (mDailyFile != null) {
13061 readDailyStatsLocked();
13062 }
13063
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013064 if (mFile == null) {
13065 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013066 return;
13067 }
13068
13069 mUidStats.clear();
13070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013071 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013072 File file = mFile.chooseForRead();
13073 if (!file.exists()) {
13074 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013075 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013076 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013077
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013078 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013079 Parcel in = Parcel.obtain();
13080 in.unmarshall(raw, 0, raw.length);
13081 in.setDataPosition(0);
13082 stream.close();
13083
13084 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013085 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013086 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013087 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013088 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013089
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013090 mEndPlatformVersion = Build.ID;
13091
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013092 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013093 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013094 final long elapsedRealtime = mClocks.elapsedRealtime();
13095 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013096 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013097 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013098 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013099 addHistoryBufferLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
13100 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013101 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013102
13103 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013104 }
13105
13106 public int describeContents() {
13107 return 0;
13108 }
13109
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013110 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013111 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013112
13113 mHistoryBuffer.setDataSize(0);
13114 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013115 mHistoryTagPool.clear();
13116 mNextHistoryTagIdx = 0;
13117 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013118
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013119 int numTags = in.readInt();
13120 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013121 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013122 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013123 if (str == null) {
13124 throw new ParcelFormatException("null history tag string");
13125 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013126 int uid = in.readInt();
13127 HistoryTag tag = new HistoryTag();
13128 tag.string = str;
13129 tag.uid = uid;
13130 tag.poolIdx = idx;
13131 mHistoryTagPool.put(tag, idx);
13132 if (idx >= mNextHistoryTagIdx) {
13133 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013134 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013135 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013136 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013137
13138 int bufSize = in.readInt();
13139 int curPos = in.dataPosition();
13140 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013141 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13142 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013143 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013144 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13145 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013146 } else {
13147 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13148 + " bytes at " + curPos);
13149 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13150 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013151 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013152
Dianne Hackbornae384452011-06-28 12:33:48 -070013153 if (andOldHistory) {
13154 readOldHistory(in);
13155 }
13156
13157 if (DEBUG_HISTORY) {
13158 StringBuilder sb = new StringBuilder(128);
13159 sb.append("****************** OLD mHistoryBaseTime: ");
13160 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13161 Slog.i(TAG, sb.toString());
13162 }
13163 mHistoryBaseTime = historyBaseTime;
13164 if (DEBUG_HISTORY) {
13165 StringBuilder sb = new StringBuilder(128);
13166 sb.append("****************** NEW mHistoryBaseTime: ");
13167 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13168 Slog.i(TAG, sb.toString());
13169 }
13170
13171 // We are just arbitrarily going to insert 1 minute from the sample of
13172 // the last run until samples in this run.
13173 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013174 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013175 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013176 if (DEBUG_HISTORY) {
13177 StringBuilder sb = new StringBuilder(128);
13178 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13179 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13180 Slog.i(TAG, sb.toString());
13181 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013182 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013183 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013184
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013185 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013186 if (!USE_OLD_HISTORY) {
13187 return;
13188 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013189 mHistory = mHistoryEnd = mHistoryCache = null;
13190 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013191 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013192 HistoryItem rec = new HistoryItem(time, in);
13193 addHistoryRecordLocked(rec);
13194 }
13195 }
13196
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013197 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013198 if (DEBUG_HISTORY) {
13199 StringBuilder sb = new StringBuilder(128);
13200 sb.append("****************** WRITING mHistoryBaseTime: ");
13201 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013202 sb.append(" mLastHistoryElapsedRealtime: ");
13203 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013204 Slog.i(TAG, sb.toString());
13205 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013206 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013207 if (!inclData) {
13208 out.writeInt(0);
13209 out.writeInt(0);
13210 return;
13211 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013212 out.writeInt(mHistoryTagPool.size());
13213 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13214 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013215 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013216 out.writeString(tag.string);
13217 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013218 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013219 out.writeInt(mHistoryBuffer.dataSize());
13220 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13221 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13222 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013223
13224 if (andOldHistory) {
13225 writeOldHistory(out);
13226 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013227 }
13228
13229 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013230 if (!USE_OLD_HISTORY) {
13231 return;
13232 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013233 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013234 while (rec != null) {
13235 if (rec.time >= 0) rec.writeToParcel(out, 0);
13236 rec = rec.next;
13237 }
13238 out.writeLong(-1);
13239 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013240
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013241 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013242 final int version = in.readInt();
13243 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013244 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013245 + ", expected " + VERSION + "; erasing old stats");
13246 return;
13247 }
13248
Dianne Hackbornae384452011-06-28 12:33:48 -070013249 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013251 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013252 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013253 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013254 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013255 mStartPlatformVersion = in.readString();
13256 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013257 mOnBatteryTimeBase.readSummaryFromParcel(in);
13258 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013259 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013260 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013261 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013262 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013263 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013264 mMinLearnedBatteryCapacity = in.readInt();
13265 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013266 mLowDischargeAmountSinceCharge = in.readInt();
13267 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013268 mDischargeAmountScreenOnSinceCharge = in.readInt();
13269 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013270 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013271 mDischargeStepTracker.readFromParcel(in);
13272 mChargeStepTracker.readFromParcel(in);
13273 mDailyDischargeStepTracker.readFromParcel(in);
13274 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013275 mDischargeCounter.readSummaryFromParcelLocked(in);
13276 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013277 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013278 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13279 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013280 int NPKG = in.readInt();
13281 if (NPKG > 0) {
13282 mDailyPackageChanges = new ArrayList<>(NPKG);
13283 while (NPKG > 0) {
13284 NPKG--;
13285 PackageChange pc = new PackageChange();
13286 pc.mPackageName = in.readString();
13287 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013288 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013289 mDailyPackageChanges.add(pc);
13290 }
13291 } else {
13292 mDailyPackageChanges = null;
13293 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013294 mDailyStartTime = in.readLong();
13295 mNextMinDailyDeadline = in.readLong();
13296 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013298 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013299
Jeff Browne95c3cd2014-05-02 16:59:26 -070013300 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013301 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013302 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013303 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13304 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13305 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013306 mInteractive = false;
13307 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013308 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013309 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013310 mLongestLightIdleTime = in.readLong();
13311 mLongestFullIdleTime = in.readLong();
13312 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13313 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13314 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013315 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013316 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013317 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013318 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13319 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013320 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013321 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13322 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13323 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013324 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013325 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13326 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013327 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013328 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013329 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013330 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013331 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013332 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13333 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013334 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013335 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013336 mWifiOn = false;
13337 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013338 mGlobalWifiRunning = false;
13339 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013340 for (int i=0; i<NUM_WIFI_STATES; i++) {
13341 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13342 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013343 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13344 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13345 }
13346 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13347 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13348 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013349 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13350 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013351 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13352 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13353 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013354 mBluetoothActivity.readSummaryFromParcel(in);
13355 mModemActivity.readSummaryFromParcel(in);
13356 mHasWifiReporting = in.readInt() != 0;
13357 mHasBluetoothReporting = in.readInt() != 0;
13358 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013359
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013360 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013361 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013362 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013363 mCameraOnNesting = 0;
13364 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013365 mBluetoothScanNesting = 0;
13366 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013367
Bookatz50df7112017-08-04 14:53:26 -070013368 int NRPMS = in.readInt();
13369 if (NRPMS > 10000) {
13370 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13371 }
13372 for (int irpm = 0; irpm < NRPMS; irpm++) {
13373 if (in.readInt() != 0) {
13374 String rpmName = in.readString();
13375 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13376 }
13377 }
13378 int NSORPMS = in.readInt();
13379 if (NSORPMS > 10000) {
13380 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13381 }
13382 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13383 if (in.readInt() != 0) {
13384 String rpmName = in.readString();
13385 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13386 }
13387 }
13388
Evan Millarc64edde2009-04-18 12:26:32 -070013389 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013390 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013391 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013392 }
Evan Millarc64edde2009-04-18 12:26:32 -070013393 for (int ikw = 0; ikw < NKW; ikw++) {
13394 if (in.readInt() != 0) {
13395 String kwltName = in.readString();
13396 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13397 }
13398 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013399
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013400 int NWR = in.readInt();
13401 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013402 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013403 }
13404 for (int iwr = 0; iwr < NWR; iwr++) {
13405 if (in.readInt() != 0) {
13406 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013407 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013408 }
13409 }
13410
James Carr3a226052016-07-01 14:49:52 -070013411 int NMS = in.readInt();
13412 for (int ims = 0; ims < NMS; ims++) {
13413 if (in.readInt() != 0) {
13414 long kmstName = in.readLong();
13415 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13416 }
13417 }
13418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013419 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013420 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013421 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013423 for (int iu = 0; iu < NU; iu++) {
13424 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013425 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013426 mUidStats.put(uid, u);
13427
Bookatz867c0d72017-03-07 18:23:42 -080013428 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013429 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013430
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013431 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013432 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013433 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013434 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013435 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013436 if (in.readInt() != 0) {
13437 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13438 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013439 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013440 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013441 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013442 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013443 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13444 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13445 if (in.readInt() != 0) {
13446 u.makeWifiBatchedScanBin(i, null);
13447 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13448 }
13449 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013450 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013451 if (in.readInt() != 0) {
13452 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13453 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013454 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013455 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013456 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013457 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013458 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13459 }
13460 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013461 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13462 }
13463 if (in.readInt() != 0) {
13464 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13465 }
13466 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013467 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13468 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013469 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013470 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13471 }
13472 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013473 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13474 }
13475 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013476 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13477 }
Bookatz956f36bf2017-04-28 09:48:17 -070013478 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013479 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13480 }
13481 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013482 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13483 }
Bookatzb1f04f32017-05-19 13:57:32 -070013484 if (in.readInt() != 0) {
13485 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13486 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013487 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013488 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13489 if (in.readInt() != 0) {
13490 u.makeProcessState(i, null);
13491 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13492 }
13493 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013494 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013495 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013496 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013497
Dianne Hackborn617f8772009-03-31 15:04:46 -070013498 if (in.readInt() != 0) {
13499 if (u.mUserActivityCounters == null) {
13500 u.initUserActivityLocked();
13501 }
13502 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13503 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13504 }
13505 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013506
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013507 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013508 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013509 u.initNetworkActivityLocked();
13510 }
13511 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013512 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13513 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013514 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013515 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13516 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013517 }
13518
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013519 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13520 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13521
Adam Lesinski6832f392015-09-05 18:05:40 -070013522 if (in.readInt() != 0) {
13523 final int numClusters = in.readInt();
13524 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13525 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013526 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013527
Sudheer Shankaaf857412017-07-21 00:14:24 -070013528 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013529 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013530 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013531 final int NSB = in.readInt();
13532 if (mPowerProfile != null &&
13533 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13534 throw new ParcelFormatException("File corrupt: too many speed bins " +
13535 NSB);
13536 }
13537
Sudheer Shankaaf857412017-07-21 00:14:24 -070013538 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070013539 for (int speed = 0; speed < NSB; speed++) {
13540 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013541 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070013542 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013543 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070013544 }
13545 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070013546 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013547 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070013548 }
13549 }
13550 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013551 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013552 }
13553
Sudheer Shanka59f5c002017-05-15 10:57:15 -070013554 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13555 in, mOnBatteryTimeBase);
13556 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13557 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070013558
13559 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
13560 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
13561
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013562 int length = in.readInt();
13563 if (length == Uid.NUM_PROCESS_STATE) {
13564 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
13565 for (int procState = 0; procState < length; ++procState) {
13566 u.mProcStateTimeMs[procState]
13567 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13568 in, mOnBatteryTimeBase);
13569 }
13570 } else {
13571 u.mProcStateTimeMs = null;
13572 }
13573 length = in.readInt();
13574 if (length == Uid.NUM_PROCESS_STATE) {
13575 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
13576 for (int procState = 0; procState < length; ++procState) {
13577 u.mProcStateScreenOffTimeMs[procState]
13578 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13579 in, mOnBatteryScreenOffTimeBase);
13580 }
13581 } else {
13582 u.mProcStateScreenOffTimeMs = null;
13583 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070013584
13585 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070013586 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13587 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
13588 } else {
13589 u.mMobileRadioApWakeupCount = null;
13590 }
13591
13592 if (in.readInt() != 0) {
13593 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13594 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
13595 } else {
13596 u.mWifiRadioApWakeupCount = null;
13597 }
13598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013599 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013600 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013601 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013603 for (int iw = 0; iw < NW; iw++) {
13604 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013605 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013606 }
13607
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013608 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013609 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013610 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013611 }
13612 for (int is = 0; is < NS; is++) {
13613 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013614 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013615 }
13616
13617 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013618 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013619 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013620 }
13621 for (int ij = 0; ij < NJ; ij++) {
13622 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013623 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013624 }
13625
Dianne Hackborn94326cb2017-06-28 16:17:20 -070013626 u.readJobCompletionsFromParcelLocked(in);
13627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013628 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013629 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013630 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013632 for (int is = 0; is < NP; is++) {
13633 int seNumber = in.readInt();
13634 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080013635 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013636 }
13637 }
13638
13639 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013640 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013641 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013643 for (int ip = 0; ip < NP; ip++) {
13644 String procName = in.readString();
13645 Uid.Proc p = u.getProcessStatsLocked(procName);
13646 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013647 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013648 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013649 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013650 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
13651 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013652 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013653 }
13654
13655 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013656 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013657 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013659 for (int ip = 0; ip < NP; ip++) {
13660 String pkgName = in.readString();
13661 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013662 final int NWA = in.readInt();
13663 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013664 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013665 }
13666 p.mWakeupAlarms.clear();
13667 for (int iwa=0; iwa<NWA; iwa++) {
13668 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070013669 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013670 c.readSummaryFromParcelLocked(in);
13671 p.mWakeupAlarms.put(tag, c);
13672 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013673 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013674 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013675 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013677 for (int is = 0; is < NS; is++) {
13678 String servName = in.readString();
13679 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
13680 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013681 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013682 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013683 }
13684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013685 }
13686 }
13687
13688 /**
13689 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
13690 * disk. This format does not allow a lossless round-trip.
13691 *
13692 * @param out the Parcel to be written to.
13693 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013694 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013695 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013696
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013697 // Pull the clock time. This may update the time and make a new history entry
13698 // if we had originally pulled a time before the RTC was set.
13699 long startClockTime = getStartClockTime();
13700
Joe Onoratoabded112016-02-08 16:49:39 -080013701 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
13702 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013703
13704 out.writeInt(VERSION);
13705
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013706 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013708 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013709 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013710 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013711 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013712 out.writeString(mStartPlatformVersion);
13713 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013714 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
13715 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013716 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013717 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070013718 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013719 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013720 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070013721 out.writeInt(mMinLearnedBatteryCapacity);
13722 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080013723 out.writeInt(getLowDischargeAmountSinceCharge());
13724 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013725 out.writeInt(getDischargeAmountScreenOnSinceCharge());
13726 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070013727 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013728 mDischargeStepTracker.writeToParcel(out);
13729 mChargeStepTracker.writeToParcel(out);
13730 mDailyDischargeStepTracker.writeToParcel(out);
13731 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070013732 mDischargeCounter.writeSummaryFromParcelLocked(out);
13733 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070013734 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080013735 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
13736 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013737 if (mDailyPackageChanges != null) {
13738 final int NPKG = mDailyPackageChanges.size();
13739 out.writeInt(NPKG);
13740 for (int i=0; i<NPKG; i++) {
13741 PackageChange pc = mDailyPackageChanges.get(i);
13742 out.writeString(pc.mPackageName);
13743 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070013744 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013745 }
13746 } else {
13747 out.writeInt(0);
13748 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013749 out.writeLong(mDailyStartTime);
13750 out.writeLong(mNextMinDailyDeadline);
13751 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013752
13753 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070013754 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013755 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013756 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013757 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013758 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013759 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013760 out.writeLong(mLongestLightIdleTime);
13761 out.writeLong(mLongestFullIdleTime);
13762 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13763 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13764 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013765 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013766 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080013767 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013768 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013769 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013770 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013771 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013772 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013773 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013774 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013775 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
13776 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013777 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013778 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13779 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013780 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013781 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
13782 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013783 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013784 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13785 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013786 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013787 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013788 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013789 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13790 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13791 }
13792 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13793 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13794 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013795 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13796 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013797 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13798 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13799 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013800 mBluetoothActivity.writeSummaryToParcel(out);
13801 mModemActivity.writeSummaryToParcel(out);
13802 out.writeInt(mHasWifiReporting ? 1 : 0);
13803 out.writeInt(mHasBluetoothReporting ? 1 : 0);
13804 out.writeInt(mHasModemReporting ? 1 : 0);
13805
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013806 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013807 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013808 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013809 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013810
Bookatz50df7112017-08-04 14:53:26 -070013811 out.writeInt(mRpmStats.size());
13812 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
13813 Timer rpmt = ent.getValue();
13814 if (rpmt != null) {
13815 out.writeInt(1);
13816 out.writeString(ent.getKey());
13817 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13818 } else {
13819 out.writeInt(0);
13820 }
13821 }
13822 out.writeInt(mScreenOffRpmStats.size());
13823 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
13824 Timer rpmt = ent.getValue();
13825 if (rpmt != null) {
13826 out.writeInt(1);
13827 out.writeString(ent.getKey());
13828 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13829 } else {
13830 out.writeInt(0);
13831 }
13832 }
13833
Evan Millarc64edde2009-04-18 12:26:32 -070013834 out.writeInt(mKernelWakelockStats.size());
13835 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
13836 Timer kwlt = ent.getValue();
13837 if (kwlt != null) {
13838 out.writeInt(1);
13839 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013840 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13841 } else {
13842 out.writeInt(0);
13843 }
13844 }
13845
13846 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013847 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
13848 SamplingTimer timer = ent.getValue();
13849 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013850 out.writeInt(1);
13851 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013852 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070013853 } else {
13854 out.writeInt(0);
13855 }
13856 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013857
James Carr3a226052016-07-01 14:49:52 -070013858 out.writeInt(mKernelMemoryStats.size());
13859 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
13860 Timer kmt = mKernelMemoryStats.valueAt(i);
13861 if (kmt != null) {
13862 out.writeInt(1);
13863 out.writeLong(mKernelMemoryStats.keyAt(i));
13864 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13865 } else {
13866 out.writeInt(0);
13867 }
13868 }
13869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013870 final int NU = mUidStats.size();
13871 out.writeInt(NU);
13872 for (int iu = 0; iu < NU; iu++) {
13873 out.writeInt(mUidStats.keyAt(iu));
13874 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013875
Bookatz867c0d72017-03-07 18:23:42 -080013876 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070013877 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080013878
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013879 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013880 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013881 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013882 } else {
13883 out.writeInt(0);
13884 }
13885 if (u.mFullWifiLockTimer != null) {
13886 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013887 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013888 } else {
13889 out.writeInt(0);
13890 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013891 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013892 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013893 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013894 } else {
13895 out.writeInt(0);
13896 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013897 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13898 if (u.mWifiBatchedScanTimer[i] != null) {
13899 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013900 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070013901 } else {
13902 out.writeInt(0);
13903 }
13904 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013905 if (u.mWifiMulticastTimer != null) {
13906 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013907 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013908 } else {
13909 out.writeInt(0);
13910 }
13911 if (u.mAudioTurnedOnTimer != null) {
13912 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013913 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013914 } else {
13915 out.writeInt(0);
13916 }
13917 if (u.mVideoTurnedOnTimer != null) {
13918 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013919 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013920 } else {
13921 out.writeInt(0);
13922 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013923 if (u.mFlashlightTurnedOnTimer != null) {
13924 out.writeInt(1);
13925 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13926 } else {
13927 out.writeInt(0);
13928 }
13929 if (u.mCameraTurnedOnTimer != null) {
13930 out.writeInt(1);
13931 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13932 } else {
13933 out.writeInt(0);
13934 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013935 if (u.mForegroundActivityTimer != null) {
13936 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013937 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013938 } else {
13939 out.writeInt(0);
13940 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013941 if (u.mForegroundServiceTimer != null) {
13942 out.writeInt(1);
13943 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13944 } else {
13945 out.writeInt(0);
13946 }
Bookatzc8c44962017-05-11 12:12:54 -070013947 if (u.mAggregatedPartialWakelockTimer != null) {
13948 out.writeInt(1);
13949 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13950 } else {
13951 out.writeInt(0);
13952 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013953 if (u.mBluetoothScanTimer != null) {
13954 out.writeInt(1);
13955 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13956 } else {
13957 out.writeInt(0);
13958 }
Bookatzb1f04f32017-05-19 13:57:32 -070013959 if (u.mBluetoothUnoptimizedScanTimer != null) {
13960 out.writeInt(1);
13961 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13962 } else {
13963 out.writeInt(0);
13964 }
Bookatz956f36bf2017-04-28 09:48:17 -070013965 if (u.mBluetoothScanResultCounter != null) {
13966 out.writeInt(1);
13967 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
13968 } else {
13969 out.writeInt(0);
13970 }
Bookatzb1f04f32017-05-19 13:57:32 -070013971 if (u.mBluetoothScanResultBgCounter != null) {
13972 out.writeInt(1);
13973 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
13974 } else {
13975 out.writeInt(0);
13976 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070013977 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13978 if (u.mProcessStateTimer[i] != null) {
13979 out.writeInt(1);
13980 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13981 } else {
13982 out.writeInt(0);
13983 }
13984 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013985 if (u.mVibratorOnTimer != null) {
13986 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013987 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013988 } else {
13989 out.writeInt(0);
13990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013991
Dianne Hackborn617f8772009-03-31 15:04:46 -070013992 if (u.mUserActivityCounters == null) {
13993 out.writeInt(0);
13994 } else {
13995 out.writeInt(1);
13996 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13997 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
13998 }
13999 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014000
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014001 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014002 out.writeInt(0);
14003 } else {
14004 out.writeInt(1);
14005 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014006 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14007 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014008 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014009 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14010 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014011 }
14012
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014013 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14014 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14015
Sudheer Shankaaf857412017-07-21 00:14:24 -070014016 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014017 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014018 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14019 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014020 if (cpuSpeeds != null) {
14021 out.writeInt(1);
14022 out.writeInt(cpuSpeeds.length);
14023 for (LongSamplingCounter c : cpuSpeeds) {
14024 if (c != null) {
14025 out.writeInt(1);
14026 c.writeSummaryFromParcelLocked(out);
14027 } else {
14028 out.writeInt(0);
14029 }
14030 }
14031 } else {
14032 out.writeInt(0);
14033 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014034 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014035 } else {
14036 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014037 }
14038
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014039 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14040 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014041
Mike Ma3d422c32017-10-25 11:08:57 -070014042 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14043 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14044
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014045 if (u.mProcStateTimeMs != null) {
14046 out.writeInt(u.mProcStateTimeMs.length);
14047 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14048 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14049 }
14050 } else {
14051 out.writeInt(0);
14052 }
14053 if (u.mProcStateScreenOffTimeMs != null) {
14054 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14055 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14056 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14057 }
14058 } else {
14059 out.writeInt(0);
14060 }
14061
Adam Lesinski5f056f62016-07-14 16:56:08 -070014062 if (u.mMobileRadioApWakeupCount != null) {
14063 out.writeInt(1);
14064 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14065 } else {
14066 out.writeInt(0);
14067 }
14068
14069 if (u.mWifiRadioApWakeupCount != null) {
14070 out.writeInt(1);
14071 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14072 } else {
14073 out.writeInt(0);
14074 }
14075
Dianne Hackbornd953c532014-08-16 18:17:38 -070014076 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14077 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014078 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014079 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014080 out.writeString(wakeStats.keyAt(iw));
14081 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014082 if (wl.mTimerFull != null) {
14083 out.writeInt(1);
14084 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14085 } else {
14086 out.writeInt(0);
14087 }
14088 if (wl.mTimerPartial != null) {
14089 out.writeInt(1);
14090 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14091 } else {
14092 out.writeInt(0);
14093 }
14094 if (wl.mTimerWindow != null) {
14095 out.writeInt(1);
14096 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14097 } else {
14098 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014099 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014100 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014101 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014102 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014103 } else {
14104 out.writeInt(0);
14105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014106 }
14107
Bookatz2bffb5b2017-04-13 11:59:33 -070014108 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014109 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014110 out.writeInt(NS);
14111 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014112 out.writeString(syncStats.keyAt(is));
14113 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014114 }
14115
Bookatzaa4594a2017-03-24 12:39:56 -070014116 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014117 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014118 out.writeInt(NJ);
14119 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014120 out.writeString(jobStats.keyAt(ij));
14121 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014122 }
14123
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014124 u.writeJobCompletionsToParcelLocked(out);
14125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014126 int NSE = u.mSensorStats.size();
14127 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014128 for (int ise=0; ise<NSE; ise++) {
14129 out.writeInt(u.mSensorStats.keyAt(ise));
14130 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14131 if (se.mTimer != null) {
14132 out.writeInt(1);
14133 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14134 } else {
14135 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014136 }
14137 }
14138
14139 int NP = u.mProcessStats.size();
14140 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014141 for (int ip=0; ip<NP; ip++) {
14142 out.writeString(u.mProcessStats.keyAt(ip));
14143 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14144 out.writeLong(ps.mUserTime);
14145 out.writeLong(ps.mSystemTime);
14146 out.writeLong(ps.mForegroundTime);
14147 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014148 out.writeInt(ps.mNumCrashes);
14149 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014150 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014151 }
14152
14153 NP = u.mPackageStats.size();
14154 out.writeInt(NP);
14155 if (NP > 0) {
14156 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14157 : u.mPackageStats.entrySet()) {
14158 out.writeString(ent.getKey());
14159 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014160 final int NWA = ps.mWakeupAlarms.size();
14161 out.writeInt(NWA);
14162 for (int iwa=0; iwa<NWA; iwa++) {
14163 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14164 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14165 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014166 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014167 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014168 for (int is=0; is<NS; is++) {
14169 out.writeString(ps.mServiceStats.keyAt(is));
14170 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14171 long time = ss.getStartTimeToNowLocked(
14172 mOnBatteryTimeBase.getUptime(NOW_SYS));
14173 out.writeLong(time);
14174 out.writeInt(ss.mStarts);
14175 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014176 }
14177 }
14178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014179 }
14180 }
14181
14182 public void readFromParcel(Parcel in) {
14183 readFromParcelLocked(in);
14184 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014186 void readFromParcelLocked(Parcel in) {
14187 int magic = in.readInt();
14188 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014189 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014190 }
14191
Dianne Hackbornae384452011-06-28 12:33:48 -070014192 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014194 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014195 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014196 mStartPlatformVersion = in.readString();
14197 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014198 mUptime = in.readLong();
14199 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014200 mRealtime = in.readLong();
14201 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014202 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014203 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014204 mMinLearnedBatteryCapacity = in.readInt();
14205 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014206 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014207 mOnBatteryTimeBase.readFromParcel(in);
14208 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14209
Jeff Browne95c3cd2014-05-02 16:59:26 -070014210 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014211 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014212 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014213 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014214 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14215 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014216 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014217 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014218 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014219 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014220 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14221 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014222 mLongestLightIdleTime = in.readLong();
14223 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014224 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14225 mOnBatteryTimeBase, in);
14226 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14227 mOnBatteryTimeBase, in);
14228 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14229 mOnBatteryTimeBase, in);
14230 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14231 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014232 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014233 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014234 null, mOnBatteryTimeBase, in);
14235 }
Joe Onoratoabded112016-02-08 16:49:39 -080014236 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14237 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014238 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014239 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014240 null, mOnBatteryTimeBase, in);
14241 }
14242 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14243 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14244 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14245 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014246 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014247 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14248 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014249 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014250 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014251 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014252 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14253 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014254 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14255 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014256 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014257 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014258 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014259 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014260 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14261 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014262 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014263 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014264 null, mOnBatteryTimeBase, in);
14265 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014266 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014267 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014268 null, mOnBatteryTimeBase, in);
14269 }
14270 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014271 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014272 null, mOnBatteryTimeBase, in);
14273 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014274 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14275 mOnBatteryTimeBase, in);
14276 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14277 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014278 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14279 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14280 null, mOnBatteryTimeBase, in);
14281 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014282 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14283 NUM_BT_TX_LEVELS, in);
14284 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14285 ModemActivityInfo.TX_POWER_LEVELS, in);
14286 mHasWifiReporting = in.readInt() != 0;
14287 mHasBluetoothReporting = in.readInt() != 0;
14288 mHasModemReporting = in.readInt() != 0;
14289
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014290 mNumConnectivityChange = in.readInt();
14291 mLoadedNumConnectivityChange = in.readInt();
14292 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014293 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014294 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014295 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014296 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014297 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014298 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014299 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014300 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014301 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014302 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014303 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014304 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014305 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014306 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014307 mLowDischargeAmountSinceCharge = in.readInt();
14308 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014309 mDischargeAmountScreenOn = in.readInt();
14310 mDischargeAmountScreenOnSinceCharge = in.readInt();
14311 mDischargeAmountScreenOff = in.readInt();
14312 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014313 mDischargeAmountScreenDoze = in.readInt();
14314 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014315 mDischargeStepTracker.readFromParcel(in);
14316 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014317 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014318 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14319 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014320 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14321 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014322 mLastWriteTime = in.readLong();
14323
Bookatz50df7112017-08-04 14:53:26 -070014324 mRpmStats.clear();
14325 int NRPMS = in.readInt();
14326 for (int irpm = 0; irpm < NRPMS; irpm++) {
14327 if (in.readInt() != 0) {
14328 String rpmName = in.readString();
14329 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14330 mRpmStats.put(rpmName, rpmt);
14331 }
14332 }
14333 mScreenOffRpmStats.clear();
14334 int NSORPMS = in.readInt();
14335 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14336 if (in.readInt() != 0) {
14337 String rpmName = in.readString();
14338 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14339 mScreenOffRpmStats.put(rpmName, rpmt);
14340 }
14341 }
14342
Evan Millarc64edde2009-04-18 12:26:32 -070014343 mKernelWakelockStats.clear();
14344 int NKW = in.readInt();
14345 for (int ikw = 0; ikw < NKW; ikw++) {
14346 if (in.readInt() != 0) {
14347 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014348 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014349 mKernelWakelockStats.put(wakelockName, kwlt);
14350 }
14351 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014352
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014353 mWakeupReasonStats.clear();
14354 int NWR = in.readInt();
14355 for (int iwr = 0; iwr < NWR; iwr++) {
14356 if (in.readInt() != 0) {
14357 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014358 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014359 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014360 }
14361 }
14362
James Carr3a226052016-07-01 14:49:52 -070014363 mKernelMemoryStats.clear();
14364 int nmt = in.readInt();
14365 for (int imt = 0; imt < nmt; imt++) {
14366 if (in.readInt() != 0) {
14367 Long bucket = in.readLong();
14368 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14369 mKernelMemoryStats.put(bucket, kmt);
14370 }
14371 }
14372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014373 mPartialTimers.clear();
14374 mFullTimers.clear();
14375 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014376 mWifiRunningTimers.clear();
14377 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014378 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014379 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014380 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014381 mAudioTurnedOnTimers.clear();
14382 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014383 mFlashlightTurnedOnTimers.clear();
14384 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014385
14386 int numUids = in.readInt();
14387 mUidStats.clear();
14388 for (int i = 0; i < numUids; i++) {
14389 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014390 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014391 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014392 mUidStats.append(uid, u);
14393 }
14394 }
14395
14396 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014397 writeToParcelLocked(out, true, flags);
14398 }
14399
14400 public void writeToParcelWithoutUids(Parcel out, int flags) {
14401 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014402 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014403
14404 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014405 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014406 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014407 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014408
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014409 // Pull the clock time. This may update the time and make a new history entry
14410 // if we had originally pulled a time before the RTC was set.
14411 long startClockTime = getStartClockTime();
14412
Joe Onoratoabded112016-02-08 16:49:39 -080014413 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14414 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014415 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14416 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014418 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014419
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014420 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014422 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014423 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014424 out.writeString(mStartPlatformVersion);
14425 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014426 out.writeLong(mUptime);
14427 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014428 out.writeLong(mRealtime);
14429 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014430 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014431 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014432 out.writeInt(mMinLearnedBatteryCapacity);
14433 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014434 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14435 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14436
14437 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014438 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014439 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14440 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14441 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014442 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014443 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014444 out.writeLong(mLongestLightIdleTime);
14445 out.writeLong(mLongestFullIdleTime);
14446 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14447 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14448 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014449 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014450 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14451 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14452 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14453 }
14454 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14455 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14456 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14457 }
14458 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14459 mNetworkByteActivityCounters[i].writeToParcel(out);
14460 mNetworkPacketActivityCounters[i].writeToParcel(out);
14461 }
14462 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14463 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014464 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014465 mMobileRadioActiveUnknownTime.writeToParcel(out);
14466 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014467 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014468 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14469 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14470 for (int i=0; i<NUM_WIFI_STATES; i++) {
14471 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14472 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014473 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14474 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14475 }
14476 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14477 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14478 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014479 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
14480 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014481 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14482 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
14483 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014484 mBluetoothActivity.writeToParcel(out, 0);
14485 mModemActivity.writeToParcel(out, 0);
14486 out.writeInt(mHasWifiReporting ? 1 : 0);
14487 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14488 out.writeInt(mHasModemReporting ? 1 : 0);
14489
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014490 out.writeInt(mNumConnectivityChange);
14491 out.writeInt(mLoadedNumConnectivityChange);
14492 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014493 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014494 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014495 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014496 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014497 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014498 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014499 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014500 out.writeInt(mLowDischargeAmountSinceCharge);
14501 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014502 out.writeInt(mDischargeAmountScreenOn);
14503 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14504 out.writeInt(mDischargeAmountScreenOff);
14505 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014506 out.writeInt(mDischargeAmountScreenDoze);
14507 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014508 mDischargeStepTracker.writeToParcel(out);
14509 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014510 mDischargeCounter.writeToParcel(out);
14511 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014512 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080014513 mDischargeLightDozeCounter.writeToParcel(out);
14514 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014515 out.writeLong(mLastWriteTime);
14516
Bookatz50df7112017-08-04 14:53:26 -070014517 out.writeInt(mRpmStats.size());
14518 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14519 SamplingTimer rpmt = ent.getValue();
14520 if (rpmt != null) {
14521 out.writeInt(1);
14522 out.writeString(ent.getKey());
14523 rpmt.writeToParcel(out, uSecRealtime);
14524 } else {
14525 out.writeInt(0);
14526 }
14527 }
14528 out.writeInt(mScreenOffRpmStats.size());
14529 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14530 SamplingTimer rpmt = ent.getValue();
14531 if (rpmt != null) {
14532 out.writeInt(1);
14533 out.writeString(ent.getKey());
14534 rpmt.writeToParcel(out, uSecRealtime);
14535 } else {
14536 out.writeInt(0);
14537 }
14538 }
14539
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014540 if (inclUids) {
14541 out.writeInt(mKernelWakelockStats.size());
14542 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14543 SamplingTimer kwlt = ent.getValue();
14544 if (kwlt != null) {
14545 out.writeInt(1);
14546 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014547 kwlt.writeToParcel(out, uSecRealtime);
14548 } else {
14549 out.writeInt(0);
14550 }
14551 }
14552 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014553 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14554 SamplingTimer timer = ent.getValue();
14555 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014556 out.writeInt(1);
14557 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014558 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014559 } else {
14560 out.writeInt(0);
14561 }
Evan Millarc64edde2009-04-18 12:26:32 -070014562 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014563 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070014564 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014565 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070014566 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070014567
James Carr3a226052016-07-01 14:49:52 -070014568 out.writeInt(mKernelMemoryStats.size());
14569 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14570 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
14571 if (kmt != null) {
14572 out.writeInt(1);
14573 out.writeLong(mKernelMemoryStats.keyAt(i));
14574 kmt.writeToParcel(out, uSecRealtime);
14575 } else {
14576 out.writeInt(0);
14577 }
14578 }
14579
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014580 if (inclUids) {
14581 int size = mUidStats.size();
14582 out.writeInt(size);
14583 for (int i = 0; i < size; i++) {
14584 out.writeInt(mUidStats.keyAt(i));
14585 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014586
Bookatz867c0d72017-03-07 18:23:42 -080014587 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014588 }
14589 } else {
14590 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014591 }
14592 }
14593
14594 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
14595 new Parcelable.Creator<BatteryStatsImpl>() {
14596 public BatteryStatsImpl createFromParcel(Parcel in) {
14597 return new BatteryStatsImpl(in);
14598 }
14599
14600 public BatteryStatsImpl[] newArray(int size) {
14601 return new BatteryStatsImpl[size];
14602 }
14603 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014604
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014605 public void prepareForDumpLocked() {
14606 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014607 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014608
14609 // Pull the clock time. This may update the time and make a new history entry
14610 // if we had originally pulled a time before the RTC was set.
14611 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014612 }
14613
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014614 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014615 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014616 pw.println("mOnBatteryTimeBase:");
14617 mOnBatteryTimeBase.dump(pw, " ");
14618 pw.println("mOnBatteryScreenOffTimeBase:");
14619 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014620 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070014621 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014622 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070014623 pr.println("*** Screen doze timer:");
14624 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014625 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014626 pr.println("*** Screen brightness #" + i + ":");
14627 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014628 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014629 pr.println("*** Interactive timer:");
14630 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014631 pr.println("*** Power save mode timer:");
14632 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014633 pr.println("*** Device idle mode light timer:");
14634 mDeviceIdleModeLightTimer.logState(pr, " ");
14635 pr.println("*** Device idle mode full timer:");
14636 mDeviceIdleModeFullTimer.logState(pr, " ");
14637 pr.println("*** Device light idling timer:");
14638 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014639 pr.println("*** Device idling timer:");
14640 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014641 pr.println("*** Phone timer:");
14642 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080014643 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070014644 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014645 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014646 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070014647 pr.println("*** Signal scanning :");
14648 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014649 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014650 pr.println("*** Data connection type #" + i + ":");
14651 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014652 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014653 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080014654 pr.println("*** Mobile network active timer:");
14655 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014656 pr.println("*** Mobile network active adjusted timer:");
14657 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014658 pr.println("*** Wifi Multicast WakeLock Timer:");
14659 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014660 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014661 pr.println("*** Wifi timer:");
14662 mWifiOnTimer.logState(pr, " ");
14663 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014664 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014665 for (int i=0; i<NUM_WIFI_STATES; i++) {
14666 pr.println("*** Wifi state #" + i + ":");
14667 mWifiStateTimer[i].logState(pr, " ");
14668 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014669 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14670 pr.println("*** Wifi suppl state #" + i + ":");
14671 mWifiSupplStateTimer[i].logState(pr, " ");
14672 }
14673 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14674 pr.println("*** Wifi signal strength #" + i + ":");
14675 mWifiSignalStrengthsTimer[i].logState(pr, " ");
14676 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014677 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14678 pr.println("*** GPS signal quality #" + i + ":");
14679 mGpsSignalQualityTimer[i].logState(pr, " ");
14680 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014681 pr.println("*** Flashlight timer:");
14682 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014683 pr.println("*** Camera timer:");
14684 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014685 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014686 super.dumpLocked(context, pw, flags, reqUid, histStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014688}