blob: 3c99467806a1fb31b014c312b701d33b8ce8b79f [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 Ma3d422c32017-10-25 11:08:57 -07003915 mKernelUidCpuActiveTimeReader.removeUid(isolatedUid);
3916 mKernelUidCpuClusterTimeReader.removeUid(isolatedUid);
Adam Lesinski61db88f2015-07-01 15:05:07 -07003917 }
3918
Dianne Hackborn099bc622014-01-22 13:39:16 -08003919 public int mapUid(int uid) {
3920 int isolated = mIsolatedUids.get(uid, -1);
3921 return isolated > 0 ? isolated : uid;
3922 }
3923
3924 public void noteEventLocked(int code, String name, int uid) {
3925 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003926 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3927 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003928 }
Joe Onoratoabded112016-02-08 16:49:39 -08003929 final long elapsedRealtime = mClocks.elapsedRealtime();
3930 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003931 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003932 }
3933
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003934 boolean ensureStartClockTime(final long currentTime) {
3935 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
3936 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
3937 // If the start clock time has changed by more than a year, then presumably
3938 // the previous time was completely bogus. So we are going to figure out a
3939 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08003940 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003941 return true;
3942 }
3943 return false;
3944 }
3945
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003946 public void noteCurrentTimeChangedLocked() {
3947 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003948 final long elapsedRealtime = mClocks.elapsedRealtime();
3949 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003950 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003951 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003952 }
3953
Dianne Hackborn61659e52014-07-09 16:13:01 -07003954 public void noteProcessStartLocked(String name, int uid) {
3955 uid = mapUid(uid);
3956 if (isOnBattery()) {
3957 Uid u = getUidStatsLocked(uid);
3958 u.getProcessStatsLocked(name).incStartsLocked();
3959 }
3960 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3961 return;
3962 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003963 if (!mRecordAllHistory) {
3964 return;
3965 }
Joe Onoratoabded112016-02-08 16:49:39 -08003966 final long elapsedRealtime = mClocks.elapsedRealtime();
3967 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07003968 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
3969 }
3970
Dianne Hackborn1e01d162014-12-04 17:46:42 -08003971 public void noteProcessCrashLocked(String name, int uid) {
3972 uid = mapUid(uid);
3973 if (isOnBattery()) {
3974 Uid u = getUidStatsLocked(uid);
3975 u.getProcessStatsLocked(name).incNumCrashesLocked();
3976 }
3977 }
3978
3979 public void noteProcessAnrLocked(String name, int uid) {
3980 uid = mapUid(uid);
3981 if (isOnBattery()) {
3982 Uid u = getUidStatsLocked(uid);
3983 u.getProcessStatsLocked(name).incNumAnrsLocked();
3984 }
3985 }
3986
Dianne Hackborna8d10942015-11-19 17:55:19 -08003987 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07003988 int parentUid = mapUid(uid);
3989 if (uid != parentUid) {
3990 // Isolated UIDs process state is already rolled up into parent, so no need to track
3991 // Otherwise the parent's process state will get downgraded incorrectly
3992 return;
3993 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08003994 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003995 }
3996
3997 public void noteProcessFinishLocked(String name, int uid) {
3998 uid = mapUid(uid);
3999 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4000 return;
4001 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004002 if (!mRecordAllHistory) {
4003 return;
4004 }
Joe Onoratoabded112016-02-08 16:49:39 -08004005 final long elapsedRealtime = mClocks.elapsedRealtime();
4006 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004007 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004008 }
4009
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004010 public void noteSyncStartLocked(String name, int uid) {
4011 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004012 final long elapsedRealtime = mClocks.elapsedRealtime();
4013 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004014 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4015 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4016 return;
4017 }
4018 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4019 }
4020
4021 public void noteSyncFinishLocked(String name, int uid) {
4022 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004023 final long elapsedRealtime = mClocks.elapsedRealtime();
4024 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004025 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4026 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4027 return;
4028 }
4029 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4030 }
4031
4032 public void noteJobStartLocked(String name, int uid) {
4033 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004034 final long elapsedRealtime = mClocks.elapsedRealtime();
4035 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004036 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4037 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4038 return;
4039 }
4040 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4041 }
4042
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004043 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004044 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004045 final long elapsedRealtime = mClocks.elapsedRealtime();
4046 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004047 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004048 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4049 return;
4050 }
4051 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4052 }
4053
Narayan Kamath695cf722017-12-21 18:32:47 +00004054 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4055 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004056 }
4057
Narayan Kamath695cf722017-12-21 18:32:47 +00004058 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4059 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4060 }
4061
4062 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4063 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004064 if (!mRecordAllHistory) {
4065 return;
4066 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004067
Joe Onoratoabded112016-02-08 16:49:39 -08004068 final long elapsedRealtime = mClocks.elapsedRealtime();
4069 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004070
4071 if (workSource != null) {
4072 for (int i = 0; i < workSource.size(); ++i) {
4073 uid = mapUid(workSource.get(i));
4074 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4075 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4076 }
4077 }
4078
4079 List<WorkChain> workChains = workSource.getWorkChains();
4080 if (workChains != null) {
4081 for (int i = 0; i < workChains.size(); ++i) {
4082 uid = mapUid(workChains.get(i).getAttributionUid());
4083 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4084 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4085 }
4086 }
4087 }
4088 } else {
4089 uid = mapUid(uid);
4090
4091 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4092 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4093 }
4094 }
4095 }
4096
4097 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4098 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004099 if (workSource != null) {
4100 for (int i = 0; i < workSource.size(); ++i) {
4101 uid = workSource.get(i);
4102 final String workSourceName = workSource.getName(i);
4103
Tej Singh6f724c42018-01-03 20:02:03 -08004104 if (isOnBattery()) {
4105 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4106 workSourceName != null ? workSourceName : packageName);
4107 pkg.noteWakeupAlarmLocked(tag);
4108 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004109 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4110 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004111 }
4112
4113 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4114 if (workChains != null) {
4115 for (int i = 0; i < workChains.size(); ++i) {
4116 final WorkChain wc = workChains.get(i);
4117 uid = wc.getAttributionUid();
4118
Tej Singh6f724c42018-01-03 20:02:03 -08004119 if (isOnBattery()) {
4120 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4121 pkg.noteWakeupAlarmLocked(tag);
4122 }
Yangster-macafad8c62018-01-05 22:30:49 -08004123 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004124 }
4125 }
4126 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004127 if (isOnBattery()) {
4128 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4129 pkg.noteWakeupAlarmLocked(tag);
4130 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004131 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004132 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004133 }
4134
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004135 private void requestWakelockCpuUpdate() {
4136 if (!mHandler.hasMessages(MSG_UPDATE_WAKELOCKS)) {
4137 Message m = mHandler.obtainMessage(MSG_UPDATE_WAKELOCKS);
4138 mHandler.sendMessageDelayed(m, DELAY_UPDATE_WAKELOCKS);
4139 }
4140 }
4141
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004142 private void requestImmediateCpuUpdate() {
4143 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
4144 mHandler.sendEmptyMessage(MSG_UPDATE_WAKELOCKS);
4145 }
4146
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004147 public void setRecordAllHistoryLocked(boolean enabled) {
4148 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004149 if (!enabled) {
4150 // Clear out any existing state.
4151 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004152 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004153 // Record the currently running processes as stopping, now that we are no
4154 // longer tracking them.
4155 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4156 HistoryItem.EVENT_PROC);
4157 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004158 long mSecRealtime = mClocks.elapsedRealtime();
4159 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004160 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4161 SparseIntArray uids = ent.getValue();
4162 for (int j=0; j<uids.size(); j++) {
4163 addHistoryEventLocked(mSecRealtime, mSecUptime,
4164 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4165 }
4166 }
4167 }
4168 } else {
4169 // Record the currently running processes as starting, now that we are tracking them.
4170 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4171 HistoryItem.EVENT_PROC);
4172 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004173 long mSecRealtime = mClocks.elapsedRealtime();
4174 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004175 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4176 SparseIntArray uids = ent.getValue();
4177 for (int j=0; j<uids.size(); j++) {
4178 addHistoryEventLocked(mSecRealtime, mSecUptime,
4179 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4180 }
4181 }
4182 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004183 }
4184 }
4185
Dianne Hackborn9a755432014-05-15 17:05:22 -07004186 public void setNoAutoReset(boolean enabled) {
4187 mNoAutoReset = enabled;
4188 }
4189
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004190 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004191 if (mPretendScreenOff != pretendScreenOff) {
4192 mPretendScreenOff = pretendScreenOff;
4193 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4194 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004195 }
4196
Dianne Hackborn9a755432014-05-15 17:05:22 -07004197 private String mInitialAcquireWakeName;
4198 private int mInitialAcquireWakeUid = -1;
4199
Narayan Kamath81822022017-12-08 11:56:01 +00004200 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4201 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004202 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004203 if (type == WAKE_TYPE_PARTIAL) {
4204 // Only care about partial wake locks, since full wake locks
4205 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004206 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004207 if (historyName == null) {
4208 historyName = name;
4209 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004210 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004211 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4212 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004213 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004214 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004215 }
4216 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004217 if (mWakeLockNesting == 0) {
4218 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4219 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4220 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004221 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004222 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004223 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004224 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004225 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004226 } else if (!mWakeLockImportant && !unimportantForLogging
4227 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004228 if (mHistoryLastWritten.wakelockTag != null) {
4229 // We'll try to update the last tag.
4230 mHistoryLastWritten.wakelockTag = null;
4231 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004232 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004233 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004234 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004235 }
4236 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004237 }
4238 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004239 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004240 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004241 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4242 // We only update the cpu time when a wake lock is acquired if the screen is off.
4243 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4244 if (DEBUG_ENERGY_CPU) {
4245 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4246 }
4247 requestWakelockCpuUpdate();
4248 }
Narayan Kamath81822022017-12-08 11:56:01 +00004249
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004250 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004251
Yangster-mac20877162017-12-22 17:19:39 -08004252 if (wc != null) {
4253 StatsLog.write(
4254 StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(), type, name, 1);
Yangster-macafad8c62018-01-05 22:30:49 -08004255 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004256 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null, type, name,
4257 1);
Narayan Kamath81822022017-12-08 11:56:01 +00004258 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004259 }
4260 }
4261
Narayan Kamath81822022017-12-08 11:56:01 +00004262 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4263 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004264 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004265 if (type == WAKE_TYPE_PARTIAL) {
4266 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004267 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004268 if (historyName == null) {
4269 historyName = name;
4270 }
4271 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4272 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004273 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004274 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004275 }
4276 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004277 if (mWakeLockNesting == 0) {
4278 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4279 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4280 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004281 mInitialAcquireWakeName = null;
4282 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004283 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004284 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004285 }
4286 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004287 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4288 if (DEBUG_ENERGY_CPU) {
4289 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4290 }
4291 requestWakelockCpuUpdate();
4292 }
Narayan Kamath81822022017-12-08 11:56:01 +00004293
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004294 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004295 if (wc != null) {
4296 StatsLog.write(
4297 StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(), type, name, 0);
Yangster-macafad8c62018-01-05 22:30:49 -08004298 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004299 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null, type, name,
4300 0);
Narayan Kamath81822022017-12-08 11:56:01 +00004301 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004302 }
4303 }
4304
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004305 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4306 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004307 final long elapsedRealtime = mClocks.elapsedRealtime();
4308 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004309 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004310 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004311 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4312 unimportantForLogging, elapsedRealtime, uptime);
4313 }
4314
4315 List<WorkChain> wcs = ws.getWorkChains();
4316 if (wcs != null) {
4317 for (int i = 0; i < wcs.size(); ++i) {
4318 final WorkChain wc = wcs.get(i);
4319 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4320 unimportantForLogging, elapsedRealtime, uptime);
4321 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004322 }
4323 }
4324
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004325 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4326 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004327 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004328 final long elapsedRealtime = mClocks.elapsedRealtime();
4329 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004330
4331 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4332
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004333 // For correct semantics, we start the need worksources first, so that we won't
4334 // make inappropriate history items as if all wake locks went away and new ones
4335 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004336 //
4337 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004338 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004339 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004340 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004341 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004342 }
Narayan Kamath81822022017-12-08 11:56:01 +00004343 if (wcs != null) {
4344 List<WorkChain> newChains = wcs[0];
4345 if (newChains != null) {
4346 for (int i = 0; i < newChains.size(); ++i) {
4347 final WorkChain newChain = newChains.get(i);
4348 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4349 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4350 uptime);
4351 }
4352 }
4353 }
4354
4355 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004356 final int NO = ws.size();
4357 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004358 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4359 uptime);
4360 }
4361 if (wcs != null) {
4362 List<WorkChain> goneChains = wcs[1];
4363 if (goneChains != null) {
4364 for (int i = 0; i < goneChains.size(); ++i) {
4365 final WorkChain goneChain = goneChains.get(i);
4366 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4367 historyName, type, elapsedRealtime, uptime);
4368 }
4369 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004370 }
4371 }
4372
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004373 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4374 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004375 final long elapsedRealtime = mClocks.elapsedRealtime();
4376 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004377 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004378 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004379 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4380 uptime);
4381 }
4382
4383 List<WorkChain> wcs = ws.getWorkChains();
4384 if (wcs != null) {
4385 for (int i = 0; i < wcs.size(); ++i) {
4386 final WorkChain wc = wcs.get(i);
4387 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4388 elapsedRealtime, uptime);
4389 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004390 }
4391 }
4392
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004393 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004394 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4395 uid, null, name, historyName, 1);
Yangster-macafad8c62018-01-05 22:30:49 -08004396
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004397 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004398 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004399 }
4400
4401 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4402 WorkSource workSource) {
4403 final int N = workSource.size();
4404 for (int i = 0; i < N; ++i) {
4405 final int uid = mapUid(workSource.get(i));
4406 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004407 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4408 workSource.get(i), workSource.getName(i), name, historyName, 1);
Narayan Kamath96a92562018-01-02 18:57:17 +00004409 }
4410
4411 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4412 if (workChains != null) {
4413 for (int i = 0; i < workChains.size(); ++i) {
4414 final WorkChain workChain = workChains.get(i);
4415 final int uid = workChain.getAttributionUid();
4416 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4417
Yangster-macafad8c62018-01-05 22:30:49 -08004418 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4419 workChain.getUids(), workChain.getTags(), name, historyName, 1);
Narayan Kamath96a92562018-01-02 18:57:17 +00004420 }
4421 }
4422 }
4423
4424 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004425 final long elapsedRealtime = mClocks.elapsedRealtime();
4426 final long uptime = mClocks.uptimeMillis();
4427 if (historyName == null) {
4428 historyName = name;
4429 }
4430 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4431 0)) {
4432 return;
4433 }
4434 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4435 historyName, uid);
4436 }
4437
4438 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004439 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4440 uid, null, name, historyName, 0);
Yangster-macafad8c62018-01-05 22:30:49 -08004441
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004442 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004443 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004444 }
4445
4446 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4447 WorkSource workSource) {
4448 final int N = workSource.size();
4449 for (int i = 0; i < N; ++i) {
4450 final int uid = mapUid(workSource.get(i));
4451 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004452 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4453 workSource.get(i), workSource.getName(i), name, historyName, 0);
Narayan Kamath96a92562018-01-02 18:57:17 +00004454 }
4455
4456 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4457 if (workChains != null) {
4458 for (int i = 0; i < workChains.size(); ++i) {
4459 final WorkChain workChain = workChains.get(i);
4460 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004461 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004462 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4463 workChain.getUids(), workChain.getTags(), name, historyName, 0);
Narayan Kamath96a92562018-01-02 18:57:17 +00004464 }
4465 }
4466 }
4467
4468 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004469 final long elapsedRealtime = mClocks.elapsedRealtime();
4470 final long uptime = mClocks.uptimeMillis();
4471 if (historyName == null) {
4472 historyName = name;
4473 }
4474 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4475 0)) {
4476 return;
4477 }
4478 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4479 historyName, uid);
4480 }
4481
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004482 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4483 if (mLastWakeupReason != null) {
4484 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004485 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004486 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz8c6571b2017-10-24 15:04:41 -07004487 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason, deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004488 mLastWakeupReason = null;
4489 }
4490 }
4491
4492 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004493 final long elapsedRealtime = mClocks.elapsedRealtime();
4494 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004495 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004496 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004497 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004498 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4499 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004500 mHistoryCur.wakeReasonTag.uid = 0;
4501 mLastWakeupReason = reason;
4502 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004503 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004504 }
4505
Adam Lesinski72478f02015-06-17 15:39:43 -07004506 public boolean startAddingCpuLocked() {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004507 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
Adam Lesinski72478f02015-06-17 15:39:43 -07004508 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004509 }
4510
Adam Lesinski72478f02015-06-17 15:39:43 -07004511 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4512 int statSystemTime, int statIOWaitTime, int statIrqTime,
4513 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004514 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4515 + " user=" + statUserTime + " sys=" + statSystemTime
4516 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4517 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4518 mCurStepCpuUserTime += totalUTime;
4519 mCurStepCpuSystemTime += totalSTime;
4520 mCurStepStatUserTime += statUserTime;
4521 mCurStepStatSystemTime += statSystemTime;
4522 mCurStepStatIOWaitTime += statIOWaitTime;
4523 mCurStepStatIrqTime += statIrqTime;
4524 mCurStepStatSoftIrqTime += statSoftIrqTime;
4525 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004526 }
4527
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004528 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004529 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004530 Uid u = mUidStats.get(uid);
4531 if (u != null) {
4532 u.mPids.remove(pid);
4533 }
4534 }
4535
4536 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004537 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004538 Uid u = mUidStats.get(uid);
4539 if (u != null) {
4540 Uid.Pid p = u.mPids.get(pid);
4541 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004542 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004543 }
4544 }
4545 return 0;
4546 }
4547
Dianne Hackborn287952c2010-09-22 22:34:31 -07004548 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004549 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004550 Uid u = mUidStats.get(uid);
4551 if (u != null) {
4552 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4553 }
4554 }
4555
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004556 int mSensorNesting;
4557
4558 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004559 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004560 final long elapsedRealtime = mClocks.elapsedRealtime();
4561 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004562 if (mSensorNesting == 0) {
4563 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4564 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4565 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004566 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004567 }
4568 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004569 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004570 }
4571
4572 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004573 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004574 final long elapsedRealtime = mClocks.elapsedRealtime();
4575 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004576 mSensorNesting--;
4577 if (mSensorNesting == 0) {
4578 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4579 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4580 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004581 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004582 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004583 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004584 }
4585
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004586 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004587
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004588 public void noteStartGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004589 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004590 final long elapsedRealtime = mClocks.elapsedRealtime();
4591 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004592 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004593 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004594 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4595 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004596 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004597 }
4598 mGpsNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004599 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004600 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004601
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004602 public void noteStopGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004603 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004604 final long elapsedRealtime = mClocks.elapsedRealtime();
4605 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004606 mGpsNesting--;
4607 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004608 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004609 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4610 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004611 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004612 stopAllGpsSignalQualityTimersLocked(-1);
4613 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004614 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004615 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004617
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004618 public void noteGpsSignalQualityLocked(int signalLevel) {
4619 if (mGpsNesting == 0) {
4620 return;
4621 }
4622 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4623 stopAllGpsSignalQualityTimersLocked(-1);
4624 return;
4625 }
4626 final long elapsedRealtime = mClocks.elapsedRealtime();
4627 final long uptime = mClocks.uptimeMillis();
4628 if (mGpsSignalQualityBin != signalLevel) {
4629 if (mGpsSignalQualityBin >= 0) {
4630 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4631 }
4632 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4633 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4634 }
4635 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4636 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4637 addHistoryRecordLocked(elapsedRealtime, uptime);
4638 mGpsSignalQualityBin = signalLevel;
4639 }
4640 return;
4641 }
4642
Jeff Browne95c3cd2014-05-02 16:59:26 -07004643 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004644 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004645
4646 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4647 // original 4 are mapped to one of the originals.
4648 if (state > MAX_TRACKED_SCREEN_STATE) {
4649 switch (state) {
4650 case Display.STATE_VR:
4651 state = Display.STATE_ON;
4652 break;
4653 default:
4654 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4655 break;
4656 }
4657 }
4658
Jeff Browne95c3cd2014-05-02 16:59:26 -07004659 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004660 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004661 final int oldState = mScreenState;
4662 mScreenState = state;
4663 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4664 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004665
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004666 if (state != Display.STATE_UNKNOWN) {
4667 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004668 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4669 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4670 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004671 } else {
4672 Slog.wtf(TAG, "Unexpected screen state: " + state);
4673 }
4674 }
4675
Mike Mac2f518a2017-09-19 16:06:03 -07004676 final long elapsedRealtime = mClocks.elapsedRealtime();
4677 final long uptime = mClocks.uptimeMillis();
4678
4679 boolean updateHistory = false;
4680 if (isScreenDoze(state)) {
4681 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4682 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4683 updateHistory = true;
4684 } else if (isScreenDoze(oldState)) {
4685 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4686 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4687 updateHistory = true;
4688 }
4689 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004690 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4691 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4692 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004693 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4694 if (mScreenBrightnessBin >= 0) {
4695 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4696 }
Mike Mac2f518a2017-09-19 16:06:03 -07004697 updateHistory = true;
4698 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004699 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4700 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4701 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004702 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4703 if (mScreenBrightnessBin >= 0) {
4704 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4705 }
Mike Mac2f518a2017-09-19 16:06:03 -07004706 updateHistory = true;
4707 }
4708 if (updateHistory) {
4709 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4710 + Display.stateToString(state));
4711 addHistoryRecordLocked(elapsedRealtime, uptime);
4712 }
4713 if (isScreenOn(state)) {
4714 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4715 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4716 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004717 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004718 elapsedRealtime, uptime);
4719 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004720 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004721 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004722 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004723 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004724 }
4725 // Update discharge amounts.
4726 if (mOnBatteryInternal) {
4727 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004728 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004729 }
4730 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004731
Dianne Hackborn617f8772009-03-31 15:04:46 -07004732 public void noteScreenBrightnessLocked(int brightness) {
4733 // Bin the brightness.
4734 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4735 if (bin < 0) bin = 0;
4736 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4737 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004738 final long elapsedRealtime = mClocks.elapsedRealtime();
4739 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004740 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4741 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004742 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4743 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004744 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004745 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004746 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004747 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004748 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004749 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004750 }
4751 mScreenBrightnessBin = bin;
4752 }
4753 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004754
Dianne Hackborn617f8772009-03-31 15:04:46 -07004755 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004756 if (mOnBatteryInternal) {
4757 uid = mapUid(uid);
4758 getUidStatsLocked(uid).noteUserActivityLocked(event);
4759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004761
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004762 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004763 final long elapsedRealtime = mClocks.elapsedRealtime();
4764 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004765 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4766 reason, reasonUid);
4767 }
4768
Jeff Browne95c3cd2014-05-02 16:59:26 -07004769 public void noteInteractiveLocked(boolean interactive) {
4770 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08004771 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004772 mInteractive = interactive;
4773 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
4774 if (interactive) {
4775 mInteractiveTimer.startRunningLocked(elapsedRealtime);
4776 } else {
4777 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
4778 }
4779 }
4780 }
4781
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004782 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004783 final long elapsedRealtime = mClocks.elapsedRealtime();
4784 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004785 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4786 extra, type);
4787 mNumConnectivityChange++;
4788 }
4789
Adam Lesinski5f056f62016-07-14 16:56:08 -07004790 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4791 final long uptimeMillis, int uid) {
4792 uid = mapUid(uid);
4793 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4794 uid);
4795 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4796 }
4797
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004798 /**
4799 * Updates the radio power state and returns true if an external stats collection should occur.
4800 */
4801 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004802 final long elapsedRealtime = mClocks.elapsedRealtime();
4803 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004804 if (mMobileRadioPowerState != powerState) {
4805 long realElapsedRealtimeMs;
4806 final boolean active =
4807 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4808 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4809 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004810 if (uid > 0) {
4811 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4812 }
4813
Adam Lesinski9acfd812016-04-19 18:29:50 -07004814 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004815 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4816 } else {
4817 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004818 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004819 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4820 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4821 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004822 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004823 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4824 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4825 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004826 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004827 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4828 }
4829 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4830 + Integer.toHexString(mHistoryCur.states));
4831 addHistoryRecordLocked(elapsedRealtime, uptime);
4832 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08004833 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004834 if (active) {
4835 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4836 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4837 } else {
4838 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004839 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004840 // Tell the caller to collect radio network/power stats.
4841 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004842 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004843 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004844 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004845 }
4846
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004847 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004848 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004849 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4850 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4851 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004852 final long elapsedRealtime = mClocks.elapsedRealtime();
4853 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004854 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004855 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004856 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4857 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004858 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004859 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004860 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004861 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4862 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004863 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004864 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004865 }
4866 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatzc1a050a2017-10-10 15:49:28 -07004867 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ? 1 : 0);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004868 }
4869 }
4870
Bookatzddccf0a2017-11-28 16:48:14 -08004871 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004872 final long elapsedRealtime = mClocks.elapsedRealtime();
4873 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004874 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004875 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004876 // We don't go out of general idling mode until explicitly taken out of
4877 // device idle through going active or significant motion.
4878 nowIdling = true;
4879 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004880 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
4881 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
4882 // We don't go out of general light idling mode until explicitly taken out of
4883 // device idle through going active or significant motion.
4884 nowLightIdling = true;
4885 }
4886 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
4887 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
4888 activeReason, activeUid);
4889 }
Bookatzddccf0a2017-11-28 16:48:14 -08004890 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
4891 int statsmode;
4892 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
4893 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
4894 else statsmode = DEVICE_IDLE_MODE_OFF;
4895 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
4896 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004897 if (mDeviceIdling != nowIdling) {
4898 mDeviceIdling = nowIdling;
4899 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
4900 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
4901 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004902 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004903 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
4904 } else {
4905 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
4906 }
4907 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004908 if (mDeviceLightIdling != nowLightIdling) {
4909 mDeviceLightIdling = nowLightIdling;
4910 if (nowLightIdling) {
4911 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004912 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004913 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004914 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004915 }
4916 if (mDeviceIdleMode != mode) {
4917 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
4918 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
4919 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
4920 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004921 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004922 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
4923 mLastIdleTimeStart = elapsedRealtime;
4924 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
4925 if (lastDuration > mLongestLightIdleTime) {
4926 mLongestLightIdleTime = lastDuration;
4927 }
4928 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004929 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004930 if (lastDuration > mLongestFullIdleTime) {
4931 mLongestFullIdleTime = lastDuration;
4932 }
4933 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
4934 }
4935 if (mode == DEVICE_IDLE_MODE_LIGHT) {
4936 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004937 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004938 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
4939 }
4940 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08004941 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004942 }
4943 }
4944
Dianne Hackborn3accca02013-09-20 09:32:11 -07004945 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08004946 final long elapsedRealtime = mClocks.elapsedRealtime();
4947 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07004948 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004949 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07004950 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004951 PackageChange pc = new PackageChange();
4952 pc.mPackageName = pkgName;
4953 pc.mUpdate = true;
4954 pc.mVersionCode = versionCode;
4955 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004956 }
4957
4958 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08004959 final long elapsedRealtime = mClocks.elapsedRealtime();
4960 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004961 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
4962 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004963 PackageChange pc = new PackageChange();
4964 pc.mPackageName = pkgName;
4965 pc.mUpdate = true;
4966 addPackageChange(pc);
4967 }
4968
4969 private void addPackageChange(PackageChange pc) {
4970 if (mDailyPackageChanges == null) {
4971 mDailyPackageChanges = new ArrayList<>();
4972 }
4973 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004974 }
4975
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004976 void stopAllGpsSignalQualityTimersLocked(int except) {
4977 final long elapsedRealtime = mClocks.elapsedRealtime();
4978 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
4979 if (i == except) {
4980 continue;
4981 }
4982 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
4983 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
4984 }
4985 }
4986 }
4987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004988 public void notePhoneOnLocked() {
4989 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004990 final long elapsedRealtime = mClocks.elapsedRealtime();
4991 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004992 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004993 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
4994 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004995 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004996 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004997 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998 }
4999 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 public void notePhoneOffLocked() {
5002 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005003 final long elapsedRealtime = mClocks.elapsedRealtime();
5004 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005005 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005006 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5007 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005008 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005009 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005010 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005011 }
5012 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005013
Dianne Hackborn3251b902014-06-20 14:40:53 -07005014 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005015 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005016 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005017 if (i == except) {
5018 continue;
5019 }
5020 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005021 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005022 }
5023 }
5024 }
5025
Dianne Hackborne4a59512010-12-07 11:08:07 -08005026 private int fixPhoneServiceState(int state, int signalBin) {
5027 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5028 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5029 // to infer that we are scanning from other data.
5030 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005031 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005032 state = ServiceState.STATE_IN_SERVICE;
5033 }
5034 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005035
Dianne Hackborne4a59512010-12-07 11:08:07 -08005036 return state;
5037 }
5038
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005039 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005040 boolean scanning = false;
5041 boolean newHistory = false;
5042
5043 mPhoneServiceStateRaw = state;
5044 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005045 mPhoneSignalStrengthBinRaw = strengthBin;
5046
Joe Onoratoabded112016-02-08 16:49:39 -08005047 final long elapsedRealtime = mClocks.elapsedRealtime();
5048 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005049
5050 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5051 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5052 // to infer that we are scanning from other data.
5053 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005054 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005055 state = ServiceState.STATE_IN_SERVICE;
5056 }
5057 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005058
5059 // If the phone is powered off, stop all timers.
5060 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005061 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005062
Dianne Hackborne4a59512010-12-07 11:08:07 -08005063 // If we are in service, make sure the correct signal string timer is running.
5064 } else if (state == ServiceState.STATE_IN_SERVICE) {
5065 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005066
5067 // If we're out of service, we are in the lowest signal strength
5068 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005069 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005070 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005071 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005072 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005073 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005074 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005075 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5076 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005077 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005078 }
5079 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005080
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005081 if (!scanning) {
5082 // If we are no longer scanning, then stop the scanning timer.
5083 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5084 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5085 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5086 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005087 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005088 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005089 }
5090 }
5091
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005092 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005093 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5094 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005095 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005096 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005097 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005098 mPhoneServiceState = state;
5099 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005100
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005101 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005102 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005103 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005104 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005105 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005106 if (strengthBin >= 0) {
5107 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005108 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005109 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005110 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5111 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005112 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005113 + Integer.toHexString(mHistoryCur.states));
5114 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005115 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005116 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005117 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005118 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005119 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005120 }
5121
5122 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005123 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005124 }
5125 }
5126
5127 /**
5128 * Telephony stack updates the phone state.
5129 * @param state phone state from ServiceState.getState()
5130 */
5131 public void notePhoneStateLocked(int state, int simState) {
5132 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005133 }
5134
Wink Savillee9b06d72009-05-18 21:47:50 -07005135 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005136 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005137 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005138 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005139 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005140
Dianne Hackborn627bba72009-03-24 22:32:56 -07005141 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
5142 int bin = DATA_CONNECTION_NONE;
5143 if (hasData) {
5144 switch (dataType) {
5145 case TelephonyManager.NETWORK_TYPE_EDGE:
5146 bin = DATA_CONNECTION_EDGE;
5147 break;
5148 case TelephonyManager.NETWORK_TYPE_GPRS:
5149 bin = DATA_CONNECTION_GPRS;
5150 break;
5151 case TelephonyManager.NETWORK_TYPE_UMTS:
5152 bin = DATA_CONNECTION_UMTS;
5153 break;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005154 case TelephonyManager.NETWORK_TYPE_CDMA:
5155 bin = DATA_CONNECTION_CDMA;
5156 break;
5157 case TelephonyManager.NETWORK_TYPE_EVDO_0:
5158 bin = DATA_CONNECTION_EVDO_0;
5159 break;
5160 case TelephonyManager.NETWORK_TYPE_EVDO_A:
5161 bin = DATA_CONNECTION_EVDO_A;
5162 break;
5163 case TelephonyManager.NETWORK_TYPE_1xRTT:
5164 bin = DATA_CONNECTION_1xRTT;
5165 break;
5166 case TelephonyManager.NETWORK_TYPE_HSDPA:
5167 bin = DATA_CONNECTION_HSDPA;
5168 break;
5169 case TelephonyManager.NETWORK_TYPE_HSUPA:
5170 bin = DATA_CONNECTION_HSUPA;
5171 break;
5172 case TelephonyManager.NETWORK_TYPE_HSPA:
5173 bin = DATA_CONNECTION_HSPA;
5174 break;
5175 case TelephonyManager.NETWORK_TYPE_IDEN:
5176 bin = DATA_CONNECTION_IDEN;
5177 break;
5178 case TelephonyManager.NETWORK_TYPE_EVDO_B:
5179 bin = DATA_CONNECTION_EVDO_B;
5180 break;
Robert Greenwalt962a9902010-11-02 11:10:25 -07005181 case TelephonyManager.NETWORK_TYPE_LTE:
5182 bin = DATA_CONNECTION_LTE;
5183 break;
5184 case TelephonyManager.NETWORK_TYPE_EHRPD:
5185 bin = DATA_CONNECTION_EHRPD;
5186 break;
Patrick Tjinb71703c2013-11-06 09:27:03 -08005187 case TelephonyManager.NETWORK_TYPE_HSPAP:
5188 bin = DATA_CONNECTION_HSPAP;
5189 break;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005190 default:
5191 bin = DATA_CONNECTION_OTHER;
5192 break;
5193 }
5194 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005195 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005196 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005197 final long elapsedRealtime = mClocks.elapsedRealtime();
5198 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005199 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5200 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005201 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5202 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005203 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005204 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005205 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005206 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005207 }
5208 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005209 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005210 }
5211 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005212
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005213 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005214 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005215 final long elapsedRealtime = mClocks.elapsedRealtime();
5216 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005217 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005218 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5219 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005220 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005221 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005222 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005223 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005224 }
5225 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005226
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005227 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005228 final long elapsedRealtime = mClocks.elapsedRealtime();
5229 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005230 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005231 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005232 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5233 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005234 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005235 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005236 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005237 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005238 }
5239 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005240
5241 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005242 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005243 final long elapsedRealtime = mClocks.elapsedRealtime();
5244 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005245 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005246 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005247 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5248 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005249 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005250 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005251 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005252 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005253 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005254 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005255
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005256 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005257 if (mAudioOnNesting == 0) {
5258 return;
5259 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005260 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005261 final long elapsedRealtime = mClocks.elapsedRealtime();
5262 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005263 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005264 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005265 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5266 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005267 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005268 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005269 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005270 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005271 }
5272
5273 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005274 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005275 final long elapsedRealtime = mClocks.elapsedRealtime();
5276 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005277 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005278 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005279 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5280 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005281 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005282 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005283 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005284 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005285 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005286 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005287
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005288 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005289 if (mVideoOnNesting == 0) {
5290 return;
5291 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005292 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005293 final long elapsedRealtime = mClocks.elapsedRealtime();
5294 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005295 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005296 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005297 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5298 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005299 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005300 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005301 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005302 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005303 }
5304
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005305 public void noteResetAudioLocked() {
5306 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005307 final long elapsedRealtime = mClocks.elapsedRealtime();
5308 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005309 mAudioOnNesting = 0;
5310 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5311 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5312 + Integer.toHexString(mHistoryCur.states));
5313 addHistoryRecordLocked(elapsedRealtime, uptime);
5314 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5315 for (int i=0; i<mUidStats.size(); i++) {
5316 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5317 uid.noteResetAudioLocked(elapsedRealtime);
5318 }
5319 }
5320 }
5321
5322 public void noteResetVideoLocked() {
5323 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005324 final long elapsedRealtime = mClocks.elapsedRealtime();
5325 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005326 mAudioOnNesting = 0;
5327 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5328 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5329 + Integer.toHexString(mHistoryCur.states));
5330 addHistoryRecordLocked(elapsedRealtime, uptime);
5331 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5332 for (int i=0; i<mUidStats.size(); i++) {
5333 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5334 uid.noteResetVideoLocked(elapsedRealtime);
5335 }
5336 }
5337 }
5338
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005339 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005340 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005341 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005342 }
5343
5344 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005345 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005346 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005347 }
5348
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005349 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005350 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005351 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5352 }
5353
5354 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005355 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005356 getUidStatsLocked(uid).noteVibratorOffLocked();
5357 }
5358
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005359 public void noteFlashlightOnLocked(int uid) {
5360 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005361 final long elapsedRealtime = mClocks.elapsedRealtime();
5362 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005363 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005364 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5365 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005366 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005367 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005368 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5369 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005370 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5371 }
5372
5373 public void noteFlashlightOffLocked(int uid) {
5374 if (mFlashlightOnNesting == 0) {
5375 return;
5376 }
5377 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005378 final long elapsedRealtime = mClocks.elapsedRealtime();
5379 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005380 if (--mFlashlightOnNesting == 0) {
5381 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5382 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5383 + Integer.toHexString(mHistoryCur.states2));
5384 addHistoryRecordLocked(elapsedRealtime, uptime);
5385 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5386 }
5387 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5388 }
5389
5390 public void noteCameraOnLocked(int uid) {
5391 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005392 final long elapsedRealtime = mClocks.elapsedRealtime();
5393 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005394 if (mCameraOnNesting++ == 0) {
5395 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5396 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5397 + Integer.toHexString(mHistoryCur.states2));
5398 addHistoryRecordLocked(elapsedRealtime, uptime);
5399 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5400 }
5401 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5402 }
5403
5404 public void noteCameraOffLocked(int uid) {
5405 if (mCameraOnNesting == 0) {
5406 return;
5407 }
5408 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005409 final long elapsedRealtime = mClocks.elapsedRealtime();
5410 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005411 if (--mCameraOnNesting == 0) {
5412 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5413 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5414 + Integer.toHexString(mHistoryCur.states2));
5415 addHistoryRecordLocked(elapsedRealtime, uptime);
5416 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5417 }
5418 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5419 }
5420
5421 public void noteResetCameraLocked() {
5422 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005423 final long elapsedRealtime = mClocks.elapsedRealtime();
5424 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005425 mCameraOnNesting = 0;
5426 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5427 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5428 + Integer.toHexString(mHistoryCur.states2));
5429 addHistoryRecordLocked(elapsedRealtime, uptime);
5430 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5431 for (int i=0; i<mUidStats.size(); i++) {
5432 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5433 uid.noteResetCameraLocked(elapsedRealtime);
5434 }
5435 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005436 }
5437
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005438 public void noteResetFlashlightLocked() {
5439 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005440 final long elapsedRealtime = mClocks.elapsedRealtime();
5441 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005442 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005443 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5444 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005445 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005446 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005447 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5448 for (int i=0; i<mUidStats.size(); i++) {
5449 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5450 uid.noteResetFlashlightLocked(elapsedRealtime);
5451 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005452 }
5453 }
5454
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005455 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5456 boolean isUnoptimized) {
5457 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005458 final long elapsedRealtime = mClocks.elapsedRealtime();
5459 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005460 if (mBluetoothScanNesting == 0) {
5461 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5462 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5463 + Integer.toHexString(mHistoryCur.states2));
5464 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005465 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005466 }
5467 mBluetoothScanNesting++;
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005468
Yangster-macafad8c62018-01-05 22:30:49 -08005469 if (workChain != null) {
5470 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
5471 workChain.getUids(), workChain.getTags(), 1);
5472 if (isUnoptimized) {
5473 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
5474 workChain.getUids(), workChain.getTags(), 1);
5475 }
5476 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005477 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null, 1);
Yangster-macafad8c62018-01-05 22:30:49 -08005478 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005479 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
5480 1);
Yangster-macafad8c62018-01-05 22:30:49 -08005481 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005482 }
5483
Bookatzb1f04f32017-05-19 13:57:32 -07005484 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005485 if (workChain != null) {
5486 getUidStatsLocked(uid).addBluetoothWorkChain(workChain, isUnoptimized);
5487 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005488 }
5489
Bookatzb1f04f32017-05-19 13:57:32 -07005490 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005491 final int N = ws.size();
5492 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005493 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5494 }
5495
5496 final List<WorkChain> workChains = ws.getWorkChains();
5497 if (workChains != null) {
5498 for (int i = 0; i < workChains.size(); ++i) {
5499 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5500 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005501 }
5502 }
5503
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005504 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5505 boolean isUnoptimized) {
5506 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005507 final long elapsedRealtime = mClocks.elapsedRealtime();
5508 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005509 mBluetoothScanNesting--;
5510 if (mBluetoothScanNesting == 0) {
5511 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5512 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5513 + Integer.toHexString(mHistoryCur.states2));
5514 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005515 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005516 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005517
Yangster-macafad8c62018-01-05 22:30:49 -08005518 if (workChain != null) {
5519 StatsLog.write(
5520 StatsLog.BLE_SCAN_STATE_CHANGED, workChain.getUids(), workChain.getTags(), 0);
5521 if (isUnoptimized) {
5522 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
5523 workChain.getUids(), workChain.getTags(), 0);
5524 }
5525 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005526 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null, 0);
Yangster-macafad8c62018-01-05 22:30:49 -08005527 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005528 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
5529 0);
Yangster-macafad8c62018-01-05 22:30:49 -08005530 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005531 }
5532
Bookatz94c5a312017-07-11 16:49:17 -07005533 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005534 if (workChain != null) {
5535 getUidStatsLocked(uid).removeBluetoothWorkChain(workChain, isUnoptimized);
5536 }
5537 }
5538
5539 private int getAttributionUid(int uid, WorkChain workChain) {
5540 if (workChain != null) {
5541 return mapUid(workChain.getAttributionUid());
5542 }
5543
5544 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005545 }
5546
Bookatz94c5a312017-07-11 16:49:17 -07005547 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005548 final int N = ws.size();
5549 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005550 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5551 }
5552
5553 final List<WorkChain> workChains = ws.getWorkChains();
5554 if (workChains != null) {
5555 for (int i = 0; i < workChains.size(); ++i) {
5556 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5557 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005558 }
5559 }
5560
5561 public void noteResetBluetoothScanLocked() {
5562 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005563 final long elapsedRealtime = mClocks.elapsedRealtime();
5564 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005565 mBluetoothScanNesting = 0;
5566 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5567 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5568 + Integer.toHexString(mHistoryCur.states2));
5569 addHistoryRecordLocked(elapsedRealtime, uptime);
5570 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005571
5572
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005573 for (int i=0; i<mUidStats.size(); i++) {
5574 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5575 uid.noteResetBluetoothScanLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005576
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005577 List<WorkChain> allWorkChains = uid.getAllBluetoothWorkChains();
5578 if (allWorkChains != null) {
5579 for (int j = 0; j < allWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005580 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005581 allWorkChains.get(j).getUids(),
5582 allWorkChains.get(j).getTags(), 0);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005583 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005584 allWorkChains.clear();
5585 }
5586
5587 List<WorkChain> unoptimizedWorkChains = uid.getUnoptimizedBluetoothWorkChains();
5588 if (unoptimizedWorkChains != null) {
5589 for (int j = 0; j < unoptimizedWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005590 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005591 unoptimizedWorkChains.get(j).getUids(),
5592 unoptimizedWorkChains.get(j).getTags(), 0);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005593 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005594 unoptimizedWorkChains.clear();
5595 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005596 }
5597 }
5598 }
5599
Bookatz4ebc0642017-05-11 12:21:19 -07005600 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005601 final int N = ws.size();
5602 for (int i = 0; i < N; i++) {
5603 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005604 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005605 StatsLog.write_non_chained(StatsLog.BLE_SCAN_RESULT_RECEIVED, ws.get(i), ws.getName(i),
5606 numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005607 }
5608
5609 final List<WorkChain> workChains = ws.getWorkChains();
5610 if (workChains != null) {
5611 for (int i = 0; i < workChains.size(); ++i) {
5612 final WorkChain wc = workChains.get(i);
5613 int uid = mapUid(wc.getAttributionUid());
5614 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-macafad8c62018-01-05 22:30:49 -08005615 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED,
5616 wc.getUids(), wc.getTags(), numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005617 }
Bookatz956f36bf2017-04-28 09:48:17 -07005618 }
5619 }
5620
Adam Lesinski5f056f62016-07-14 16:56:08 -07005621 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5622 final long uptimeMillis, int uid) {
5623 uid = mapUid(uid);
5624 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5625 uid);
5626 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5627 }
5628
5629 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005630 final long elapsedRealtime = mClocks.elapsedRealtime();
5631 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005632 if (mWifiRadioPowerState != powerState) {
5633 final boolean active =
5634 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5635 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5636 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005637 if (uid > 0) {
5638 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5639 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005640 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005641 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005642 } else {
5643 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005644 mWifiActiveTimer.stopRunningLocked(
5645 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005646 }
5647 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5648 + Integer.toHexString(mHistoryCur.states));
5649 addHistoryRecordLocked(elapsedRealtime, uptime);
5650 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005651 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005652 }
5653 }
5654
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005655 public void noteWifiRunningLocked(WorkSource ws) {
5656 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005657 final long elapsedRealtime = mClocks.elapsedRealtime();
5658 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005659 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005660 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5661 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005662 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005663 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005664 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005665 int N = ws.size();
5666 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005667 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005668 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005669 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005670
5671 List<WorkChain> workChains = ws.getWorkChains();
5672 if (workChains != null) {
5673 for (int i = 0; i < workChains.size(); ++i) {
5674 int uid = mapUid(workChains.get(i).getAttributionUid());
5675 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5676 }
5677 }
5678
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005679 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005680 } else {
5681 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005682 }
5683 }
5684
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005685 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5686 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005687 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005688 int N = oldWs.size();
5689 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005690 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005691 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005692 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005693
5694 List<WorkChain> workChains = oldWs.getWorkChains();
5695 if (workChains != null) {
5696 for (int i = 0; i < workChains.size(); ++i) {
5697 int uid = mapUid(workChains.get(i).getAttributionUid());
5698 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5699 }
5700 }
5701
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005702 N = newWs.size();
5703 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005704 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005705 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005706 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005707
5708 workChains = newWs.getWorkChains();
5709 if (workChains != null) {
5710 for (int i = 0; i < workChains.size(); ++i) {
5711 int uid = mapUid(workChains.get(i).getAttributionUid());
5712 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5713 }
5714 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005715 } else {
5716 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5717 }
5718 }
5719
5720 public void noteWifiStoppedLocked(WorkSource ws) {
5721 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005722 final long elapsedRealtime = mClocks.elapsedRealtime();
5723 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005724 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005725 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5726 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005727 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005728 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005729 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005730 int N = ws.size();
5731 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005732 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005733 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005734 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005735
5736 List<WorkChain> workChains = ws.getWorkChains();
5737 if (workChains != null) {
5738 for (int i = 0; i < workChains.size(); ++i) {
5739 int uid = mapUid(workChains.get(i).getAttributionUid());
5740 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5741 }
5742 }
5743
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005744 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005745 } else {
5746 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005747 }
5748 }
5749
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005750 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5751 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5752 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005753 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005754 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005755 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005756 }
5757 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005758 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005759 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005760 }
5761 }
5762
Dianne Hackborn3251b902014-06-20 14:40:53 -07005763 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5764 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5765 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005766 final long elapsedRealtime = mClocks.elapsedRealtime();
5767 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005768 if (mWifiSupplState >= 0) {
5769 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5770 }
5771 mWifiSupplState = supplState;
5772 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5773 mHistoryCur.states2 =
5774 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5775 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5776 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5777 + Integer.toHexString(mHistoryCur.states2));
5778 addHistoryRecordLocked(elapsedRealtime, uptime);
5779 }
5780 }
5781
5782 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005783 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005784 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5785 if (i == except) {
5786 continue;
5787 }
5788 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5789 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5790 }
5791 }
5792 }
5793
5794 public void noteWifiRssiChangedLocked(int newRssi) {
5795 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5796 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5797 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005798 final long elapsedRealtime = mClocks.elapsedRealtime();
5799 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005800 if (mWifiSignalStrengthBin >= 0) {
5801 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5802 elapsedRealtime);
5803 }
5804 if (strengthBin >= 0) {
5805 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5806 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Bookatze5885242017-10-24 20:10:31 -07005807 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07005808 }
5809 mHistoryCur.states2 =
5810 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5811 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5812 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5813 + Integer.toHexString(mHistoryCur.states2));
5814 addHistoryRecordLocked(elapsedRealtime, uptime);
5815 } else {
5816 stopAllWifiSignalStrengthTimersLocked(-1);
5817 }
5818 mWifiSignalStrengthBin = strengthBin;
5819 }
5820 }
5821
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005822 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005823
The Android Open Source Project10592532009-03-18 17:39:46 -07005824 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005825 final long elapsedRealtime = mClocks.elapsedRealtime();
5826 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005827 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005828 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005829 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5830 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005831 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005832 }
5833 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005834 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005835 }
5836
5837 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005838 final long elapsedRealtime = mClocks.elapsedRealtime();
5839 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005840 mWifiFullLockNesting--;
5841 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005842 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005843 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
5844 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005845 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005846 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005847 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005848 }
5849
Nick Pelly6ccaa542012-06-15 15:22:47 -07005850 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005851
Nick Pelly6ccaa542012-06-15 15:22:47 -07005852 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005853 final long elapsedRealtime = mClocks.elapsedRealtime();
5854 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005855 if (mWifiScanNesting == 0) {
5856 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
5857 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005858 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005859 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005860 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07005861 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005862 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005863 }
5864
Nick Pelly6ccaa542012-06-15 15:22:47 -07005865 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005866 final long elapsedRealtime = mClocks.elapsedRealtime();
5867 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005868 mWifiScanNesting--;
5869 if (mWifiScanNesting == 0) {
5870 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
5871 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005872 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005873 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005874 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005875 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005876 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005877
Robert Greenwalta029ea12013-09-25 16:38:12 -07005878 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005879 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005880 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005881 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005882 }
5883
5884 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005885 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005886 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005887 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005888 }
5889
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005890 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005891
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005892 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005893 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005894 final long elapsedRealtime = mClocks.elapsedRealtime();
5895 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005896 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005897 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005898 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
5899 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005900 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08005901
5902 // Start Wifi Multicast overall timer
5903 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
5904 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
5905 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
5906 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005907 }
5908 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005909 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005910 }
5911
5912 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005913 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005914 final long elapsedRealtime = mClocks.elapsedRealtime();
5915 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005916 mWifiMulticastNesting--;
5917 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005918 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005919 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
5920 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005921 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08005922
5923 // Stop Wifi Multicast overall timer
5924 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
5925 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
5926 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
5927 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005928 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005929 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005930 }
5931
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005932 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
5933 int N = ws.size();
5934 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005935 final int uid = mapUid(ws.get(i));
5936 noteFullWifiLockAcquiredLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005937 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i), 1);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005938 }
5939
5940 final List<WorkChain> workChains = ws.getWorkChains();
5941 if (workChains != null) {
5942 for (int i = 0; i < workChains.size(); ++i) {
5943 final WorkChain workChain = workChains.get(i);
5944 final int uid = mapUid(workChain.getAttributionUid());
5945 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08005946 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
5947 workChain.getUids(), workChain.getTags(), 1);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005948 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005949 }
5950 }
5951
5952 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
5953 int N = ws.size();
5954 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005955 final int uid = mapUid(ws.get(i));
5956 noteFullWifiLockReleasedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005957 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i), 0);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005958 }
5959
5960 final List<WorkChain> workChains = ws.getWorkChains();
5961 if (workChains != null) {
5962 for (int i = 0; i < workChains.size(); ++i) {
5963 final WorkChain workChain = workChains.get(i);
5964 final int uid = mapUid(workChain.getAttributionUid());
5965 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08005966 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
5967 workChain.getUids(), workChain.getTags(), 0);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005968 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005969 }
5970 }
5971
Nick Pelly6ccaa542012-06-15 15:22:47 -07005972 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005973 int N = ws.size();
5974 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005975 final int uid = mapUid(ws.get(i));
5976 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005977 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
5978 1);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005979 }
5980
5981 final List<WorkChain> workChains = ws.getWorkChains();
5982 if (workChains != null) {
5983 for (int i = 0; i < workChains.size(); ++i) {
5984 final WorkChain workChain = workChains.get(i);
5985 final int uid = mapUid(workChain.getAttributionUid());
5986 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08005987 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
5988 workChain.getTags(), 1);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005989 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005990 }
5991 }
5992
Nick Pelly6ccaa542012-06-15 15:22:47 -07005993 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005994 int N = ws.size();
5995 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005996 final int uid = mapUid(ws.get(i));
5997 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005998 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
5999 0);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006000 }
6001
6002 final List<WorkChain> workChains = ws.getWorkChains();
6003 if (workChains != null) {
6004 for (int i = 0; i < workChains.size(); ++i) {
6005 final WorkChain workChain = workChains.get(i);
6006 final int uid = mapUid(workChain.getAttributionUid());
6007 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006008 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
6009 workChain.getUids(), workChain.getTags(), 0);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006010 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006011 }
6012 }
6013
Robert Greenwalta029ea12013-09-25 16:38:12 -07006014 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6015 int N = ws.size();
6016 for (int i=0; i<N; i++) {
6017 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6018 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006019
6020 final List<WorkChain> workChains = ws.getWorkChains();
6021 if (workChains != null) {
6022 for (int i = 0; i < workChains.size(); ++i) {
6023 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6024 }
6025 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006026 }
6027
6028 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6029 int N = ws.size();
6030 for (int i=0; i<N; i++) {
6031 noteWifiBatchedScanStoppedLocked(ws.get(i));
6032 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006033
6034 final List<WorkChain> workChains = ws.getWorkChains();
6035 if (workChains != null) {
6036 for (int i = 0; i < workChains.size(); ++i) {
6037 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6038 }
6039 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006040 }
6041
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006042 private static String[] includeInStringArray(String[] array, String str) {
6043 if (ArrayUtils.indexOf(array, str) >= 0) {
6044 return array;
6045 }
6046 String[] newArray = new String[array.length+1];
6047 System.arraycopy(array, 0, newArray, 0, array.length);
6048 newArray[array.length] = str;
6049 return newArray;
6050 }
6051
6052 private static String[] excludeFromStringArray(String[] array, String str) {
6053 int index = ArrayUtils.indexOf(array, str);
6054 if (index >= 0) {
6055 String[] newArray = new String[array.length-1];
6056 if (index > 0) {
6057 System.arraycopy(array, 0, newArray, 0, index);
6058 }
6059 if (index < array.length-1) {
6060 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6061 }
6062 return newArray;
6063 }
6064 return array;
6065 }
6066
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006067 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006068 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006069
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006070 synchronized (mModemNetworkLock) {
6071 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6072 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6073 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6074 } else {
6075 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6076 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6077 }
6078 }
6079
6080 synchronized (mWifiNetworkLock) {
6081 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6082 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6083 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6084 } else {
6085 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6086 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6087 }
6088 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006089 }
6090
David Chenc8a43242017-10-17 16:23:28 -07006091 public String[] getWifiIfaces() {
6092 synchronized (mWifiNetworkLock) {
6093 return mWifiIfaces;
6094 }
6095 }
6096
6097 public String[] getMobileIfaces() {
6098 synchronized (mModemNetworkLock) {
6099 return mModemIfaces;
6100 }
6101 }
6102
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006103 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6104 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006106
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006107 @Override public int getScreenOnCount(int which) {
6108 return mScreenOnTimer.getCountLocked(which);
6109 }
6110
Mike Mac2f518a2017-09-19 16:06:03 -07006111 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6112 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6113 }
6114
6115 @Override public int getScreenDozeCount(int which) {
6116 return mScreenDozeTimer.getCountLocked(which);
6117 }
6118
Dianne Hackborn617f8772009-03-31 15:04:46 -07006119 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006120 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006121 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006122 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006123 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006124
Kweku Adams87b19ec2017-10-09 12:40:03 -07006125 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6126 return mScreenBrightnessTimer[brightnessBin];
6127 }
6128
Jeff Browne95c3cd2014-05-02 16:59:26 -07006129 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6130 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006131 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006132
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006133 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6134 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006135 }
6136
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006137 @Override public int getPowerSaveModeEnabledCount(int which) {
6138 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6139 }
6140
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006141 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6142 int which) {
6143 switch (mode) {
6144 case DEVICE_IDLE_MODE_LIGHT:
6145 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006146 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006147 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6148 }
6149 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006150 }
6151
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006152 @Override public int getDeviceIdleModeCount(int mode, int which) {
6153 switch (mode) {
6154 case DEVICE_IDLE_MODE_LIGHT:
6155 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006156 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006157 return mDeviceIdleModeFullTimer.getCountLocked(which);
6158 }
6159 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006160 }
6161
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006162 @Override public long getLongestDeviceIdleModeTime(int mode) {
6163 switch (mode) {
6164 case DEVICE_IDLE_MODE_LIGHT:
6165 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006166 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006167 return mLongestFullIdleTime;
6168 }
6169 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006170 }
6171
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006172 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6173 switch (mode) {
6174 case DEVICE_IDLE_MODE_LIGHT:
6175 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006176 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006177 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6178 }
6179 return 0;
6180 }
6181
6182 @Override public int getDeviceIdlingCount(int mode, int which) {
6183 switch (mode) {
6184 case DEVICE_IDLE_MODE_LIGHT:
6185 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006186 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006187 return mDeviceIdlingTimer.getCountLocked(which);
6188 }
6189 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006190 }
6191
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006192 @Override public int getNumConnectivityChange(int which) {
6193 int val = mNumConnectivityChange;
6194 if (which == STATS_CURRENT) {
6195 val -= mLoadedNumConnectivityChange;
6196 } else if (which == STATS_SINCE_UNPLUGGED) {
6197 val -= mUnpluggedNumConnectivityChange;
6198 }
6199 return val;
6200 }
6201
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006202 @Override public long getGpsSignalQualityTime(int strengthBin,
6203 long elapsedRealtimeUs, int which) {
6204 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6205 return 0;
6206 }
6207 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6208 elapsedRealtimeUs, which);
6209 }
6210
6211 @Override public long getGpsBatteryDrainMaMs() {
6212 //TODO: Add GPS power computation (b/67213967)
6213 return 0;
6214 }
6215
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006216 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6217 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006219
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006220 @Override public int getPhoneOnCount(int which) {
6221 return mPhoneOnTimer.getCountLocked(which);
6222 }
6223
Dianne Hackborn627bba72009-03-24 22:32:56 -07006224 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006225 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006226 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006227 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006228 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006229
6230 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006231 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006232 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006233 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006234 }
6235
Kweku Adams87b19ec2017-10-09 12:40:03 -07006236 @Override public Timer getPhoneSignalScanningTimer() {
6237 return mPhoneSignalScanningTimer;
6238 }
6239
Catherine Liufb900812012-07-17 14:12:56 -05006240 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6241 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006242 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006243
Kweku Adams87b19ec2017-10-09 12:40:03 -07006244 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6245 return mPhoneSignalStrengthsTimer[strengthBin];
6246 }
6247
Dianne Hackborn627bba72009-03-24 22:32:56 -07006248 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006249 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006250 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006251 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006252 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006253
Dianne Hackborn617f8772009-03-31 15:04:46 -07006254 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006255 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006256 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006257
Kweku Adams87b19ec2017-10-09 12:40:03 -07006258 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6259 return mPhoneDataConnectionsTimer[dataType];
6260 }
6261
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006262 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6263 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006264 }
6265
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006266 @Override public int getMobileRadioActiveCount(int which) {
6267 return mMobileRadioActiveTimer.getCountLocked(which);
6268 }
6269
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006270 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6271 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6272 }
6273
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006274 @Override public long getMobileRadioActiveUnknownTime(int which) {
6275 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6276 }
6277
6278 @Override public int getMobileRadioActiveUnknownCount(int which) {
6279 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6280 }
6281
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006282 @Override public long getWifiMulticastWakelockTime(
6283 long elapsedRealtimeUs, int which) {
6284 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6285 elapsedRealtimeUs, which);
6286 }
6287
6288 @Override public int getWifiMulticastWakelockCount(int which) {
6289 return mWifiMulticastWakelockTimer.getCountLocked(which);
6290 }
6291
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006292 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6293 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006294 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006295
Siddharth Rayb50a6842017-12-14 15:15:28 -08006296 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6297 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6298 }
6299
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006300 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6301 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006302 }
6303
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006304 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006305 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006306 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006307 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006308 }
6309
6310 @Override public int getWifiStateCount(int wifiState, int which) {
6311 return mWifiStateTimer[wifiState].getCountLocked(which);
6312 }
6313
Kweku Adams87b19ec2017-10-09 12:40:03 -07006314 @Override public Timer getWifiStateTimer(int wifiState) {
6315 return mWifiStateTimer[wifiState];
6316 }
6317
Dianne Hackborn3251b902014-06-20 14:40:53 -07006318 @Override public long getWifiSupplStateTime(int state,
6319 long elapsedRealtimeUs, int which) {
6320 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6321 elapsedRealtimeUs, which);
6322 }
6323
6324 @Override public int getWifiSupplStateCount(int state, int which) {
6325 return mWifiSupplStateTimer[state].getCountLocked(which);
6326 }
6327
Kweku Adams87b19ec2017-10-09 12:40:03 -07006328 @Override public Timer getWifiSupplStateTimer(int state) {
6329 return mWifiSupplStateTimer[state];
6330 }
6331
Dianne Hackborn3251b902014-06-20 14:40:53 -07006332 @Override public long getWifiSignalStrengthTime(int strengthBin,
6333 long elapsedRealtimeUs, int which) {
6334 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6335 elapsedRealtimeUs, which);
6336 }
6337
6338 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6339 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6340 }
6341
Kweku Adams87b19ec2017-10-09 12:40:03 -07006342 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6343 return mWifiSignalStrengthsTimer[strengthBin];
6344 }
6345
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006346 @Override
6347 public ControllerActivityCounter getBluetoothControllerActivity() {
6348 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006349 }
6350
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006351 @Override
6352 public ControllerActivityCounter getWifiControllerActivity() {
6353 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006354 }
6355
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006356 @Override
6357 public ControllerActivityCounter getModemControllerActivity() {
6358 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006359 }
6360
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006361 @Override
6362 public boolean hasBluetoothActivityReporting() {
6363 return mHasBluetoothReporting;
6364 }
6365
6366 @Override
6367 public boolean hasWifiActivityReporting() {
6368 return mHasWifiReporting;
6369 }
6370
6371 @Override
6372 public boolean hasModemActivityReporting() {
6373 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006374 }
6375
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006376 @Override
6377 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006378 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6379 }
6380
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006381 @Override
6382 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006383 return mFlashlightOnTimer.getCountLocked(which);
6384 }
6385
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006386 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006387 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6388 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6389 }
6390
6391 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006392 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6393 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6394 }
6395
6396 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006397 public long getNetworkActivityBytes(int type, int which) {
6398 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6399 return mNetworkByteActivityCounters[type].getCountLocked(which);
6400 } else {
6401 return 0;
6402 }
6403 }
6404
6405 @Override
6406 public long getNetworkActivityPackets(int type, int which) {
6407 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6408 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006409 } else {
6410 return 0;
6411 }
6412 }
6413
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006414 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006415 final long currentTime = System.currentTimeMillis();
6416 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006417 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6418 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006419 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006420 return mStartClockTime;
6421 }
6422
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006423 @Override public String getStartPlatformVersion() {
6424 return mStartPlatformVersion;
6425 }
6426
6427 @Override public String getEndPlatformVersion() {
6428 return mEndPlatformVersion;
6429 }
6430
6431 @Override public int getParcelVersion() {
6432 return VERSION;
6433 }
6434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006435 @Override public boolean getIsOnBattery() {
6436 return mOnBattery;
6437 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6440 return mUidStats;
6441 }
6442
Adam Lesinski5f056f62016-07-14 16:56:08 -07006443 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6444 if (timer != null) {
6445 timer.detach();
6446 }
6447 }
6448
6449 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6450 boolean detachIfReset) {
6451 if (timer != null) {
6452 return timer.reset(detachIfReset);
6453 }
6454 return true;
6455 }
6456
Bookatz867c0d72017-03-07 18:23:42 -08006457 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6458 if (timer != null) {
6459 return timer.reset(detachIfReset);
6460 }
6461 return true;
6462 }
6463
Adam Lesinski5f056f62016-07-14 16:56:08 -07006464 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6465 if (counter != null) {
6466 counter.detach();
6467 }
6468 }
6469
6470 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6471 boolean detachIfReset) {
6472 if (counter != null) {
6473 counter.reset(detachIfReset);
6474 }
6475 }
6476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 /**
6478 * The statistics associated with a particular uid.
6479 */
Joe Onoratoabded112016-02-08 16:49:39 -08006480 public static class Uid extends BatteryStats.Uid {
6481 /**
6482 * BatteryStatsImpl that we are associated with.
6483 */
6484 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006487
Bookatz867c0d72017-03-07 18:23:42 -08006488 /** TimeBase for when uid is in background and device is on battery. */
6489 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6490 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006491 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6492 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006493
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006494 boolean mWifiRunning;
6495 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006496
The Android Open Source Project10592532009-03-18 17:39:46 -07006497 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006498 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006499
Nick Pelly6ccaa542012-06-15 15:22:47 -07006500 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006501 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006502
Dianne Hackborn61659e52014-07-09 16:13:01 -07006503 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006504 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6505 StopwatchTimer[] mWifiBatchedScanTimer;
6506
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006507 boolean mWifiMulticastEnabled;
6508 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006509
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006510 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006511 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006512 StopwatchTimer mFlashlightTurnedOnTimer;
6513 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006514 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006515 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006516 /** Total time spent by the uid holding any partial wakelocks. */
6517 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006518 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006519 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006520 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006521 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006522
Dianne Hackborna8d10942015-11-19 17:55:19 -08006523 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006524 StopwatchTimer[] mProcessStateTimer;
6525
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006526 boolean mInForegroundService = false;
6527
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006528 BatchTimer mVibratorOnTimer;
6529
Dianne Hackborn617f8772009-03-31 15:04:46 -07006530 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006531
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006532 LongSamplingCounter[] mNetworkByteActivityCounters;
6533 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006534 LongSamplingCounter mMobileRadioActiveTime;
6535 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006538 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6539 */
6540 private LongSamplingCounter mMobileRadioApWakeupCount;
6541
6542 /**
6543 * How many times this UID woke up the Application Processor due to a Wifi packet.
6544 */
6545 private LongSamplingCounter mWifiRadioApWakeupCount;
6546
6547 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006548 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006549 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006550 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006551 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006552
6553 /**
6554 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006555 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006556 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006557 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6558
6559 /**
6560 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6561 * Can be null if the UID has had no such activity.
6562 */
6563 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006564
6565 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006566 * The CPU times we had at the last history details update.
6567 */
6568 long mLastStepUserTime;
6569 long mLastStepSystemTime;
6570 long mCurStepUserTime;
6571 long mCurStepSystemTime;
6572
Joe Onoratoabded112016-02-08 16:49:39 -08006573 LongSamplingCounter mUserCpuTime;
6574 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006575 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006576 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006577
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006578 LongSamplingCounterArray mCpuFreqTimeMs;
6579 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006580 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006581
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006582 LongSamplingCounterArray[] mProcStateTimeMs;
6583 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6584
6585 IntArray mChildUids;
6586
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006587 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 * The statistics we have collected for this uid's wake locks.
6589 */
Joe Onoratoabded112016-02-08 16:49:39 -08006590 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006591
6592 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006593 * The statistics we have collected for this uid's syncs.
6594 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006595 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006596
6597 /**
6598 * The statistics we have collected for this uid's jobs.
6599 */
Bookatzaa4594a2017-03-24 12:39:56 -07006600 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006601
6602 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006603 * Count of the jobs that have completed and the reasons why they completed.
6604 */
6605 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6606
6607 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 * The statistics we have collected for this uid's sensor activations.
6609 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006610 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611
6612 /**
6613 * The statistics we have collected for this uid's processes.
6614 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006615 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616
6617 /**
6618 * The statistics we have collected for this uid's processes.
6619 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006620 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006621
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006622 /**
6623 * The transient wake stats we have collected for this uid's pids.
6624 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006625 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006626
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00006627 /**
6628 * The list of WorkChains associated with active bluetooth scans.
6629 *
6630 * NOTE: This is a hack and it only needs to exist because there's a "reset" API that is
6631 * supposed to stop and log all WorkChains that were currently active.
6632 */
6633 ArrayList<WorkChain> mAllBluetoothChains = null;
6634 ArrayList<WorkChain> mUnoptimizedBluetoothChains = null;
6635
Joe Onoratoabded112016-02-08 16:49:39 -08006636 public Uid(BatteryStatsImpl bsi, int uid) {
6637 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006638 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006639
Bookatz867c0d72017-03-07 18:23:42 -08006640 mOnBatteryBackgroundTimeBase = new TimeBase();
6641 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6642 mBsi.mClocks.elapsedRealtime() * 1000);
6643
Bookatzc8c44962017-05-11 12:12:54 -07006644 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6645 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6646 mBsi.mClocks.elapsedRealtime() * 1000);
6647
Joe Onoratoabded112016-02-08 16:49:39 -08006648 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6649 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006650 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6651 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006652
Dianne Hackborn657153b2016-07-29 14:54:14 -07006653 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006654 @Override public Wakelock instantiateObject() {
6655 return new Wakelock(mBsi, Uid.this);
6656 }
6657 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006658 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6659 @Override public DualTimer instantiateObject() {
6660 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6661 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006662 }
6663 };
Bookatzaa4594a2017-03-24 12:39:56 -07006664 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6665 @Override public DualTimer instantiateObject() {
6666 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6667 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006668 }
6669 };
6670
6671 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6672 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6673 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6674 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006675 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6676 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006677 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006678 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6679 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006680 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006681 }
6682
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006683 @VisibleForTesting
6684 public void setProcessStateForTest(int procState) {
6685 mProcessState = procState;
6686 }
6687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006688 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006689 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006690 return nullIfAllZeros(mCpuFreqTimeMs, which);
6691 }
6692
6693 @Override
6694 public long[] getScreenOffCpuFreqTimes(int which) {
6695 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6696 }
6697
6698 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006699 public long getCpuActiveTime() {
6700 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6701 }
6702
6703 @Override
6704 public long[] getCpuClusterTimes() {
6705 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6706 }
6707
6708
6709 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006710 public long[] getCpuFreqTimes(int which, int procState) {
6711 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006712 return null;
6713 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006714 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006715 return null;
6716 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006717 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6718 mProcStateTimeMs = null;
6719 return null;
6720 }
6721 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6722 }
6723
6724 @Override
6725 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6726 if (which < 0 || which >= NUM_PROCESS_STATE) {
6727 return null;
6728 }
6729 if (mProcStateScreenOffTimeMs == null) {
6730 return null;
6731 }
6732 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6733 mProcStateScreenOffTimeMs = null;
6734 return null;
6735 }
6736 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6737 }
6738
6739 public void addIsolatedUid(int isolatedUid) {
6740 if (mChildUids == null) {
6741 mChildUids = new IntArray();
6742 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6743 return;
6744 }
6745 mChildUids.add(isolatedUid);
6746 }
6747
6748 public void removeIsolatedUid(int isolatedUid) {
6749 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6750 if (idx < 0) {
6751 return;
6752 }
6753 mChildUids.remove(idx);
6754 }
6755
6756 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6757 if (cpuTimesMs == null) {
6758 return null;
6759 }
6760 final long[] counts = cpuTimesMs.getCountsLocked(which);
6761 if (counts == null) {
6762 return null;
6763 }
6764 // Return counts only if at least one of the elements is non-zero.
6765 for (int i = counts.length - 1; i >= 0; --i) {
6766 if (counts[i] != 0) {
6767 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006768 }
6769 }
6770 return null;
6771 }
6772
Sudheer Shankae544d162017-12-28 17:06:20 -08006773 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006774 if (mProcStateTimeMs == null) {
6775 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006776 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006777 if (mProcStateTimeMs[procState] == null
6778 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
6779 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6780 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006781 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006782 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006783 }
6784
Sudheer Shankae544d162017-12-28 17:06:20 -08006785 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6786 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006787 if (mProcStateScreenOffTimeMs == null) {
6788 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006789 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006790 if (mProcStateScreenOffTimeMs[procState] == null
6791 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
6792 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
6793 mBsi.mOnBatteryScreenOffTimeBase);
6794 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006795 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006796 }
6797
6798 @Override
Bookatzc8c44962017-05-11 12:12:54 -07006799 public Timer getAggregatedPartialWakelockTimer() {
6800 return mAggregatedPartialWakelockTimer;
6801 }
6802
6803 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006804 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006805 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006806 }
6807
6808 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07006809 public Timer getMulticastWakelockStats() {
6810 return mWifiMulticastTimer;
6811 }
6812
6813 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006814 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006815 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006816 }
6817
6818 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006819 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006820 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006821 }
6822
6823 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006824 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
6825 return mJobCompletions;
6826 }
6827
6828 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07006829 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006830 return mSensorStats;
6831 }
6832
6833 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006834 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006835 return mProcessStats;
6836 }
6837
6838 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006839 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 return mPackageStats;
6841 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006842
6843 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844 public int getUid() {
6845 return mUid;
6846 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006847
6848 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006849 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006850 if (!mWifiRunning) {
6851 mWifiRunning = true;
6852 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006853 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
6854 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006855 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006856 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006857 }
6858 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006859
Dianne Hackborn617f8772009-03-31 15:04:46 -07006860 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006861 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006862 if (mWifiRunning) {
6863 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006864 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006865 }
6866 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006867
Dianne Hackborn617f8772009-03-31 15:04:46 -07006868 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006869 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006870 if (!mFullWifiLockOut) {
6871 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006872 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006873 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
6874 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006875 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006876 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006877 }
6878 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006879
The Android Open Source Project10592532009-03-18 17:39:46 -07006880 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006881 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006882 if (mFullWifiLockOut) {
6883 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006884 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006885 }
6886 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006887
The Android Open Source Project10592532009-03-18 17:39:46 -07006888 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006889 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006890 if (!mWifiScanStarted) {
6891 mWifiScanStarted = true;
6892 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006893 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
6894 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
6895 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006896 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006897 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006898 }
6899 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006900
The Android Open Source Project10592532009-03-18 17:39:46 -07006901 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006902 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006903 if (mWifiScanStarted) {
6904 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006905 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006906 }
6907 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006908
6909 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006910 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006911 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07006912 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006913 csph = csph >> 3;
6914 bin++;
6915 }
6916
6917 if (mWifiBatchedScanBinStarted == bin) return;
6918
6919 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
6920 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006921 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006922 }
6923 mWifiBatchedScanBinStarted = bin;
6924 if (mWifiBatchedScanTimer[bin] == null) {
6925 makeWifiBatchedScanBin(bin, null);
6926 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006927 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006928 }
6929
6930 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006931 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006932 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
6933 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006934 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006935 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6936 }
6937 }
6938
6939 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006940 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006941 if (!mWifiMulticastEnabled) {
6942 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006943 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006944 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6945 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006946 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006947 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006948 }
6949 }
6950
6951 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006952 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006953 if (mWifiMulticastEnabled) {
6954 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006955 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006956 }
6957 }
6958
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006959 @Override
6960 public ControllerActivityCounter getWifiControllerActivity() {
6961 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006962 }
6963
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006964 @Override
6965 public ControllerActivityCounter getBluetoothControllerActivity() {
6966 return mBluetoothControllerActivity;
6967 }
6968
6969 @Override
6970 public ControllerActivityCounter getModemControllerActivity() {
6971 return mModemControllerActivity;
6972 }
6973
6974 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
6975 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006976 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006977 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08006978 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006979 return mWifiControllerActivity;
6980 }
6981
6982 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
6983 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006984 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006985 NUM_BT_TX_LEVELS);
6986 }
6987 return mBluetoothControllerActivity;
6988 }
6989
6990 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
6991 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006992 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006993 ModemActivityInfo.TX_POWER_LEVELS);
6994 }
6995 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08006996 }
6997
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006998 public StopwatchTimer createAudioTurnedOnTimerLocked() {
6999 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007000 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7001 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007002 }
7003 return mAudioTurnedOnTimer;
7004 }
7005
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007006 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007007 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007008 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null, 1);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007009 }
7010
7011 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7012 if (mAudioTurnedOnTimer != null) {
7013 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007014 if (!mAudioTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007015 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07007016 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007017 }
7018 }
7019
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007020 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7021 if (mAudioTurnedOnTimer != null) {
7022 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007023 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null, 0);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007024 }
7025 }
7026
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007027 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7028 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007029 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7030 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007031 }
7032 return mVideoTurnedOnTimer;
7033 }
7034
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007035 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007036 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007037 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null, 1);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007038 }
7039
7040 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7041 if (mVideoTurnedOnTimer != null) {
7042 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007043 if (!mVideoTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007044 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(),
7045 null, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07007046 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007047 }
7048 }
7049
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007050 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7051 if (mVideoTurnedOnTimer != null) {
7052 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007053 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
7054 0);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007055 }
7056 }
7057
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007058 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7059 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007060 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7061 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007062 }
7063 return mFlashlightTurnedOnTimer;
7064 }
7065
7066 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7067 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007068 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,1);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007069 }
7070
7071 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7072 if (mFlashlightTurnedOnTimer != null) {
7073 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007074 if (!mFlashlightTurnedOnTimer.isRunningLocked()) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08007075 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7076 0);
Bookatzc1a050a2017-10-10 15:49:28 -07007077 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007078 }
7079 }
7080
7081 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7082 if (mFlashlightTurnedOnTimer != null) {
7083 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007084 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null, 0);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007085 }
7086 }
7087
7088 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7089 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007090 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7091 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007092 }
7093 return mCameraTurnedOnTimer;
7094 }
7095
7096 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7097 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007098 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null, 1);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007099 }
7100
7101 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7102 if (mCameraTurnedOnTimer != null) {
7103 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007104 if (!mCameraTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007105 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07007106 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007107 }
7108 }
7109
7110 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7111 if (mCameraTurnedOnTimer != null) {
7112 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007113 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null, 0);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007114 }
7115 }
7116
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007117 public StopwatchTimer createForegroundActivityTimerLocked() {
7118 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007119 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7120 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007121 }
7122 return mForegroundActivityTimer;
7123 }
7124
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007125 public StopwatchTimer createForegroundServiceTimerLocked() {
7126 if (mForegroundServiceTimer == null) {
7127 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7128 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7129 }
7130 return mForegroundServiceTimer;
7131 }
7132
Bookatzc8c44962017-05-11 12:12:54 -07007133 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7134 if (mAggregatedPartialWakelockTimer == null) {
7135 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7136 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7137 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7138 }
7139 return mAggregatedPartialWakelockTimer;
7140 }
7141
Bookatz867c0d72017-03-07 18:23:42 -08007142 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007143 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007144 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7145 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7146 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007147 }
7148 return mBluetoothScanTimer;
7149 }
7150
Bookatzb1f04f32017-05-19 13:57:32 -07007151 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7152 if (mBluetoothUnoptimizedScanTimer == null) {
7153 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7154 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7155 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7156 }
7157 return mBluetoothUnoptimizedScanTimer;
7158 }
7159
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007160 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7161 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007162 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007163 if (isUnoptimized) {
7164 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7165 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007166 }
7167
Bookatz94c5a312017-07-11 16:49:17 -07007168 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007169 if (mBluetoothScanTimer != null) {
7170 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7171 }
Bookatz94c5a312017-07-11 16:49:17 -07007172 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007173 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7174 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007175 }
7176
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007177 public void addBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7178 if (mAllBluetoothChains == null) {
7179 mAllBluetoothChains = new ArrayList<WorkChain>(4);
7180 }
7181
7182 if (isUnoptimized && mUnoptimizedBluetoothChains == null) {
7183 mUnoptimizedBluetoothChains = new ArrayList<WorkChain>(4);
7184 }
7185
7186 mAllBluetoothChains.add(workChain);
7187 if (isUnoptimized) {
7188 mUnoptimizedBluetoothChains.add(workChain);
7189 }
7190 }
7191
7192 public void removeBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7193 if (mAllBluetoothChains != null) {
7194 mAllBluetoothChains.remove(workChain);
7195 }
7196
7197 if (isUnoptimized && mUnoptimizedBluetoothChains != null) {
7198 mUnoptimizedBluetoothChains.remove(workChain);
7199 }
7200 }
7201
7202 public List<WorkChain> getAllBluetoothWorkChains() {
7203 return mAllBluetoothChains;
7204 }
7205
7206 public List<WorkChain> getUnoptimizedBluetoothWorkChains() {
7207 return mUnoptimizedBluetoothChains;
7208 }
7209
7210
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007211 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7212 if (mBluetoothScanTimer != null) {
7213 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7214 }
Bookatzb1f04f32017-05-19 13:57:32 -07007215 if (mBluetoothUnoptimizedScanTimer != null) {
7216 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7217 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007218 }
7219
Bookatz956f36bf2017-04-28 09:48:17 -07007220 public Counter createBluetoothScanResultCounterLocked() {
7221 if (mBluetoothScanResultCounter == null) {
7222 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7223 }
7224 return mBluetoothScanResultCounter;
7225 }
7226
Bookatzb1f04f32017-05-19 13:57:32 -07007227 public Counter createBluetoothScanResultBgCounterLocked() {
7228 if (mBluetoothScanResultBgCounter == null) {
7229 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7230 }
7231 return mBluetoothScanResultBgCounter;
7232 }
7233
Bookatz4ebc0642017-05-11 12:21:19 -07007234 public void noteBluetoothScanResultsLocked(int numNewResults) {
7235 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007236 // Uses background timebase, so the count will only be incremented if uid in background.
7237 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007238 }
7239
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007240 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007241 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007242 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007243 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007244 }
7245
7246 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007247 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007248 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007249 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007250 }
7251 }
7252
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007253 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7254 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7255 }
7256
7257 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7258 if (mForegroundServiceTimer != null) {
7259 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7260 }
7261 }
7262
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007263 public BatchTimer createVibratorOnTimerLocked() {
7264 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007265 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7266 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007267 }
7268 return mVibratorOnTimer;
7269 }
7270
7271 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007272 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007273 }
7274
7275 public void noteVibratorOffLocked() {
7276 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007277 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007278 }
7279 }
7280
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007281 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007282 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007283 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007284 return 0;
7285 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007286 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007287 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007288
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007289 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007290 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007291 if (mFullWifiLockTimer == null) {
7292 return 0;
7293 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007294 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007295 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007296
7297 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007298 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007299 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007300 return 0;
7301 }
Bookatzaa4594a2017-03-24 12:39:56 -07007302 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007303 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007304
7305 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007306 public int getWifiScanCount(int which) {
7307 if (mWifiScanTimer == null) {
7308 return 0;
7309 }
Bookatzaa4594a2017-03-24 12:39:56 -07007310 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007311 }
7312
7313 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007314 public Timer getWifiScanTimer() {
7315 return mWifiScanTimer;
7316 }
7317
7318 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007319 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007320 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007321 return 0;
7322 }
7323 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7324 }
7325
7326 @Override
7327 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7328 if (mWifiScanTimer == null) {
7329 return 0;
7330 }
7331 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007332 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007333 }
7334
7335 @Override
7336 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007337 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007338 return 0;
7339 }
7340 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7341 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007342 }
7343
7344 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007345 public Timer getWifiScanBackgroundTimer() {
7346 if (mWifiScanTimer == null) {
7347 return null;
7348 }
7349 return mWifiScanTimer.getSubTimer();
7350 }
7351
7352 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007353 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007354 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7355 if (mWifiBatchedScanTimer[csphBin] == null) {
7356 return 0;
7357 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007358 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007359 }
7360
7361 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007362 public int getWifiBatchedScanCount(int csphBin, int which) {
7363 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7364 if (mWifiBatchedScanTimer[csphBin] == null) {
7365 return 0;
7366 }
7367 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7368 }
7369
7370 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007371 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007372 if (mWifiMulticastTimer == null) {
7373 return 0;
7374 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007375 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007376 }
7377
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007378 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007379 public Timer getAudioTurnedOnTimer() {
7380 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007381 }
7382
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007383 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007384 public Timer getVideoTurnedOnTimer() {
7385 return mVideoTurnedOnTimer;
7386 }
7387
7388 @Override
7389 public Timer getFlashlightTurnedOnTimer() {
7390 return mFlashlightTurnedOnTimer;
7391 }
7392
7393 @Override
7394 public Timer getCameraTurnedOnTimer() {
7395 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007396 }
7397
Dianne Hackborn617f8772009-03-31 15:04:46 -07007398 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007399 public Timer getForegroundActivityTimer() {
7400 return mForegroundActivityTimer;
7401 }
7402
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007403 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007404 public Timer getForegroundServiceTimer() {
7405 return mForegroundServiceTimer;
7406 }
7407
7408 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007409 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007410 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007411 }
7412
7413 @Override
7414 public Timer getBluetoothScanBackgroundTimer() {
7415 if (mBluetoothScanTimer == null) {
7416 return null;
7417 }
7418 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007419 }
7420
Bookatz956f36bf2017-04-28 09:48:17 -07007421 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007422 public Timer getBluetoothUnoptimizedScanTimer() {
7423 return mBluetoothUnoptimizedScanTimer;
7424 }
7425
7426 @Override
7427 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7428 if (mBluetoothUnoptimizedScanTimer == null) {
7429 return null;
7430 }
7431 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7432 }
7433
7434 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007435 public Counter getBluetoothScanResultCounter() {
7436 return mBluetoothScanResultCounter;
7437 }
7438
Bookatzb1f04f32017-05-19 13:57:32 -07007439 @Override
7440 public Counter getBluetoothScanResultBgCounter() {
7441 return mBluetoothScanResultBgCounter;
7442 }
7443
Dianne Hackborn61659e52014-07-09 16:13:01 -07007444 void makeProcessState(int i, Parcel in) {
7445 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7446
7447 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007448 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7449 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007450 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007451 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7452 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007453 }
7454 }
7455
7456 @Override
7457 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7458 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7459 if (mProcessStateTimer[state] == null) {
7460 return 0;
7461 }
7462 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7463 }
7464
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007465 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007466 public Timer getProcessStateTimer(int state) {
7467 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7468 return mProcessStateTimer[state];
7469 }
7470
7471 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007472 public Timer getVibratorOnTimer() {
7473 return mVibratorOnTimer;
7474 }
7475
7476 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007477 public void noteUserActivityLocked(int type) {
7478 if (mUserActivityCounters == null) {
7479 initUserActivityLocked();
7480 }
Jeff Browndf693de2012-07-27 12:03:38 -07007481 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7482 mUserActivityCounters[type].stepAtomic();
7483 } else {
7484 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7485 new Throwable());
7486 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007487 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007488
Dianne Hackborn617f8772009-03-31 15:04:46 -07007489 @Override
7490 public boolean hasUserActivity() {
7491 return mUserActivityCounters != null;
7492 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007493
Dianne Hackborn617f8772009-03-31 15:04:46 -07007494 @Override
7495 public int getUserActivityCount(int type, int which) {
7496 if (mUserActivityCounters == null) {
7497 return 0;
7498 }
Evan Millarc64edde2009-04-18 12:26:32 -07007499 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007500 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007501
Robert Greenwalta029ea12013-09-25 16:38:12 -07007502 void makeWifiBatchedScanBin(int i, Parcel in) {
7503 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7504
Joe Onoratoabded112016-02-08 16:49:39 -08007505 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007506 if (collected == null) {
7507 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007508 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007509 }
7510 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007511 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7512 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007513 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007514 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7515 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007516 }
7517 }
7518
7519
Dianne Hackborn617f8772009-03-31 15:04:46 -07007520 void initUserActivityLocked() {
7521 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7522 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007523 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007524 }
7525 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007526
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007527 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7528 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007529 initNetworkActivityLocked();
7530 }
7531 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007532 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7533 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007534 } else {
7535 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7536 new Throwable());
7537 }
7538 }
7539
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007540 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7541 if (mNetworkByteActivityCounters == null) {
7542 initNetworkActivityLocked();
7543 }
7544 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7545 mMobileRadioActiveCount.addCountLocked(1);
7546 }
7547
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007548 @Override
7549 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007550 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007551 }
7552
7553 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007554 public long getNetworkActivityBytes(int type, int which) {
7555 if (mNetworkByteActivityCounters != null && type >= 0
7556 && type < mNetworkByteActivityCounters.length) {
7557 return mNetworkByteActivityCounters[type].getCountLocked(which);
7558 } else {
7559 return 0;
7560 }
7561 }
7562
7563 @Override
7564 public long getNetworkActivityPackets(int type, int which) {
7565 if (mNetworkPacketActivityCounters != null && type >= 0
7566 && type < mNetworkPacketActivityCounters.length) {
7567 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007568 } else {
7569 return 0;
7570 }
7571 }
7572
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007573 @Override
7574 public long getMobileRadioActiveTime(int which) {
7575 return mMobileRadioActiveTime != null
7576 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7577 }
7578
7579 @Override
7580 public int getMobileRadioActiveCount(int which) {
7581 return mMobileRadioActiveCount != null
7582 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7583 }
7584
Adam Lesinskie08af192015-03-25 16:42:59 -07007585 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007586 public long getUserCpuTimeUs(int which) {
7587 return mUserCpuTime.getCountLocked(which);
7588 }
7589
7590 @Override
7591 public long getSystemCpuTimeUs(int which) {
7592 return mSystemCpuTime.getCountLocked(which);
7593 }
7594
7595 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007596 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007597 if (mCpuClusterSpeedTimesUs != null) {
7598 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7599 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7600 if (cpuSpeedTimesUs != null) {
7601 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7602 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007603 if (c != null) {
7604 return c.getCountLocked(which);
7605 }
7606 }
7607 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007608 }
7609 }
7610 return 0;
7611 }
7612
Adam Lesinski5f056f62016-07-14 16:56:08 -07007613 public void noteMobileRadioApWakeupLocked() {
7614 if (mMobileRadioApWakeupCount == null) {
7615 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7616 }
7617 mMobileRadioApWakeupCount.addCountLocked(1);
7618 }
7619
7620 @Override
7621 public long getMobileRadioApWakeupCount(int which) {
7622 if (mMobileRadioApWakeupCount != null) {
7623 return mMobileRadioApWakeupCount.getCountLocked(which);
7624 }
7625 return 0;
7626 }
7627
7628 public void noteWifiRadioApWakeupLocked() {
7629 if (mWifiRadioApWakeupCount == null) {
7630 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7631 }
7632 mWifiRadioApWakeupCount.addCountLocked(1);
7633 }
7634
7635 @Override
7636 public long getWifiRadioApWakeupCount(int which) {
7637 if (mWifiRadioApWakeupCount != null) {
7638 return mWifiRadioApWakeupCount.getCountLocked(which);
7639 }
7640 return 0;
7641 }
7642
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007643 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007644 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7645 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007646 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007647 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7648 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007649 }
Joe Onoratoabded112016-02-08 16:49:39 -08007650 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7651 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007653
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007654 /**
7655 * Clear all stats for this uid. Returns true if the uid is completely
7656 * inactive so can be dropped.
7657 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007658 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007659 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007660 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007661
Bookatz993a0be2017-07-21 09:03:23 -07007662 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7663 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7664
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007665 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007666 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007667 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007668 }
7669 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007670 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007671 active |= mFullWifiLockOut;
7672 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007673 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007674 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007675 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007676 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007677 if (mWifiBatchedScanTimer != null) {
7678 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7679 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007680 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007681 }
7682 }
7683 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7684 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007685 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007686 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007687 active |= mWifiMulticastEnabled;
7688 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007689
7690 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7691 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7692 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7693 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7694 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007695 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007696 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007697 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007698 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007699 if (mBluetoothScanResultCounter != null) {
7700 mBluetoothScanResultCounter.reset(false);
7701 }
Bookatzb1f04f32017-05-19 13:57:32 -07007702 if (mBluetoothScanResultBgCounter != null) {
7703 mBluetoothScanResultBgCounter.reset(false);
7704 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007705
Dianne Hackborn61659e52014-07-09 16:13:01 -07007706 if (mProcessStateTimer != null) {
7707 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7708 if (mProcessStateTimer[i] != null) {
7709 active |= !mProcessStateTimer[i].reset(false);
7710 }
7711 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007712 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007713 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007714 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007715 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007716 mVibratorOnTimer.detach();
7717 mVibratorOnTimer = null;
7718 } else {
7719 active = true;
7720 }
7721 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007722
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007723 if (mUserActivityCounters != null) {
7724 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7725 mUserActivityCounters[i].reset(false);
7726 }
7727 }
7728
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007729 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007730 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007731 mNetworkByteActivityCounters[i].reset(false);
7732 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007733 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007734 mMobileRadioActiveTime.reset(false);
7735 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007736 }
7737
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007738 if (mWifiControllerActivity != null) {
7739 mWifiControllerActivity.reset(false);
7740 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007741
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007742 if (mBluetoothControllerActivity != null) {
7743 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007744 }
7745
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007746 if (mModemControllerActivity != null) {
7747 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007748 }
7749
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007750 mUserCpuTime.reset(false);
7751 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007752
Sudheer Shankaaf857412017-07-21 00:14:24 -07007753 if (mCpuClusterSpeedTimesUs != null) {
7754 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007755 if (speeds != null) {
7756 for (LongSamplingCounter speed : speeds) {
7757 if (speed != null) {
7758 speed.reset(false);
7759 }
7760 }
7761 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007762 }
7763 }
7764
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007765 if (mCpuFreqTimeMs != null) {
7766 mCpuFreqTimeMs.reset(false);
7767 }
7768 if (mScreenOffCpuFreqTimeMs != null) {
7769 mScreenOffCpuFreqTimeMs.reset(false);
7770 }
7771
Mike Ma3d422c32017-10-25 11:08:57 -07007772 mCpuActiveTimeMs.reset(false);
7773 mCpuClusterTimesMs.reset(false);
7774
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007775 if (mProcStateTimeMs != null) {
7776 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7777 if (counters != null) {
7778 counters.reset(false);
7779 }
7780 }
7781 }
7782 if (mProcStateScreenOffTimeMs != null) {
7783 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7784 if (counters != null) {
7785 counters.reset(false);
7786 }
7787 }
7788 }
7789
Adam Lesinski5f056f62016-07-14 16:56:08 -07007790 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
7791 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
7792
Dianne Hackbornd953c532014-08-16 18:17:38 -07007793 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7794 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
7795 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007796 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007797 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007798 } else {
7799 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007800 }
7801 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007802 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07007803 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007804 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07007805 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007806 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007807 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007808 timer.detach();
7809 } else {
7810 active = true;
7811 }
7812 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007813 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07007814 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007815 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07007816 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007817 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007818 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007819 timer.detach();
7820 } else {
7821 active = true;
7822 }
7823 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007824 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007825 mJobCompletions.clear();
Dianne Hackborn61659e52014-07-09 16:13:01 -07007826 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
7827 Sensor s = mSensorStats.valueAt(ise);
7828 if (s.reset()) {
7829 mSensorStats.removeAt(ise);
7830 } else {
7831 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007832 }
7833 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07007834 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
7835 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08007836 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007837 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007838 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007839 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007840 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007841 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007842 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007843 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007844 } else {
7845 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007846 }
7847 }
7848 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007849 if (mPackageStats.size() > 0) {
7850 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
7851 while (it.hasNext()) {
7852 Map.Entry<String, Pkg> pkgEntry = it.next();
7853 Pkg p = pkgEntry.getValue();
7854 p.detach();
7855 if (p.mServiceStats.size() > 0) {
7856 Iterator<Map.Entry<String, Pkg.Serv>> it2
7857 = p.mServiceStats.entrySet().iterator();
7858 while (it2.hasNext()) {
7859 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
7860 servEntry.getValue().detach();
7861 }
7862 }
7863 }
7864 mPackageStats.clear();
7865 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007866
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08007867 mLastStepUserTime = mLastStepSystemTime = 0;
7868 mCurStepUserTime = mCurStepSystemTime = 0;
7869
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007870 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007871 if (mWifiRunningTimer != null) {
7872 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007873 }
7874 if (mFullWifiLockTimer != null) {
7875 mFullWifiLockTimer.detach();
7876 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007877 if (mWifiScanTimer != null) {
7878 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007879 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007880 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7881 if (mWifiBatchedScanTimer[i] != null) {
7882 mWifiBatchedScanTimer[i].detach();
7883 }
7884 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007885 if (mWifiMulticastTimer != null) {
7886 mWifiMulticastTimer.detach();
7887 }
7888 if (mAudioTurnedOnTimer != null) {
7889 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007890 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007891 }
7892 if (mVideoTurnedOnTimer != null) {
7893 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007894 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007895 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007896 if (mFlashlightTurnedOnTimer != null) {
7897 mFlashlightTurnedOnTimer.detach();
7898 mFlashlightTurnedOnTimer = null;
7899 }
7900 if (mCameraTurnedOnTimer != null) {
7901 mCameraTurnedOnTimer.detach();
7902 mCameraTurnedOnTimer = null;
7903 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007904 if (mForegroundActivityTimer != null) {
7905 mForegroundActivityTimer.detach();
7906 mForegroundActivityTimer = null;
7907 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007908 if (mForegroundServiceTimer != null) {
7909 mForegroundServiceTimer.detach();
7910 mForegroundServiceTimer = null;
7911 }
Bookatzc8c44962017-05-11 12:12:54 -07007912 if (mAggregatedPartialWakelockTimer != null) {
7913 mAggregatedPartialWakelockTimer.detach();
7914 mAggregatedPartialWakelockTimer = null;
7915 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007916 if (mBluetoothScanTimer != null) {
7917 mBluetoothScanTimer.detach();
7918 mBluetoothScanTimer = null;
7919 }
Bookatzb1f04f32017-05-19 13:57:32 -07007920 if (mBluetoothUnoptimizedScanTimer != null) {
7921 mBluetoothUnoptimizedScanTimer.detach();
7922 mBluetoothUnoptimizedScanTimer = null;
7923 }
Bookatz956f36bf2017-04-28 09:48:17 -07007924 if (mBluetoothScanResultCounter != null) {
7925 mBluetoothScanResultCounter.detach();
7926 mBluetoothScanResultCounter = null;
7927 }
Bookatzb1f04f32017-05-19 13:57:32 -07007928 if (mBluetoothScanResultBgCounter != null) {
7929 mBluetoothScanResultBgCounter.detach();
7930 mBluetoothScanResultBgCounter = null;
7931 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007932 if (mUserActivityCounters != null) {
7933 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7934 mUserActivityCounters[i].detach();
7935 }
7936 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007937 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007938 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007939 mNetworkByteActivityCounters[i].detach();
7940 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007941 }
7942 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007943
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007944 if (mWifiControllerActivity != null) {
7945 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07007946 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007947
7948 if (mBluetoothControllerActivity != null) {
7949 mBluetoothControllerActivity.detach();
7950 }
7951
7952 if (mModemControllerActivity != null) {
7953 mModemControllerActivity.detach();
7954 }
7955
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007956 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007957
7958 mUserCpuTime.detach();
7959 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07007960
Sudheer Shankaaf857412017-07-21 00:14:24 -07007961 if (mCpuClusterSpeedTimesUs != null) {
7962 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007963 if (cpuSpeeds != null) {
7964 for (LongSamplingCounter c : cpuSpeeds) {
7965 if (c != null) {
7966 c.detach();
7967 }
7968 }
7969 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007970 }
7971 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007972
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007973 if (mCpuFreqTimeMs != null) {
7974 mCpuFreqTimeMs.detach();
7975 }
7976 if (mScreenOffCpuFreqTimeMs != null) {
7977 mScreenOffCpuFreqTimeMs.detach();
7978 }
Mike Ma3d422c32017-10-25 11:08:57 -07007979 mCpuActiveTimeMs.detach();
7980 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007981
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007982 if (mProcStateTimeMs != null) {
7983 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7984 if (counters != null) {
7985 counters.detach();
7986 }
7987 }
7988 }
7989 if (mProcStateScreenOffTimeMs != null) {
7990 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7991 if (counters != null) {
7992 counters.detach();
7993 }
7994 }
7995 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007996 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
7997 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007998 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007999
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008000 return !active;
8001 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008002
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008003 void writeJobCompletionsToParcelLocked(Parcel out) {
8004 int NJC = mJobCompletions.size();
8005 out.writeInt(NJC);
8006 for (int ijc=0; ijc<NJC; ijc++) {
8007 out.writeString(mJobCompletions.keyAt(ijc));
8008 SparseIntArray types = mJobCompletions.valueAt(ijc);
8009 int NT = types.size();
8010 out.writeInt(NT);
8011 for (int it=0; it<NT; it++) {
8012 out.writeInt(types.keyAt(it));
8013 out.writeInt(types.valueAt(it));
8014 }
8015 }
8016 }
8017
Bookatz867c0d72017-03-07 18:23:42 -08008018 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8019 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008020 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008021
Dianne Hackbornd953c532014-08-16 18:17:38 -07008022 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8023 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008024 out.writeInt(NW);
8025 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008026 out.writeString(wakeStats.keyAt(iw));
8027 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008028 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008029 }
8030
Bookatz2bffb5b2017-04-13 11:59:33 -07008031 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008032 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008033 out.writeInt(NS);
8034 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008035 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008036 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008037 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8038 }
8039
Bookatzaa4594a2017-03-24 12:39:56 -07008040 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008041 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008042 out.writeInt(NJ);
8043 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008044 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008045 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008046 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8047 }
8048
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008049 writeJobCompletionsToParcelLocked(out);
8050
Dianne Hackborn61659e52014-07-09 16:13:01 -07008051 int NSE = mSensorStats.size();
8052 out.writeInt(NSE);
8053 for (int ise=0; ise<NSE; ise++) {
8054 out.writeInt(mSensorStats.keyAt(ise));
8055 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008056 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 }
8058
Dianne Hackborn61659e52014-07-09 16:13:01 -07008059 int NP = mProcessStats.size();
8060 out.writeInt(NP);
8061 for (int ip=0; ip<NP; ip++) {
8062 out.writeString(mProcessStats.keyAt(ip));
8063 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 proc.writeToParcelLocked(out);
8065 }
8066
8067 out.writeInt(mPackageStats.size());
8068 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8069 out.writeString(pkgEntry.getKey());
8070 Uid.Pkg pkg = pkgEntry.getValue();
8071 pkg.writeToParcelLocked(out);
8072 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008073
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008074 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008075 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008076 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008077 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008078 out.writeInt(0);
8079 }
8080 if (mFullWifiLockTimer != null) {
8081 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008082 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008083 } else {
8084 out.writeInt(0);
8085 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008086 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008087 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008088 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008089 } else {
8090 out.writeInt(0);
8091 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008092 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8093 if (mWifiBatchedScanTimer[i] != null) {
8094 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008095 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008096 } else {
8097 out.writeInt(0);
8098 }
8099 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008100 if (mWifiMulticastTimer != null) {
8101 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008102 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008103 } else {
8104 out.writeInt(0);
8105 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008106
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008107 if (mAudioTurnedOnTimer != null) {
8108 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008109 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008110 } else {
8111 out.writeInt(0);
8112 }
8113 if (mVideoTurnedOnTimer != null) {
8114 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008115 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008116 } else {
8117 out.writeInt(0);
8118 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008119 if (mFlashlightTurnedOnTimer != null) {
8120 out.writeInt(1);
8121 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8122 } else {
8123 out.writeInt(0);
8124 }
8125 if (mCameraTurnedOnTimer != null) {
8126 out.writeInt(1);
8127 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8128 } else {
8129 out.writeInt(0);
8130 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008131 if (mForegroundActivityTimer != null) {
8132 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008133 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008134 } else {
8135 out.writeInt(0);
8136 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008137 if (mForegroundServiceTimer != null) {
8138 out.writeInt(1);
8139 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8140 } else {
8141 out.writeInt(0);
8142 }
Bookatzc8c44962017-05-11 12:12:54 -07008143 if (mAggregatedPartialWakelockTimer != null) {
8144 out.writeInt(1);
8145 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8146 } else {
8147 out.writeInt(0);
8148 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008149 if (mBluetoothScanTimer != null) {
8150 out.writeInt(1);
8151 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8152 } else {
8153 out.writeInt(0);
8154 }
Bookatzb1f04f32017-05-19 13:57:32 -07008155 if (mBluetoothUnoptimizedScanTimer != null) {
8156 out.writeInt(1);
8157 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8158 } else {
8159 out.writeInt(0);
8160 }
Bookatz956f36bf2017-04-28 09:48:17 -07008161 if (mBluetoothScanResultCounter != null) {
8162 out.writeInt(1);
8163 mBluetoothScanResultCounter.writeToParcel(out);
8164 } else {
8165 out.writeInt(0);
8166 }
Bookatzb1f04f32017-05-19 13:57:32 -07008167 if (mBluetoothScanResultBgCounter != null) {
8168 out.writeInt(1);
8169 mBluetoothScanResultBgCounter.writeToParcel(out);
8170 } else {
8171 out.writeInt(0);
8172 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008173 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8174 if (mProcessStateTimer[i] != null) {
8175 out.writeInt(1);
8176 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8177 } else {
8178 out.writeInt(0);
8179 }
8180 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008181 if (mVibratorOnTimer != null) {
8182 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008183 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008184 } else {
8185 out.writeInt(0);
8186 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008187 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008188 out.writeInt(1);
8189 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8190 mUserActivityCounters[i].writeToParcel(out);
8191 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008192 } else {
8193 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008194 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008195 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008196 out.writeInt(1);
8197 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008198 mNetworkByteActivityCounters[i].writeToParcel(out);
8199 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008200 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008201 mMobileRadioActiveTime.writeToParcel(out);
8202 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008203 } else {
8204 out.writeInt(0);
8205 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008206
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008207 if (mWifiControllerActivity != null) {
8208 out.writeInt(1);
8209 mWifiControllerActivity.writeToParcel(out, 0);
8210 } else {
8211 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008212 }
8213
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008214 if (mBluetoothControllerActivity != null) {
8215 out.writeInt(1);
8216 mBluetoothControllerActivity.writeToParcel(out, 0);
8217 } else {
8218 out.writeInt(0);
8219 }
8220
8221 if (mModemControllerActivity != null) {
8222 out.writeInt(1);
8223 mModemControllerActivity.writeToParcel(out, 0);
8224 } else {
8225 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008226 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008227
8228 mUserCpuTime.writeToParcel(out);
8229 mSystemCpuTime.writeToParcel(out);
8230
Sudheer Shankaaf857412017-07-21 00:14:24 -07008231 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008232 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008233 out.writeInt(mCpuClusterSpeedTimesUs.length);
8234 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008235 if (cpuSpeeds != null) {
8236 out.writeInt(1);
8237 out.writeInt(cpuSpeeds.length);
8238 for (LongSamplingCounter c : cpuSpeeds) {
8239 if (c != null) {
8240 out.writeInt(1);
8241 c.writeToParcel(out);
8242 } else {
8243 out.writeInt(0);
8244 }
8245 }
8246 } else {
8247 out.writeInt(0);
8248 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008249 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008250 } else {
8251 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008252 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008253
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008254 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8255 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008256
8257 mCpuActiveTimeMs.writeToParcel(out);
8258 mCpuClusterTimesMs.writeToParcel(out);
8259
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008260 if (mProcStateTimeMs != null) {
8261 out.writeInt(mProcStateTimeMs.length);
8262 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8263 LongSamplingCounterArray.writeToParcel(out, counters);
8264 }
8265 } else {
8266 out.writeInt(0);
8267 }
8268 if (mProcStateScreenOffTimeMs != null) {
8269 out.writeInt(mProcStateScreenOffTimeMs.length);
8270 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8271 LongSamplingCounterArray.writeToParcel(out, counters);
8272 }
8273 } else {
8274 out.writeInt(0);
8275 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008276
Adam Lesinski5f056f62016-07-14 16:56:08 -07008277 if (mMobileRadioApWakeupCount != null) {
8278 out.writeInt(1);
8279 mMobileRadioApWakeupCount.writeToParcel(out);
8280 } else {
8281 out.writeInt(0);
8282 }
8283
8284 if (mWifiRadioApWakeupCount != null) {
8285 out.writeInt(1);
8286 mWifiRadioApWakeupCount.writeToParcel(out);
8287 } else {
8288 out.writeInt(0);
8289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 }
8291
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008292 void readJobCompletionsFromParcelLocked(Parcel in) {
8293 int numJobCompletions = in.readInt();
8294 mJobCompletions.clear();
8295 for (int j = 0; j < numJobCompletions; j++) {
8296 String jobName = in.readString();
8297 int numTypes = in.readInt();
8298 if (numTypes > 0) {
8299 SparseIntArray types = new SparseIntArray();
8300 for (int k = 0; k < numTypes; k++) {
8301 int type = in.readInt();
8302 int count = in.readInt();
8303 types.put(type, count);
8304 }
8305 mJobCompletions.put(jobName, types);
8306 }
8307 }
8308 }
8309
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008310 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008311 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008312 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008314 int numWakelocks = in.readInt();
8315 mWakelockStats.clear();
8316 for (int j = 0; j < numWakelocks; j++) {
8317 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008318 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008319 wakelock.readFromParcelLocked(
8320 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008321 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008322 }
8323
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008324 int numSyncs = in.readInt();
8325 mSyncStats.clear();
8326 for (int j = 0; j < numSyncs; j++) {
8327 String syncName = in.readString();
8328 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008329 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8330 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008331 }
8332 }
8333
8334 int numJobs = in.readInt();
8335 mJobStats.clear();
8336 for (int j = 0; j < numJobs; j++) {
8337 String jobName = in.readString();
8338 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008339 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8340 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008341 }
8342 }
8343
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008344 readJobCompletionsFromParcelLocked(in);
8345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 int numSensors = in.readInt();
8347 mSensorStats.clear();
8348 for (int k = 0; k < numSensors; k++) {
8349 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008350 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008351 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8352 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008353 mSensorStats.put(sensorNumber, sensor);
8354 }
8355
8356 int numProcs = in.readInt();
8357 mProcessStats.clear();
8358 for (int k = 0; k < numProcs; k++) {
8359 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008360 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008361 proc.readFromParcelLocked(in);
8362 mProcessStats.put(processName, proc);
8363 }
8364
8365 int numPkgs = in.readInt();
8366 mPackageStats.clear();
8367 for (int l = 0; l < numPkgs; l++) {
8368 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008369 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008370 pkg.readFromParcelLocked(in);
8371 mPackageStats.put(packageName, pkg);
8372 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008373
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008374 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008375 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008376 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8377 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008378 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008379 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008380 }
8381 mFullWifiLockOut = false;
8382 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008383 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8384 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008385 } else {
8386 mFullWifiLockTimer = null;
8387 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008388 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008389 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008390 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8391 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8392 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008393 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008394 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008395 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008396 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8397 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8398 if (in.readInt() != 0) {
8399 makeWifiBatchedScanBin(i, in);
8400 } else {
8401 mWifiBatchedScanTimer[i] = null;
8402 }
8403 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008404 mWifiMulticastEnabled = false;
8405 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008406 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8407 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008408 } else {
8409 mWifiMulticastTimer = null;
8410 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008411 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008412 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8413 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008414 } else {
8415 mAudioTurnedOnTimer = null;
8416 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008417 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008418 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8419 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008420 } else {
8421 mVideoTurnedOnTimer = null;
8422 }
8423 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008424 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8425 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008426 } else {
8427 mFlashlightTurnedOnTimer = null;
8428 }
8429 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008430 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8431 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008432 } else {
8433 mCameraTurnedOnTimer = null;
8434 }
8435 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008436 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8437 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008438 } else {
8439 mForegroundActivityTimer = null;
8440 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008441 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008442 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8443 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8444 } else {
8445 mForegroundServiceTimer = null;
8446 }
8447 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008448 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8449 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8450 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8451 in);
8452 } else {
8453 mAggregatedPartialWakelockTimer = null;
8454 }
8455 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008456 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8457 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8458 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008459 } else {
8460 mBluetoothScanTimer = null;
8461 }
Bookatz956f36bf2017-04-28 09:48:17 -07008462 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008463 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8464 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8465 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8466 } else {
8467 mBluetoothUnoptimizedScanTimer = null;
8468 }
8469 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008470 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8471 } else {
8472 mBluetoothScanResultCounter = null;
8473 }
Bookatzb1f04f32017-05-19 13:57:32 -07008474 if (in.readInt() != 0) {
8475 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8476 } else {
8477 mBluetoothScanResultBgCounter = null;
8478 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008479 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008480 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8481 if (in.readInt() != 0) {
8482 makeProcessState(i, in);
8483 } else {
8484 mProcessStateTimer[i] = null;
8485 }
8486 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008487 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008488 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8489 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008490 } else {
8491 mVibratorOnTimer = null;
8492 }
8493 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008494 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8495 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008496 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008497 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008498 } else {
8499 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008500 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008501 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008502 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8503 mNetworkPacketActivityCounters
8504 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008505 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008506 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008507 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008508 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008509 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008510 }
Joe Onoratoabded112016-02-08 16:49:39 -08008511 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8512 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008513 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008514 mNetworkByteActivityCounters = null;
8515 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008516 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008517
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008518 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008519 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008520 NUM_WIFI_TX_LEVELS, in);
8521 } else {
8522 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008523 }
8524
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008525 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008526 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008527 NUM_BT_TX_LEVELS, in);
8528 } else {
8529 mBluetoothControllerActivity = null;
8530 }
8531
8532 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008533 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008534 ModemActivityInfo.TX_POWER_LEVELS, in);
8535 } else {
8536 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008537 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008538
Joe Onoratoabded112016-02-08 16:49:39 -08008539 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8540 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008541
Adam Lesinski6832f392015-09-05 18:05:40 -07008542 if (in.readInt() != 0) {
8543 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008544 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008545 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008546 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008547
Sudheer Shankaaf857412017-07-21 00:14:24 -07008548 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008549 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8550 if (in.readInt() != 0) {
8551 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008552 if (mBsi.mPowerProfile != null &&
8553 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008554 throw new ParcelFormatException("Incompatible number of cpu speeds");
8555 }
8556
8557 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008558 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008559 for (int speed = 0; speed < numSpeeds; speed++) {
8560 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008561 cpuSpeeds[speed] = new LongSamplingCounter(
8562 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008563 }
8564 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008565 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008566 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008567 }
8568 }
8569 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008570 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008571 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008572
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008573 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8574 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8575 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008576
Mike Ma3d422c32017-10-25 11:08:57 -07008577 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8578 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8579
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008580 int length = in.readInt();
8581 if (length == NUM_PROCESS_STATE) {
8582 mProcStateTimeMs = new LongSamplingCounterArray[length];
8583 for (int procState = 0; procState < length; ++procState) {
8584 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8585 in, mBsi.mOnBatteryTimeBase);
8586 }
8587 } else {
8588 mProcStateTimeMs = null;
8589 }
8590 length = in.readInt();
8591 if (length == NUM_PROCESS_STATE) {
8592 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8593 for (int procState = 0; procState < length; ++procState) {
8594 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8595 in, mBsi.mOnBatteryScreenOffTimeBase);
8596 }
8597 } else {
8598 mProcStateScreenOffTimeMs = null;
8599 }
8600
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008601 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008602 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8603 } else {
8604 mMobileRadioApWakeupCount = null;
8605 }
8606
8607 if (in.readInt() != 0) {
8608 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8609 } else {
8610 mWifiRadioApWakeupCount = null;
8611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 }
8613
8614 /**
8615 * The statistics associated with a particular wake lock.
8616 */
Joe Onoratoabded112016-02-08 16:49:39 -08008617 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8618 /**
8619 * BatteryStatsImpl that we are associated with.
8620 */
8621 protected BatteryStatsImpl mBsi;
8622
8623 /**
8624 * BatteryStatsImpl that we are associated with.
8625 */
8626 protected Uid mUid;
8627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628 /**
8629 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008630 * 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 -08008631 */
Bookatz5b5ec322017-05-26 09:40:38 -07008632 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008633
8634 /**
8635 * How long (in ms) this uid has been keeping the device fully awake.
8636 */
Evan Millarc64edde2009-04-18 12:26:32 -07008637 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008638
8639 /**
8640 * How long (in ms) this uid has had a window keeping the device awake.
8641 */
Evan Millarc64edde2009-04-18 12:26:32 -07008642 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643
8644 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008645 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008646 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008647 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008648
Joe Onoratoabded112016-02-08 16:49:39 -08008649 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8650 mBsi = bsi;
8651 mUid = uid;
8652 }
8653
Adam Lesinski9425fe22015-06-19 12:02:13 -07008654 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008655 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8656 * proper timer pool from the given BatteryStatsImpl object.
8657 *
8658 * @param in the Parcel to be read from.
8659 * return a new Timer, or null.
8660 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008661 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8662 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 if (in.readInt() == 0) {
8664 return null;
8665 }
8666
Joe Onoratoabded112016-02-08 16:49:39 -08008667 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 }
8669
Joe Onorato92fd23f2016-07-25 11:18:42 -07008670 /**
8671 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8672 * proper timer pool from the given BatteryStatsImpl object.
8673 *
8674 * @param in the Parcel to be read from.
8675 * return a new Timer, or null.
8676 */
Bookatz5b5ec322017-05-26 09:40:38 -07008677 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8678 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008679 if (in.readInt() == 0) {
8680 return null;
8681 }
8682
Bookatz5b5ec322017-05-26 09:40:38 -07008683 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008684 }
8685
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008686 boolean reset() {
8687 boolean wlactive = false;
8688 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008689 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008690 }
8691 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008692 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008693 }
8694 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008695 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008696 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008697 if (mTimerDraw != null) {
8698 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008699 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008700 if (!wlactive) {
8701 if (mTimerFull != null) {
8702 mTimerFull.detach();
8703 mTimerFull = null;
8704 }
8705 if (mTimerPartial != null) {
8706 mTimerPartial.detach();
8707 mTimerPartial = null;
8708 }
8709 if (mTimerWindow != null) {
8710 mTimerWindow.detach();
8711 mTimerWindow = null;
8712 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008713 if (mTimerDraw != null) {
8714 mTimerDraw.detach();
8715 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008716 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008717 }
8718 return !wlactive;
8719 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008720
Bookatz5b5ec322017-05-26 09:40:38 -07008721 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
8722 TimeBase screenOffBgTimeBase, Parcel in) {
8723 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
8724 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008725 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
8726 mBsi.mFullTimers, timeBase, in);
8727 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
8728 mBsi.mWindowTimers, timeBase, in);
8729 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
8730 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008731 }
8732
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008733 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
8734 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
8735 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
8736 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008737 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008738 }
8739
8740 @Override
8741 public Timer getWakeTime(int type) {
8742 switch (type) {
8743 case WAKE_TYPE_FULL: return mTimerFull;
8744 case WAKE_TYPE_PARTIAL: return mTimerPartial;
8745 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008746 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008747 default: throw new IllegalArgumentException("type = " + type);
8748 }
8749 }
8750 }
8751
Joe Onoratoabded112016-02-08 16:49:39 -08008752 public static class Sensor extends BatteryStats.Uid.Sensor {
8753 /**
8754 * BatteryStatsImpl that we are associated with.
8755 */
8756 protected BatteryStatsImpl mBsi;
8757
8758 /**
Bookatz867c0d72017-03-07 18:23:42 -08008759 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08008760 */
8761 protected Uid mUid;
8762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008763 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08008764 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008765
Joe Onoratoabded112016-02-08 16:49:39 -08008766 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
8767 mBsi = bsi;
8768 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769 mHandle = handle;
8770 }
8771
Bookatz867c0d72017-03-07 18:23:42 -08008772 private DualTimer readTimersFromParcel(
8773 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 if (in.readInt() == 0) {
8775 return null;
8776 }
8777
Joe Onoratoabded112016-02-08 16:49:39 -08008778 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07008780 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08008781 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782 }
Bookatz867c0d72017-03-07 18:23:42 -08008783 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008784 }
8785
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008786 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008787 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008788 mTimer = null;
8789 return true;
8790 }
8791 return false;
8792 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008793
Bookatz867c0d72017-03-07 18:23:42 -08008794 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
8795 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008796 }
8797
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008798 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07008799 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008800 }
8801
8802 @Override
8803 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07008804 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008805 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008806
8807 @Override
Bookatz867c0d72017-03-07 18:23:42 -08008808 public Timer getSensorBackgroundTime() {
8809 if (mTimer == null) {
8810 return null;
8811 }
8812 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008813 }
8814
8815 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008816 public int getHandle() {
8817 return mHandle;
8818 }
8819 }
8820
8821 /**
8822 * The statistics associated with a particular process.
8823 */
Joe Onoratoabded112016-02-08 16:49:39 -08008824 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
8825 /**
8826 * BatteryStatsImpl that we are associated with.
8827 */
8828 protected BatteryStatsImpl mBsi;
8829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008830 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008831 * The name of this process.
8832 */
8833 final String mName;
8834
8835 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08008836 * Remains true until removed from the stats.
8837 */
8838 boolean mActive = true;
8839
8840 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008841 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008842 */
8843 long mUserTime;
8844
8845 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008846 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008847 */
8848 long mSystemTime;
8849
8850 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008851 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008852 */
8853 long mForegroundTime;
8854
8855 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008856 * Number of times the process has been started.
8857 */
8858 int mStarts;
8859
8860 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008861 * Number of times the process has crashed.
8862 */
8863 int mNumCrashes;
8864
8865 /**
8866 * Number of times the process has had an ANR.
8867 */
8868 int mNumAnrs;
8869
8870 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008871 * The amount of user time loaded from a previous save.
8872 */
8873 long mLoadedUserTime;
8874
8875 /**
8876 * The amount of system time loaded from a previous save.
8877 */
8878 long mLoadedSystemTime;
8879
8880 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008881 * The amount of foreground time loaded from a previous save.
8882 */
8883 long mLoadedForegroundTime;
8884
8885 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008886 * The number of times the process has started from a previous save.
8887 */
8888 int mLoadedStarts;
8889
8890 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008891 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008893 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008894
8895 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008896 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008897 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008898 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008899
8900 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008901 * The amount of user time when last unplugged.
8902 */
8903 long mUnpluggedUserTime;
8904
8905 /**
8906 * The amount of system time when last unplugged.
8907 */
8908 long mUnpluggedSystemTime;
8909
8910 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008911 * The amount of foreground time since unplugged.
8912 */
8913 long mUnpluggedForegroundTime;
8914
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008915 /**
8916 * The number of times the process has started before unplugged.
8917 */
8918 int mUnpluggedStarts;
8919
Dianne Hackborn61659e52014-07-09 16:13:01 -07008920 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008921 * Number of times the process has crashed before unplugged.
8922 */
8923 int mUnpluggedNumCrashes;
8924
8925 /**
8926 * Number of times the process has had an ANR before unplugged.
8927 */
8928 int mUnpluggedNumAnrs;
8929
Dianne Hackborn287952c2010-09-22 22:34:31 -07008930 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008931
Joe Onoratoabded112016-02-08 16:49:39 -08008932 public Proc(BatteryStatsImpl bsi, String name) {
8933 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008934 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08008935 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07008937
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008938 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939 mUnpluggedUserTime = mUserTime;
8940 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008941 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008942 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008943 mUnpluggedNumCrashes = mNumCrashes;
8944 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 }
8946
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008947 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008948 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008949
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008950 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08008951 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08008952 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008953 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008954
Dianne Hackborn287952c2010-09-22 22:34:31 -07008955 public int countExcessivePowers() {
8956 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008957 }
8958
Dianne Hackborn287952c2010-09-22 22:34:31 -07008959 public ExcessivePower getExcessivePower(int i) {
8960 if (mExcessivePower != null) {
8961 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008962 }
8963 return null;
8964 }
8965
Dianne Hackborn287952c2010-09-22 22:34:31 -07008966 public void addExcessiveCpu(long overTime, long usedTime) {
8967 if (mExcessivePower == null) {
8968 mExcessivePower = new ArrayList<ExcessivePower>();
8969 }
8970 ExcessivePower ew = new ExcessivePower();
8971 ew.type = ExcessivePower.TYPE_CPU;
8972 ew.overTime = overTime;
8973 ew.usedTime = usedTime;
8974 mExcessivePower.add(ew);
8975 }
8976
8977 void writeExcessivePowerToParcelLocked(Parcel out) {
8978 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008979 out.writeInt(0);
8980 return;
8981 }
8982
Dianne Hackborn287952c2010-09-22 22:34:31 -07008983 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008984 out.writeInt(N);
8985 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008986 ExcessivePower ew = mExcessivePower.get(i);
8987 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008988 out.writeLong(ew.overTime);
8989 out.writeLong(ew.usedTime);
8990 }
8991 }
8992
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07008993 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008994 final int N = in.readInt();
8995 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008996 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07008997 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008998 }
8999
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009000 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009001 throw new ParcelFormatException(
9002 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009003 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009004
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009005 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009006 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009007 ExcessivePower ew = new ExcessivePower();
9008 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009009 ew.overTime = in.readLong();
9010 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009011 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009012 }
9013 }
9014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009015 void writeToParcelLocked(Parcel out) {
9016 out.writeLong(mUserTime);
9017 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009018 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009019 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009020 out.writeInt(mNumCrashes);
9021 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009022 out.writeLong(mLoadedUserTime);
9023 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009024 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009026 out.writeInt(mLoadedNumCrashes);
9027 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 out.writeLong(mUnpluggedUserTime);
9029 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009030 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009032 out.writeInt(mUnpluggedNumCrashes);
9033 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009034 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 }
9036
9037 void readFromParcelLocked(Parcel in) {
9038 mUserTime = in.readLong();
9039 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009040 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009041 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009042 mNumCrashes = in.readInt();
9043 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009044 mLoadedUserTime = in.readLong();
9045 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009046 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009047 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009048 mLoadedNumCrashes = in.readInt();
9049 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009050 mUnpluggedUserTime = in.readLong();
9051 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009052 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009053 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009054 mUnpluggedNumCrashes = in.readInt();
9055 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009056 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009057 }
9058
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009059 public void addCpuTimeLocked(int utime, int stime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009060 mUserTime += utime;
9061 mSystemTime += stime;
9062 }
9063
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009064 public void addForegroundTimeLocked(long ttime) {
9065 mForegroundTime += ttime;
9066 }
9067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009068 public void incStartsLocked() {
9069 mStarts++;
9070 }
9071
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009072 public void incNumCrashesLocked() {
9073 mNumCrashes++;
9074 }
9075
9076 public void incNumAnrsLocked() {
9077 mNumAnrs++;
9078 }
9079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009080 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009081 public boolean isActive() {
9082 return mActive;
9083 }
9084
9085 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009086 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009087 long val = mUserTime;
9088 if (which == STATS_CURRENT) {
9089 val -= mLoadedUserTime;
9090 } else if (which == STATS_SINCE_UNPLUGGED) {
9091 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 }
9093 return val;
9094 }
9095
9096 @Override
9097 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009098 long val = mSystemTime;
9099 if (which == STATS_CURRENT) {
9100 val -= mLoadedSystemTime;
9101 } else if (which == STATS_SINCE_UNPLUGGED) {
9102 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009103 }
9104 return val;
9105 }
9106
9107 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009108 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009109 long val = mForegroundTime;
9110 if (which == STATS_CURRENT) {
9111 val -= mLoadedForegroundTime;
9112 } else if (which == STATS_SINCE_UNPLUGGED) {
9113 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009114 }
9115 return val;
9116 }
9117
9118 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009119 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009120 int val = mStarts;
9121 if (which == STATS_CURRENT) {
9122 val -= mLoadedStarts;
9123 } else if (which == STATS_SINCE_UNPLUGGED) {
9124 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009125 }
9126 return val;
9127 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009128
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009129 @Override
9130 public int getNumCrashes(int which) {
9131 int val = mNumCrashes;
9132 if (which == STATS_CURRENT) {
9133 val -= mLoadedNumCrashes;
9134 } else if (which == STATS_SINCE_UNPLUGGED) {
9135 val -= mUnpluggedNumCrashes;
9136 }
9137 return val;
9138 }
9139
9140 @Override
9141 public int getNumAnrs(int which) {
9142 int val = mNumAnrs;
9143 if (which == STATS_CURRENT) {
9144 val -= mLoadedNumAnrs;
9145 } else if (which == STATS_SINCE_UNPLUGGED) {
9146 val -= mUnpluggedNumAnrs;
9147 }
9148 return val;
9149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009150 }
9151
9152 /**
9153 * The statistics associated with a particular package.
9154 */
Joe Onoratoabded112016-02-08 16:49:39 -08009155 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9156 /**
9157 * BatteryStatsImpl that we are associated with.
9158 */
9159 protected BatteryStatsImpl mBsi;
9160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009161 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009162 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009163 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009164 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009165 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009166
9167 /**
9168 * The statics we have collected for this package's services.
9169 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009170 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009171
Joe Onoratoabded112016-02-08 16:49:39 -08009172 public Pkg(BatteryStatsImpl bsi) {
9173 mBsi = bsi;
9174 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009175 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009176
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009177 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009178 }
9179
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009180 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009182
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009183 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009184 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009185 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009187 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009188 int numWA = in.readInt();
9189 mWakeupAlarms.clear();
9190 for (int i=0; i<numWA; i++) {
9191 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009192 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009194
9195 int numServs = in.readInt();
9196 mServiceStats.clear();
9197 for (int m = 0; m < numServs; m++) {
9198 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009199 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009200 mServiceStats.put(serviceName, serv);
9201
9202 serv.readFromParcelLocked(in);
9203 }
9204 }
9205
9206 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009207 int numWA = mWakeupAlarms.size();
9208 out.writeInt(numWA);
9209 for (int i=0; i<numWA; i++) {
9210 out.writeString(mWakeupAlarms.keyAt(i));
9211 mWakeupAlarms.valueAt(i).writeToParcel(out);
9212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009213
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009214 final int NS = mServiceStats.size();
9215 out.writeInt(NS);
9216 for (int i=0; i<NS; i++) {
9217 out.writeString(mServiceStats.keyAt(i));
9218 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009219 serv.writeToParcelLocked(out);
9220 }
9221 }
9222
9223 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009224 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9225 return mWakeupAlarms;
9226 }
9227
9228 public void noteWakeupAlarmLocked(String tag) {
9229 Counter c = mWakeupAlarms.get(tag);
9230 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009231 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009232 mWakeupAlarms.put(tag, c);
9233 }
9234 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009235 }
9236
9237 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009238 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9239 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009240 }
9241
9242 /**
9243 * The statistics associated with a particular service.
9244 */
Joe Onoratoabded112016-02-08 16:49:39 -08009245 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9246 /**
9247 * BatteryStatsImpl that we are associated with.
9248 */
9249 protected BatteryStatsImpl mBsi;
9250
9251 /**
9252 * The android package in which this service resides.
9253 */
9254 protected Pkg mPkg;
9255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009256 /**
9257 * Total time (ms in battery uptime) the service has been left started.
9258 */
Joe Onoratoabded112016-02-08 16:49:39 -08009259 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009260
9261 /**
9262 * If service has been started and not yet stopped, this is
9263 * when it was started.
9264 */
Joe Onoratoabded112016-02-08 16:49:39 -08009265 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266
9267 /**
9268 * True if we are currently running.
9269 */
Joe Onoratoabded112016-02-08 16:49:39 -08009270 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009271
9272 /**
9273 * Total number of times startService() has been called.
9274 */
Joe Onoratoabded112016-02-08 16:49:39 -08009275 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009276
9277 /**
9278 * Total time (ms in battery uptime) the service has been left launched.
9279 */
Joe Onoratoabded112016-02-08 16:49:39 -08009280 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009281
9282 /**
9283 * If service has been launched and not yet exited, this is
9284 * when it was launched (ms in battery uptime).
9285 */
Joe Onoratoabded112016-02-08 16:49:39 -08009286 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009287
9288 /**
9289 * True if we are currently launched.
9290 */
Joe Onoratoabded112016-02-08 16:49:39 -08009291 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009292
9293 /**
9294 * Total number times the service has been launched.
9295 */
Joe Onoratoabded112016-02-08 16:49:39 -08009296 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297
9298 /**
9299 * The amount of time spent started loaded from a previous save
9300 * (ms in battery uptime).
9301 */
Joe Onoratoabded112016-02-08 16:49:39 -08009302 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303
9304 /**
9305 * The number of starts loaded from a previous save.
9306 */
Joe Onoratoabded112016-02-08 16:49:39 -08009307 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009308
9309 /**
9310 * The number of launches loaded from a previous save.
9311 */
Joe Onoratoabded112016-02-08 16:49:39 -08009312 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009313
9314 /**
9315 * The amount of time spent started as of the last run (ms
9316 * in battery uptime).
9317 */
Joe Onoratoabded112016-02-08 16:49:39 -08009318 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009319
9320 /**
9321 * The number of starts as of the last run.
9322 */
Joe Onoratoabded112016-02-08 16:49:39 -08009323 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009324
9325 /**
9326 * The number of launches as of the last run.
9327 */
Joe Onoratoabded112016-02-08 16:49:39 -08009328 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009329
9330 /**
9331 * The amount of time spent started when last unplugged (ms
9332 * in battery uptime).
9333 */
Joe Onoratoabded112016-02-08 16:49:39 -08009334 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009335
9336 /**
9337 * The number of starts when last unplugged.
9338 */
Joe Onoratoabded112016-02-08 16:49:39 -08009339 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009340
9341 /**
9342 * The number of launches when last unplugged.
9343 */
Joe Onoratoabded112016-02-08 16:49:39 -08009344 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009345
Joe Onoratoabded112016-02-08 16:49:39 -08009346 /**
9347 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9348 */
9349 public Serv(BatteryStatsImpl bsi) {
9350 mBsi = bsi;
9351 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009353
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009354 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9355 long baseRealtime) {
9356 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009357 mUnpluggedStarts = mStarts;
9358 mUnpluggedLaunches = mLaunches;
9359 }
9360
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009361 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9362 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009363 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009364
Joe Onoratoabded112016-02-08 16:49:39 -08009365 /**
9366 * Remove this Serv as a listener from the time base.
9367 */
9368 public void detach() {
9369 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009370 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009371
Joe Onoratoabded112016-02-08 16:49:39 -08009372 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009373 mStartTime = in.readLong();
9374 mRunningSince = in.readLong();
9375 mRunning = in.readInt() != 0;
9376 mStarts = in.readInt();
9377 mLaunchedTime = in.readLong();
9378 mLaunchedSince = in.readLong();
9379 mLaunched = in.readInt() != 0;
9380 mLaunches = in.readInt();
9381 mLoadedStartTime = in.readLong();
9382 mLoadedStarts = in.readInt();
9383 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009384 mLastStartTime = 0;
9385 mLastStarts = 0;
9386 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009387 mUnpluggedStartTime = in.readLong();
9388 mUnpluggedStarts = in.readInt();
9389 mUnpluggedLaunches = in.readInt();
9390 }
9391
Joe Onoratoabded112016-02-08 16:49:39 -08009392 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009393 out.writeLong(mStartTime);
9394 out.writeLong(mRunningSince);
9395 out.writeInt(mRunning ? 1 : 0);
9396 out.writeInt(mStarts);
9397 out.writeLong(mLaunchedTime);
9398 out.writeLong(mLaunchedSince);
9399 out.writeInt(mLaunched ? 1 : 0);
9400 out.writeInt(mLaunches);
9401 out.writeLong(mLoadedStartTime);
9402 out.writeInt(mLoadedStarts);
9403 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009404 out.writeLong(mUnpluggedStartTime);
9405 out.writeInt(mUnpluggedStarts);
9406 out.writeInt(mUnpluggedLaunches);
9407 }
9408
Joe Onoratoabded112016-02-08 16:49:39 -08009409 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009410 if (!mLaunched) return mLaunchedTime;
9411 return mLaunchedTime + batteryUptime - mLaunchedSince;
9412 }
9413
Joe Onoratoabded112016-02-08 16:49:39 -08009414 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009415 if (!mRunning) return mStartTime;
9416 return mStartTime + batteryUptime - mRunningSince;
9417 }
9418
9419 public void startLaunchedLocked() {
9420 if (!mLaunched) {
9421 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009422 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423 mLaunched = true;
9424 }
9425 }
9426
9427 public void stopLaunchedLocked() {
9428 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009429 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009430 if (time > 0) {
9431 mLaunchedTime += time;
9432 } else {
9433 mLaunches--;
9434 }
9435 mLaunched = false;
9436 }
9437 }
9438
9439 public void startRunningLocked() {
9440 if (!mRunning) {
9441 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009442 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009443 mRunning = true;
9444 }
9445 }
9446
9447 public void stopRunningLocked() {
9448 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009449 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009450 if (time > 0) {
9451 mStartTime += time;
9452 } else {
9453 mStarts--;
9454 }
9455 mRunning = false;
9456 }
9457 }
9458
9459 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009460 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009461 }
9462
9463 @Override
9464 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009465 int val = mLaunches;
9466 if (which == STATS_CURRENT) {
9467 val -= mLoadedLaunches;
9468 } else if (which == STATS_SINCE_UNPLUGGED) {
9469 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009471 return val;
9472 }
9473
9474 @Override
9475 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009476 long val = getStartTimeToNowLocked(now);
9477 if (which == STATS_CURRENT) {
9478 val -= mLoadedStartTime;
9479 } else if (which == STATS_SINCE_UNPLUGGED) {
9480 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009482 return val;
9483 }
9484
9485 @Override
9486 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009487 int val = mStarts;
9488 if (which == STATS_CURRENT) {
9489 val -= mLoadedStarts;
9490 } else if (which == STATS_SINCE_UNPLUGGED) {
9491 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009492 }
9493
9494 return val;
9495 }
9496 }
9497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009498 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009499 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009500 }
9501 }
9502
9503 /**
9504 * Retrieve the statistics object for a particular process, creating
9505 * if needed.
9506 */
9507 public Proc getProcessStatsLocked(String name) {
9508 Proc ps = mProcessStats.get(name);
9509 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009510 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009511 mProcessStats.put(name, ps);
9512 }
9513
9514 return ps;
9515 }
9516
Dianne Hackborna8d10942015-11-19 17:55:19 -08009517 public void updateUidProcessStateLocked(int procState) {
9518 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009519 // Make special note of Foreground Services
9520 final boolean userAwareService =
9521 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009522 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009523
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009524 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9525 return;
9526 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009527
Bookatz867c0d72017-03-07 18:23:42 -08009528 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009529 if (mProcessState != uidRunningState) {
9530 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009531
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009532 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9533 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009534
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009535 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009536 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009537 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9538 mBsi.mOnBatteryTimeBase.isRunning(),
9539 mBsi.mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009540 }
9541 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9542 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9543 mBsi.mPendingUids.put(mUid, mProcessState);
9544 }
9545 } else {
9546 mBsi.mPendingUids.clear();
9547 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009548 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009549 mProcessState = uidRunningState;
9550 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9551 if (mProcessStateTimer[uidRunningState] == null) {
9552 makeProcessState(uidRunningState, null);
9553 }
9554 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9555 }
9556
9557 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9558 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009559 }
Bookatz867c0d72017-03-07 18:23:42 -08009560
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009561 if (userAwareService != mInForegroundService) {
9562 if (userAwareService) {
9563 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9564 } else {
9565 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9566 }
9567 mInForegroundService = userAwareService;
9568 }
Bookatz867c0d72017-03-07 18:23:42 -08009569 }
9570
Bookatzc8c44962017-05-11 12:12:54 -07009571 /** Whether to consider Uid to be in the background for background timebase purposes. */
9572 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009573 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9574 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009575 return mProcessState >= PROCESS_STATE_BACKGROUND;
9576 }
9577
9578 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9579 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9580 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9581 }
9582
9583 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9584 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9585 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009586 }
9587
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009588 public SparseArray<? extends Pid> getPidStats() {
9589 return mPids;
9590 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009591
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009592 public Pid getPidStatsLocked(int pid) {
9593 Pid p = mPids.get(pid);
9594 if (p == null) {
9595 p = new Pid();
9596 mPids.put(pid, p);
9597 }
9598 return p;
9599 }
9600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009601 /**
9602 * Retrieve the statistics object for a particular service, creating
9603 * if needed.
9604 */
9605 public Pkg getPackageStatsLocked(String name) {
9606 Pkg ps = mPackageStats.get(name);
9607 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009608 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009609 mPackageStats.put(name, ps);
9610 }
9611
9612 return ps;
9613 }
9614
9615 /**
9616 * Retrieve the statistics object for a particular service, creating
9617 * if needed.
9618 */
9619 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9620 Pkg ps = getPackageStatsLocked(pkg);
9621 Pkg.Serv ss = ps.mServiceStats.get(serv);
9622 if (ss == null) {
9623 ss = ps.newServiceStatsLocked();
9624 ps.mServiceStats.put(serv, ss);
9625 }
9626
9627 return ss;
9628 }
9629
Dianne Hackbornd953c532014-08-16 18:17:38 -07009630 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009631 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009632 timer.readSummaryFromParcelLocked(in);
9633 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009634 }
9635
Dianne Hackbornd953c532014-08-16 18:17:38 -07009636 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009637 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009638 timer.readSummaryFromParcelLocked(in);
9639 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009640 }
9641
Dianne Hackbornd953c532014-08-16 18:17:38 -07009642 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009643 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009644 mWakelockStats.add(wlName, wl);
9645 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009646 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009647 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009648 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009649 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009650 }
9651 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009652 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009653 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009654 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009655 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009657 }
9658
Bookatz867c0d72017-03-07 18:23:42 -08009659 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009660 Sensor se = mSensorStats.get(sensor);
9661 if (se == null) {
9662 if (!create) {
9663 return null;
9664 }
Joe Onoratoabded112016-02-08 16:49:39 -08009665 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009666 mSensorStats.put(sensor, se);
9667 }
Bookatz867c0d72017-03-07 18:23:42 -08009668 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009669 if (t != null) {
9670 return t;
9671 }
Joe Onoratoabded112016-02-08 16:49:39 -08009672 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009673 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009674 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009675 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009676 }
Bookatz867c0d72017-03-07 18:23:42 -08009677 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9678 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 se.mTimer = t;
9680 return t;
9681 }
9682
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009683 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009684 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009685 if (t != null) {
9686 t.startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08009687 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name, 1);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009688 }
9689 }
9690
9691 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009692 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009693 if (t != null) {
9694 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009695 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08009696 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07009697 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009698 }
9699 }
9700
9701 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009702 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009703 if (t != null) {
9704 t.startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08009705 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
9706 name, 1);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009707 }
9708 }
9709
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009710 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07009711 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009712 if (t != null) {
9713 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009714 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08009715 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
9716 name, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07009717 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009718 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009719 if (mBsi.mOnBatteryTimeBase.isRunning()) {
9720 SparseIntArray types = mJobCompletions.get(name);
9721 if (types == null) {
9722 types = new SparseIntArray();
9723 mJobCompletions.put(name, types);
9724 }
9725 int last = types.get(stopReason, 0);
9726 types.put(stopReason, last + 1);
9727 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009728 }
9729
Bookatz5b5ec322017-05-26 09:40:38 -07009730 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
9731 if (wl == null) {
9732 return null;
9733 }
9734 switch (type) {
9735 case WAKE_TYPE_PARTIAL: {
9736 DualTimer t = wl.mTimerPartial;
9737 if (t == null) {
9738 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
9739 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
9740 mOnBatteryScreenOffBackgroundTimeBase);
9741 wl.mTimerPartial = t;
9742 }
9743 return t;
9744 }
9745 case WAKE_TYPE_FULL: {
9746 StopwatchTimer t = wl.mTimerFull;
9747 if (t == null) {
9748 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
9749 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
9750 wl.mTimerFull = t;
9751 }
9752 return t;
9753 }
9754 case WAKE_TYPE_WINDOW: {
9755 StopwatchTimer t = wl.mTimerWindow;
9756 if (t == null) {
9757 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
9758 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
9759 wl.mTimerWindow = t;
9760 }
9761 return t;
9762 }
9763 case WAKE_TYPE_DRAW: {
9764 StopwatchTimer t = wl.mTimerDraw;
9765 if (t == null) {
9766 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
9767 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
9768 wl.mTimerDraw = t;
9769 }
9770 return t;
9771 }
9772 default:
9773 throw new IllegalArgumentException("type=" + type);
9774 }
9775 }
9776
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009777 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009778 Wakelock wl = mWakelockStats.startObject(name);
9779 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07009780 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009781 }
Bookatzc8c44962017-05-11 12:12:54 -07009782 if (type == WAKE_TYPE_PARTIAL) {
9783 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
9784 if (pid >= 0) {
9785 Pid p = getPidStatsLocked(pid);
9786 if (p.mWakeNesting++ == 0) {
9787 p.mWakeStartMs = elapsedRealtimeMs;
9788 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -07009789 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009791 }
9792
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009793 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009794 Wakelock wl = mWakelockStats.stopObject(name);
9795 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -07009796 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
9797 wlt.stopRunningLocked(elapsedRealtimeMs);
9798 if (!wlt.isRunningLocked()) { // only tell statsd if truly stopped
Bookatzd6746242017-10-24 18:39:35 -07009799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009800 }
Bookatzc8c44962017-05-11 12:12:54 -07009801 if (type == WAKE_TYPE_PARTIAL) {
9802 if (mAggregatedPartialWakelockTimer != null) {
9803 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
9804 }
9805 if (pid >= 0) {
9806 Pid p = mPids.get(pid);
9807 if (p != null && p.mWakeNesting > 0) {
9808 if (p.mWakeNesting-- == 1) {
9809 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
9810 p.mWakeStartMs = 0;
9811 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08009812 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009813 }
9814 }
9815 }
9816
Dianne Hackborn287952c2010-09-22 22:34:31 -07009817 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
9818 Proc p = getProcessStatsLocked(proc);
9819 if (p != null) {
9820 p.addExcessiveCpu(overTime, usedTime);
9821 }
9822 }
9823
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009824 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009825 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -08009826 t.startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009827 if (sensor == Sensor.GPS) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08009828 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, getUid(), null, 1);
Bookatzc1a050a2017-10-10 15:49:28 -07009829 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08009830 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null, sensor,
9831 1);
Bookatzc1a050a2017-10-10 15:49:28 -07009832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009833 }
9834
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009835 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009836 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -08009837 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009838 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009839 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009840 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Bookatzc1a050a2017-10-10 15:49:28 -07009841 if (sensor == Sensor.GPS) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08009842 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, getUid(), null,
9843 0);
Bookatzc1a050a2017-10-10 15:49:28 -07009844 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08009845 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null,
9846 sensor, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07009847 }
9848 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009850 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009851
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009852 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009853 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009854 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009855
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009856 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009857 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009858 }
9859
9860 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009861 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009862 }
9863 }
9864
Sudheer Shanka9b735c52017-05-09 18:26:18 -07009865 public long[] getCpuFreqs() {
9866 return mCpuFreqs;
9867 }
9868
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009869 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
9870 UserInfoProvider userInfoProvider) {
9871 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009872 }
9873
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009874 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
9875 PlatformIdleStateCallback cb,
9876 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -08009877 init(clocks);
9878
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009879 if (systemDir != null) {
9880 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
9881 new File(systemDir, "batterystats.bin.tmp"));
9882 } else {
9883 mFile = null;
9884 }
9885 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009886 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -08009887 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009888 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009889 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -08009890 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -07009891 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07009892 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009893 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009894 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009895 }
Joe Onoratoabded112016-02-08 16:49:39 -08009896 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
9897 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
9898 mOnBatteryTimeBase);
9899 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
9900 mOnBatteryTimeBase);
9901 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
9902 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
9903 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
9904 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
9905 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
9906 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
9907 mOnBatteryTimeBase);
9908 }
9909 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
9910 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009911 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009912 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009913 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009914 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009915 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009916 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
9917 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009918 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009919 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
9920 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
9921 NUM_BT_TX_LEVELS);
9922 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
9923 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -08009924 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
9925 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
9926 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009927 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009928 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
9929 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08009930 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
9931 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08009932 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
9933 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08009934 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009935 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -07009936 mOnBatteryTimeBase);
9937 }
Joe Onoratoabded112016-02-08 16:49:39 -08009938 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9939 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
9940 mOnBatteryTimeBase);
9941 }
9942 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9943 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
9944 mOnBatteryTimeBase);
9945 }
Siddharth Rayb50a6842017-12-14 15:15:28 -08009946 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08009947 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
9948 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
9949 mOnBatteryTimeBase);
9950 }
Joe Onoratoabded112016-02-08 16:49:39 -08009951 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
9952 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
9953 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
9954 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
9955 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009956 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -07009957 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -08009958 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
9959 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009960 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009961 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009962 long uptime = mClocks.uptimeMillis() * 1000;
9963 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009964 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009965 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -07009966 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009967 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009968 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -07009969 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009970 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009971 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009972 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009973 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009974 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009975 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009976 }
9977
9978 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -08009979 this(new SystemClocks(), p);
9980 }
9981
9982 public BatteryStatsImpl(Clocks clocks, Parcel p) {
9983 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07009984 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009985 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009986 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07009987 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009988 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009989 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009990 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009991 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009992 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009993 }
9994
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009995 public void setPowerProfileLocked(PowerProfile profile) {
9996 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -07009997
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009998 // We need to initialize the KernelCpuSpeedReaders to read from
9999 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10000 // information.
10001 final int numClusters = mPowerProfile.getNumCpuClusters();
10002 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10003 int firstCpuOfCluster = 0;
10004 for (int i = 0; i < numClusters; i++) {
10005 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10006 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10007 numSpeedSteps);
10008 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10009 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010010
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010011 if (mEstimatedBatteryCapacity == -1) {
10012 // Initialize the estimated battery capacity to a known preset one.
10013 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010014 }
10015 }
10016
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010017 public void setCallback(BatteryCallback cb) {
10018 mCallback = cb;
10019 }
10020
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010021 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010022 if (mPhoneSignalScanningTimer != null) {
10023 mPhoneSignalScanningTimer.setTimeout(timeout);
10024 }
10025 }
10026
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010027 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10028 mExternalSync = sync;
10029 }
10030
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010031 public void updateDailyDeadlineLocked() {
10032 // Get the current time.
10033 long currentTime = mDailyStartTime = System.currentTimeMillis();
10034 Calendar calDeadline = Calendar.getInstance();
10035 calDeadline.setTimeInMillis(currentTime);
10036
10037 // Move time up to the next day, ranging from 1am to 3pm.
10038 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10039 calDeadline.set(Calendar.MILLISECOND, 0);
10040 calDeadline.set(Calendar.SECOND, 0);
10041 calDeadline.set(Calendar.MINUTE, 0);
10042 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10043 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10044 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10045 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10046 }
10047
10048 public void recordDailyStatsIfNeededLocked(boolean settled) {
10049 long currentTime = System.currentTimeMillis();
10050 if (currentTime >= mNextMaxDailyDeadline) {
10051 recordDailyStatsLocked();
10052 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10053 recordDailyStatsLocked();
10054 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10055 recordDailyStatsLocked();
10056 }
10057 }
10058
10059 public void recordDailyStatsLocked() {
10060 DailyItem item = new DailyItem();
10061 item.mStartTime = mDailyStartTime;
10062 item.mEndTime = System.currentTimeMillis();
10063 boolean hasData = false;
10064 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10065 hasData = true;
10066 item.mDischargeSteps = new LevelStepTracker(
10067 mDailyDischargeStepTracker.mNumStepDurations,
10068 mDailyDischargeStepTracker.mStepDurations);
10069 }
10070 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10071 hasData = true;
10072 item.mChargeSteps = new LevelStepTracker(
10073 mDailyChargeStepTracker.mNumStepDurations,
10074 mDailyChargeStepTracker.mStepDurations);
10075 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010076 if (mDailyPackageChanges != null) {
10077 hasData = true;
10078 item.mPackageChanges = mDailyPackageChanges;
10079 mDailyPackageChanges = null;
10080 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010081 mDailyDischargeStepTracker.init();
10082 mDailyChargeStepTracker.init();
10083 updateDailyDeadlineLocked();
10084
10085 if (hasData) {
10086 mDailyItems.add(item);
10087 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10088 mDailyItems.remove(0);
10089 }
10090 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10091 try {
10092 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010093 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010094 writeDailyItemsLocked(out);
10095 BackgroundThread.getHandler().post(new Runnable() {
10096 @Override
10097 public void run() {
10098 synchronized (mCheckinFile) {
10099 FileOutputStream stream = null;
10100 try {
10101 stream = mDailyFile.startWrite();
10102 memStream.writeTo(stream);
10103 stream.flush();
10104 FileUtils.sync(stream);
10105 stream.close();
10106 mDailyFile.finishWrite(stream);
10107 } catch (IOException e) {
10108 Slog.w("BatteryStats",
10109 "Error writing battery daily items", e);
10110 mDailyFile.failWrite(stream);
10111 }
10112 }
10113 }
10114 });
10115 } catch (IOException e) {
10116 }
10117 }
10118 }
10119
10120 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10121 StringBuilder sb = new StringBuilder(64);
10122 out.startDocument(null, true);
10123 out.startTag(null, "daily-items");
10124 for (int i=0; i<mDailyItems.size(); i++) {
10125 final DailyItem dit = mDailyItems.get(i);
10126 out.startTag(null, "item");
10127 out.attribute(null, "start", Long.toString(dit.mStartTime));
10128 out.attribute(null, "end", Long.toString(dit.mEndTime));
10129 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10130 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010131 if (dit.mPackageChanges != null) {
10132 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10133 PackageChange pc = dit.mPackageChanges.get(j);
10134 if (pc.mUpdate) {
10135 out.startTag(null, "upd");
10136 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010137 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010138 out.endTag(null, "upd");
10139 } else {
10140 out.startTag(null, "rem");
10141 out.attribute(null, "pkg", pc.mPackageName);
10142 out.endTag(null, "rem");
10143 }
10144 }
10145 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010146 out.endTag(null, "item");
10147 }
10148 out.endTag(null, "daily-items");
10149 out.endDocument();
10150 }
10151
10152 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10153 StringBuilder tmpBuilder) throws IOException {
10154 if (steps != null) {
10155 out.startTag(null, tag);
10156 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10157 for (int i=0; i<steps.mNumStepDurations; i++) {
10158 out.startTag(null, "s");
10159 tmpBuilder.setLength(0);
10160 steps.encodeEntryAt(i, tmpBuilder);
10161 out.attribute(null, "v", tmpBuilder.toString());
10162 out.endTag(null, "s");
10163 }
10164 out.endTag(null, tag);
10165 }
10166 }
10167
10168 public void readDailyStatsLocked() {
10169 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10170 mDailyItems.clear();
10171 FileInputStream stream;
10172 try {
10173 stream = mDailyFile.openRead();
10174 } catch (FileNotFoundException e) {
10175 return;
10176 }
10177 try {
10178 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010179 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010180 readDailyItemsLocked(parser);
10181 } catch (XmlPullParserException e) {
10182 } finally {
10183 try {
10184 stream.close();
10185 } catch (IOException e) {
10186 }
10187 }
10188 }
10189
10190 private void readDailyItemsLocked(XmlPullParser parser) {
10191 try {
10192 int type;
10193 while ((type = parser.next()) != XmlPullParser.START_TAG
10194 && type != XmlPullParser.END_DOCUMENT) {
10195 ;
10196 }
10197
10198 if (type != XmlPullParser.START_TAG) {
10199 throw new IllegalStateException("no start tag found");
10200 }
10201
10202 int outerDepth = parser.getDepth();
10203 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10204 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10205 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10206 continue;
10207 }
10208
10209 String tagName = parser.getName();
10210 if (tagName.equals("item")) {
10211 readDailyItemTagLocked(parser);
10212 } else {
10213 Slog.w(TAG, "Unknown element under <daily-items>: "
10214 + parser.getName());
10215 XmlUtils.skipCurrentTag(parser);
10216 }
10217 }
10218
10219 } catch (IllegalStateException e) {
10220 Slog.w(TAG, "Failed parsing daily " + e);
10221 } catch (NullPointerException e) {
10222 Slog.w(TAG, "Failed parsing daily " + e);
10223 } catch (NumberFormatException e) {
10224 Slog.w(TAG, "Failed parsing daily " + e);
10225 } catch (XmlPullParserException e) {
10226 Slog.w(TAG, "Failed parsing daily " + e);
10227 } catch (IOException e) {
10228 Slog.w(TAG, "Failed parsing daily " + e);
10229 } catch (IndexOutOfBoundsException e) {
10230 Slog.w(TAG, "Failed parsing daily " + e);
10231 }
10232 }
10233
10234 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10235 XmlPullParserException, IOException {
10236 DailyItem dit = new DailyItem();
10237 String attr = parser.getAttributeValue(null, "start");
10238 if (attr != null) {
10239 dit.mStartTime = Long.parseLong(attr);
10240 }
10241 attr = parser.getAttributeValue(null, "end");
10242 if (attr != null) {
10243 dit.mEndTime = Long.parseLong(attr);
10244 }
10245 int outerDepth = parser.getDepth();
10246 int type;
10247 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10248 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10249 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10250 continue;
10251 }
10252
10253 String tagName = parser.getName();
10254 if (tagName.equals("dis")) {
10255 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10256 } else if (tagName.equals("chg")) {
10257 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010258 } else if (tagName.equals("upd")) {
10259 if (dit.mPackageChanges == null) {
10260 dit.mPackageChanges = new ArrayList<>();
10261 }
10262 PackageChange pc = new PackageChange();
10263 pc.mUpdate = true;
10264 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10265 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010266 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010267 dit.mPackageChanges.add(pc);
10268 XmlUtils.skipCurrentTag(parser);
10269 } else if (tagName.equals("rem")) {
10270 if (dit.mPackageChanges == null) {
10271 dit.mPackageChanges = new ArrayList<>();
10272 }
10273 PackageChange pc = new PackageChange();
10274 pc.mUpdate = false;
10275 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10276 dit.mPackageChanges.add(pc);
10277 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010278 } else {
10279 Slog.w(TAG, "Unknown element under <item>: "
10280 + parser.getName());
10281 XmlUtils.skipCurrentTag(parser);
10282 }
10283 }
10284 mDailyItems.add(dit);
10285 }
10286
10287 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10288 String tag)
10289 throws NumberFormatException, XmlPullParserException, IOException {
10290 final String numAttr = parser.getAttributeValue(null, "n");
10291 if (numAttr == null) {
10292 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10293 XmlUtils.skipCurrentTag(parser);
10294 return;
10295 }
10296 final int num = Integer.parseInt(numAttr);
10297 LevelStepTracker steps = new LevelStepTracker(num);
10298 if (isCharge) {
10299 dit.mChargeSteps = steps;
10300 } else {
10301 dit.mDischargeSteps = steps;
10302 }
10303 int i = 0;
10304 int outerDepth = parser.getDepth();
10305 int type;
10306 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10307 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10308 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10309 continue;
10310 }
10311
10312 String tagName = parser.getName();
10313 if ("s".equals(tagName)) {
10314 if (i < num) {
10315 String valueAttr = parser.getAttributeValue(null, "v");
10316 if (valueAttr != null) {
10317 steps.decodeEntryAt(i, valueAttr);
10318 i++;
10319 }
10320 }
10321 } else {
10322 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10323 + parser.getName());
10324 XmlUtils.skipCurrentTag(parser);
10325 }
10326 }
10327 steps.mNumStepDurations = i;
10328 }
10329
10330 @Override
10331 public DailyItem getDailyItemLocked(int daysAgo) {
10332 int index = mDailyItems.size()-1-daysAgo;
10333 return index >= 0 ? mDailyItems.get(index) : null;
10334 }
10335
10336 @Override
10337 public long getCurrentDailyStartTime() {
10338 return mDailyStartTime;
10339 }
10340
10341 @Override
10342 public long getNextMinDailyDeadline() {
10343 return mNextMinDailyDeadline;
10344 }
10345
10346 @Override
10347 public long getNextMaxDailyDeadline() {
10348 return mNextMaxDailyDeadline;
10349 }
10350
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010351 @Override
10352 public boolean startIteratingOldHistoryLocked() {
10353 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10354 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010355 if ((mHistoryIterator = mHistory) == null) {
10356 return false;
10357 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010358 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010359 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010360 mReadOverflow = false;
10361 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010362 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010363 }
10364
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010365 @Override
10366 public boolean getNextOldHistoryLocked(HistoryItem out) {
10367 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10368 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010369 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010370 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010371 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010372 HistoryItem cur = mHistoryIterator;
10373 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010374 if (!mReadOverflow && !end) {
10375 Slog.w(TAG, "Old history ends before new history!");
10376 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010377 return false;
10378 }
10379 out.setTo(cur);
10380 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010381 if (!mReadOverflow) {
10382 if (end) {
10383 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010384 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010385 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010386 pw.println("Histories differ!");
10387 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010388 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010389 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010390 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10391 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010392 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010393 }
10394 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010395 return true;
10396 }
10397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010398 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010399 public void finishIteratingOldHistoryLocked() {
10400 mIteratingHistory = false;
10401 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010402 mHistoryIterator = null;
10403 }
10404
10405 public int getHistoryTotalSize() {
10406 return MAX_HISTORY_BUFFER;
10407 }
10408
10409 public int getHistoryUsedSize() {
10410 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010411 }
10412
10413 @Override
10414 public boolean startIteratingHistoryLocked() {
10415 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10416 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010417 if (mHistoryBuffer.dataSize() <= 0) {
10418 return false;
10419 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010420 mHistoryBuffer.setDataPosition(0);
10421 mReadOverflow = false;
10422 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010423 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10424 mReadHistoryUids = new int[mHistoryTagPool.size()];
10425 mReadHistoryChars = 0;
10426 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10427 final HistoryTag tag = ent.getKey();
10428 final int idx = ent.getValue();
10429 mReadHistoryStrings[idx] = tag.string;
10430 mReadHistoryUids[idx] = tag.uid;
10431 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010432 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010433 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010434 }
10435
10436 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010437 public int getHistoryStringPoolSize() {
10438 return mReadHistoryStrings.length;
10439 }
10440
10441 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010442 public int getHistoryStringPoolBytes() {
10443 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10444 // Each string character is 2 bytes.
10445 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10446 }
10447
10448 @Override
10449 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010450 return mReadHistoryStrings[index];
10451 }
10452
10453 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010454 public int getHistoryTagPoolUid(int index) {
10455 return mReadHistoryUids[index];
10456 }
10457
10458 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010459 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010460 final int pos = mHistoryBuffer.dataPosition();
10461 if (pos == 0) {
10462 out.clear();
10463 }
10464 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010465 if (end) {
10466 return false;
10467 }
10468
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010469 final long lastRealtime = out.time;
10470 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010471 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010472 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10473 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010474 out.currentTime = lastWalltime + (out.time - lastRealtime);
10475 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010476 return true;
10477 }
10478
10479 @Override
10480 public void finishIteratingHistoryLocked() {
10481 mIteratingHistory = false;
10482 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010483 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010484 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010485
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010486 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010487 public long getHistoryBaseTime() {
10488 return mHistoryBaseTime;
10489 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010490
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010491 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010492 public int getStartCount() {
10493 return mStartCount;
10494 }
10495
10496 public boolean isOnBattery() {
10497 return mOnBattery;
10498 }
10499
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010500 public boolean isCharging() {
10501 return mCharging;
10502 }
10503
Mike Mac2f518a2017-09-19 16:06:03 -070010504 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010505 return state == Display.STATE_ON || state == Display.STATE_VR
10506 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010507 }
10508
10509 public boolean isScreenOff(int state) {
10510 return state == Display.STATE_OFF;
10511 }
10512
10513 public boolean isScreenDoze(int state) {
10514 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010515 }
10516
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010517 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010518 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010519 mOnBatteryTimeBase.init(uptime, realtime);
10520 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010521 mRealtime = 0;
10522 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010523 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010524 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010525 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010526
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010527 void initDischarge() {
10528 mLowDischargeAmountSinceCharge = 0;
10529 mHighDischargeAmountSinceCharge = 0;
10530 mDischargeAmountScreenOn = 0;
10531 mDischargeAmountScreenOnSinceCharge = 0;
10532 mDischargeAmountScreenOff = 0;
10533 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010534 mDischargeAmountScreenDoze = 0;
10535 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010536 mDischargeStepTracker.init();
10537 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010538 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010539 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010540 mDischargeLightDozeCounter.reset(false);
10541 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010542 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010543 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010544
10545 public void resetAllStatsCmdLocked() {
10546 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010547 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010548 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010549 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010550 long realtime = mSecRealtime * 1000;
10551 mDischargeStartLevel = mHistoryCur.batteryLevel;
10552 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010553 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010554 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10555 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010556 mOnBatteryTimeBase.reset(uptime, realtime);
10557 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10558 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010559 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010560 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010561 mDischargeScreenDozeUnplugLevel = 0;
10562 mDischargeScreenOffUnplugLevel = 0;
10563 } else if (isScreenDoze(mScreenState)) {
10564 mDischargeScreenOnUnplugLevel = 0;
10565 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010566 mDischargeScreenOffUnplugLevel = 0;
10567 } else {
10568 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010569 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010570 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10571 }
10572 mDischargeAmountScreenOn = 0;
10573 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010574 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010575 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010576 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010577 }
10578
10579 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010580 final long uptimeMillis = mClocks.uptimeMillis();
10581 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010582 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010583 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010584 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010585 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010586 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010587 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010588 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010589
10590 if (mPowerProfile != null) {
10591 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10592 } else {
10593 mEstimatedBatteryCapacity = -1;
10594 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010595 mMinLearnedBatteryCapacity = -1;
10596 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010597 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010598 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010599 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010600 mLongestLightIdleTime = 0;
10601 mLongestFullIdleTime = 0;
10602 mDeviceIdleModeLightTimer.reset(false);
10603 mDeviceIdleModeFullTimer.reset(false);
10604 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010605 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010606 mPhoneOnTimer.reset(false);
10607 mAudioOnTimer.reset(false);
10608 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010609 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010610 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010611 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010612 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010613 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010614 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010615 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010616 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010617 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010618 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010619 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010620 mNetworkByteActivityCounters[i].reset(false);
10621 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010622 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010623 mMobileRadioActiveTimer.reset(false);
10624 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010625 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010626 mMobileRadioActiveUnknownTime.reset(false);
10627 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010628 mWifiOnTimer.reset(false);
10629 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010630 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010631 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010632 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010633 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10634 mWifiSupplStateTimer[i].reset(false);
10635 }
10636 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10637 mWifiSignalStrengthsTimer[i].reset(false);
10638 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010639 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010640 mWifiActiveTimer.reset(false);
10641 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010642 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10643 mGpsSignalQualityTimer[i].reset(false);
10644 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010645 mBluetoothActivity.reset(false);
10646 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010647 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010648
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010649 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010650 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010651 mUidStats.remove(mUidStats.keyAt(i));
10652 i--;
10653 }
10654 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010655
Bookatz50df7112017-08-04 14:53:26 -070010656 if (mRpmStats.size() > 0) {
10657 for (SamplingTimer timer : mRpmStats.values()) {
10658 mOnBatteryTimeBase.remove(timer);
10659 }
10660 mRpmStats.clear();
10661 }
10662 if (mScreenOffRpmStats.size() > 0) {
10663 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10664 mOnBatteryScreenOffTimeBase.remove(timer);
10665 }
10666 mScreenOffRpmStats.clear();
10667 }
10668
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010669 if (mKernelWakelockStats.size() > 0) {
10670 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010671 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010672 }
10673 mKernelWakelockStats.clear();
10674 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010675
James Carr3a226052016-07-01 14:49:52 -070010676 if (mKernelMemoryStats.size() > 0) {
10677 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10678 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10679 }
10680 mKernelMemoryStats.clear();
10681 }
10682
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010683 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010684 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10685 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010686 }
10687 mWakeupReasonStats.clear();
10688 }
10689
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010690 mLastHistoryStepDetails = null;
10691 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10692 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10693 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10694 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10695 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10696 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10697 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
10698 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
10699 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
10700 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
10701
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010702 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010703
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010704 clearHistoryLocked();
10705 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010706
Dianne Hackborn40c87252014-03-19 16:55:40 -070010707 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010708 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010709 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
10710 // Not recording process starts/stops.
10711 continue;
10712 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010713 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010714 if (active == null) {
10715 continue;
10716 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010717 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
10718 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010719 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070010720 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
10721 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010722 }
10723 }
10724 }
10725 }
10726
Mike Mac2f518a2017-09-19 16:06:03 -070010727 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
10728 updateOldDischargeScreenLevelLocked(oldState);
10729 updateNewDischargeScreenLevelLocked(newState);
10730 }
10731
10732 private void updateOldDischargeScreenLevelLocked(int state) {
10733 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010734 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
10735 if (diff > 0) {
10736 mDischargeAmountScreenOn += diff;
10737 mDischargeAmountScreenOnSinceCharge += diff;
10738 }
Mike Mac2f518a2017-09-19 16:06:03 -070010739 } else if (isScreenDoze(state)) {
10740 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
10741 if (diff > 0) {
10742 mDischargeAmountScreenDoze += diff;
10743 mDischargeAmountScreenDozeSinceCharge += diff;
10744 }
10745 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010746 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
10747 if (diff > 0) {
10748 mDischargeAmountScreenOff += diff;
10749 mDischargeAmountScreenOffSinceCharge += diff;
10750 }
10751 }
Mike Mac2f518a2017-09-19 16:06:03 -070010752 }
10753
10754 private void updateNewDischargeScreenLevelLocked(int state) {
10755 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010756 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
10757 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010758 mDischargeScreenDozeUnplugLevel = 0;
10759 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010760 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010761 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
10762 mDischargeScreenOffUnplugLevel = 0;
10763 } else if (isScreenOff(state)) {
10764 mDischargeScreenOnUnplugLevel = 0;
10765 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010766 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
10767 }
10768 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010769
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010770 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010771 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070010772 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010773 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010774 }
10775
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010776 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
10777 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
10778
10779 private final Object mWifiNetworkLock = new Object();
10780
10781 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010782 private String[] mWifiIfaces = EmptyArray.STRING;
10783
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010784 @GuardedBy("mWifiNetworkLock")
10785 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010786
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010787 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010788
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010789 @GuardedBy("mModemNetworkLock")
10790 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010791
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010792 @GuardedBy("mModemNetworkLock")
10793 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
10794
10795 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
10796 try {
10797 if (!ArrayUtils.isEmpty(ifaces)) {
10798 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
10799 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
10800 }
10801 } catch (IOException e) {
10802 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010803 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010804 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010805 }
10806
10807 /**
10808 * Distribute WiFi energy info and network traffic to apps.
10809 * @param info The energy information from the WiFi controller.
10810 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010811 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010812 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010813 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010814 }
10815
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010816 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070010817 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010818 synchronized (mWifiNetworkLock) {
10819 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
10820 if (latestStats != null) {
10821 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
10822 mNetworkStatsPool.acquire());
10823 mNetworkStatsPool.release(mLastWifiNetworkStats);
10824 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070010825 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010826 }
10827
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010828 synchronized (this) {
10829 if (!mOnBatteryInternal) {
10830 if (delta != null) {
10831 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010832 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010833 return;
10834 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010835
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010836 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
10837 SparseLongArray rxPackets = new SparseLongArray();
10838 SparseLongArray txPackets = new SparseLongArray();
10839 long totalTxPackets = 0;
10840 long totalRxPackets = 0;
10841 if (delta != null) {
10842 NetworkStats.Entry entry = new NetworkStats.Entry();
10843 final int size = delta.size();
10844 for (int i = 0; i < size; i++) {
10845 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010846
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010847 if (DEBUG_ENERGY) {
10848 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
10849 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
10850 + " txPackets=" + entry.txPackets);
10851 }
10852
10853 if (entry.rxBytes == 0 && entry.txBytes == 0) {
10854 // Skip the lookup below since there is no work to do.
10855 continue;
10856 }
10857
10858 final Uid u = getUidStatsLocked(mapUid(entry.uid));
10859 if (entry.rxBytes != 0) {
10860 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080010861 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010862 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10863 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
10864 entry.rxPackets);
10865 }
10866 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
10867 entry.rxBytes);
10868 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
10869 entry.rxPackets);
10870
10871 rxPackets.put(u.getUid(), entry.rxPackets);
10872
10873 // Sum the total number of packets so that the Rx Power can
10874 // be evenly distributed amongst the apps.
10875 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080010876 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010877
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010878 if (entry.txBytes != 0) {
10879 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080010880 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010881 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10882 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
10883 entry.txPackets);
10884 }
10885 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
10886 entry.txBytes);
10887 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
10888 entry.txPackets);
10889
10890 txPackets.put(u.getUid(), entry.txPackets);
10891
10892 // Sum the total number of packets so that the Tx Power can
10893 // be evenly distributed amongst the apps.
10894 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080010895 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080010896 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010897 mNetworkStatsPool.release(delta);
10898 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070010899 }
10900
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010901 if (info != null) {
10902 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070010903
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010904 // Measured in mAms
10905 final long txTimeMs = info.getControllerTxTimeMillis();
10906 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080010907 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010908 final long idleTimeMs = info.getControllerIdleTimeMillis();
10909 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070010910
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010911 long leftOverRxTimeMs = rxTimeMs;
10912 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070010913
Adam Lesinskie08af192015-03-25 16:42:59 -070010914 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010915 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
10916 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
10917 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
10918 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
10919 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080010920 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070010921 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010922
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010923 long totalWifiLockTimeMs = 0;
10924 long totalScanTimeMs = 0;
10925
10926 // On the first pass, collect some totals so that we can normalize power
10927 // calculations if we need to.
10928 final int uidStatsSize = mUidStats.size();
10929 for (int i = 0; i < uidStatsSize; i++) {
10930 final Uid uid = mUidStats.valueAt(i);
10931
10932 // Sum the total scan power for all apps.
10933 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
10934 elapsedRealtimeMs * 1000) / 1000;
10935
10936 // Sum the total time holding wifi lock for all apps.
10937 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
10938 elapsedRealtimeMs * 1000) / 1000;
10939 }
10940
10941 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
10942 Slog.d(TAG,
10943 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
10944 + rxTimeMs + " ms). Normalizing scan time.");
10945 }
10946 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
10947 Slog.d(TAG,
10948 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
10949 + txTimeMs + " ms). Normalizing scan time.");
10950 }
10951
10952 // Actually assign and distribute power usage to apps.
10953 for (int i = 0; i < uidStatsSize; i++) {
10954 final Uid uid = mUidStats.valueAt(i);
10955
10956 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
10957 elapsedRealtimeMs * 1000) / 1000;
10958 if (scanTimeSinceMarkMs > 0) {
10959 // Set the new mark so that next time we get new data since this point.
10960 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
10961
10962 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
10963 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
10964
10965 // Our total scan time is more than the reported Tx/Rx time.
10966 // This is possible because the cost of a scan is approximate.
10967 // Let's normalize the result so that we evenly blame each app
10968 // scanning.
10969 //
10970 // This means that we may have apps that transmitted/received packets not be
10971 // blamed for this, but this is fine as scans are relatively more expensive.
10972 if (totalScanTimeMs > rxTimeMs) {
10973 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
10974 totalScanTimeMs;
10975 }
10976 if (totalScanTimeMs > txTimeMs) {
10977 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
10978 totalScanTimeMs;
10979 }
10980
10981 if (DEBUG_ENERGY) {
10982 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
10983 + scanRxTimeSinceMarkMs + " ms Tx:"
10984 + scanTxTimeSinceMarkMs + " ms)");
10985 }
10986
10987 ControllerActivityCounterImpl activityCounter =
10988 uid.getOrCreateWifiControllerActivityLocked();
10989 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
10990 activityCounter.getTxTimeCounters()[0].addCountLocked(
10991 scanTxTimeSinceMarkMs);
10992 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
10993 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
10994 }
10995
10996 // Distribute evenly the power consumed while Idle to each app holding a WiFi
10997 // lock.
10998 final long wifiLockTimeSinceMarkMs =
10999 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11000 elapsedRealtimeMs * 1000) / 1000;
11001 if (wifiLockTimeSinceMarkMs > 0) {
11002 // Set the new mark so that next time we get new data since this point.
11003 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11004
11005 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11006 / totalWifiLockTimeMs;
11007 if (DEBUG_ENERGY) {
11008 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11009 + myIdleTimeMs + " ms");
11010 }
11011 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11012 .addCountLocked(myIdleTimeMs);
11013 }
11014 }
11015
Adam Lesinskie08af192015-03-25 16:42:59 -070011016 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011017 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11018 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011019 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011020
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011021 // Distribute the remaining Tx power appropriately between all apps that transmitted
11022 // packets.
11023 for (int i = 0; i < txPackets.size(); i++) {
11024 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11025 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11026 / totalTxPackets;
11027 if (DEBUG_ENERGY) {
11028 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11029 }
11030 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11031 .addCountLocked(myTxTimeMs);
11032 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011033
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011034 // Distribute the remaining Rx power appropriately between all apps that received
11035 // packets.
11036 for (int i = 0; i < rxPackets.size(); i++) {
11037 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11038 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11039 / totalRxPackets;
11040 if (DEBUG_ENERGY) {
11041 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11042 }
11043 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11044 .addCountLocked(myRxTimeMs);
11045 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011046
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011047 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11048
11049
11050 // Update WiFi controller stats.
11051 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11052 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11053 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011054 mWifiActivity.getScanTimeCounter().addCountLocked(
11055 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011056 mWifiActivity.getIdleTimeCounter().addCountLocked(
11057 info.getControllerIdleTimeMillis());
11058
11059 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11060 final double opVolt = mPowerProfile.getAveragePower(
11061 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11062 if (opVolt != 0) {
11063 // We store the power drain as mAms.
11064 mWifiActivity.getPowerCounter().addCountLocked(
11065 (long) (info.getControllerEnergyUsed() / opVolt));
11066 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011067 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011068 }
11069 }
11070
11071 /**
11072 * Distribute Cell radio energy info and network traffic to apps.
11073 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011074 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011075 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011076 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011077 }
11078
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011079 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011080 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011081 synchronized (mModemNetworkLock) {
11082 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11083 if (latestStats != null) {
11084 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11085 mNetworkStatsPool.acquire());
11086 mNetworkStatsPool.release(mLastModemNetworkStats);
11087 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011088 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011089 }
11090
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011091 synchronized (this) {
11092 if (!mOnBatteryInternal) {
11093 if (delta != null) {
11094 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011095 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011096 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011097 }
11098
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011099 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011100 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11101 elapsedRealtimeMs * 1000);
11102 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11103
11104 long totalRxPackets = 0;
11105 long totalTxPackets = 0;
11106 if (delta != null) {
11107 NetworkStats.Entry entry = new NetworkStats.Entry();
11108 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011109 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011110 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011111 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11112 continue;
11113 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011114
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011115 if (DEBUG_ENERGY) {
11116 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11117 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11118 + " txPackets=" + entry.txPackets);
11119 }
11120
11121 totalRxPackets += entry.rxPackets;
11122 totalTxPackets += entry.txPackets;
11123
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011124 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011125 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11126 entry.rxPackets);
11127 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11128 entry.txPackets);
11129 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11130 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11131 entry.rxBytes, entry.rxPackets);
11132 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11133 entry.txBytes, entry.txPackets);
11134 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011135
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011136 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11137 entry.rxBytes);
11138 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11139 entry.txBytes);
11140 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11141 entry.rxPackets);
11142 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11143 entry.txPackets);
11144 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011145
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011146 // Now distribute proportional blame to the apps that did networking.
11147 long totalPackets = totalRxPackets + totalTxPackets;
11148 if (totalPackets > 0) {
11149 for (int i = 0; i < size; i++) {
11150 entry = delta.getValues(i, entry);
11151 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11152 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011153 }
11154
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011155 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11156
11157 // Distribute total radio active time in to this app.
11158 final long appPackets = entry.rxPackets + entry.txPackets;
11159 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11160 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11161
11162 // Remove this app from the totals, so that we don't lose any time
11163 // due to rounding.
11164 radioTime -= appRadioTime;
11165 totalPackets -= appPackets;
11166
11167 if (activityInfo != null) {
11168 ControllerActivityCounterImpl activityCounter =
11169 u.getOrCreateModemControllerActivityLocked();
11170 if (totalRxPackets > 0 && entry.rxPackets > 0) {
11171 final long rxMs = (entry.rxPackets * activityInfo.getRxTimeMillis())
11172 / totalRxPackets;
11173 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11174 }
11175
11176 if (totalTxPackets > 0 && entry.txPackets > 0) {
11177 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11178 long txMs =
11179 entry.txPackets * activityInfo.getTxTimeMillis()[lvl];
11180 txMs /= totalTxPackets;
11181 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11182 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011183 }
11184 }
11185 }
11186 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011187
11188 if (radioTime > 0) {
11189 // Whoops, there is some radio time we can't blame on an app!
11190 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11191 mMobileRadioActiveUnknownCount.addCountLocked(1);
11192 }
11193
11194 mNetworkStatsPool.release(delta);
11195 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011196 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011197
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011198 if (activityInfo != null) {
11199 mHasModemReporting = true;
11200 mModemActivity.getIdleTimeCounter().addCountLocked(
11201 activityInfo.getIdleTimeMillis());
11202 mModemActivity.getRxTimeCounter().addCountLocked(activityInfo.getRxTimeMillis());
11203 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11204 mModemActivity.getTxTimeCounters()[lvl]
11205 .addCountLocked(activityInfo.getTxTimeMillis()[lvl]);
11206 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011207
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011208 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11209 final double opVolt = mPowerProfile.getAveragePower(
11210 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11211 if (opVolt != 0) {
11212 // We store the power drain as mAms.
11213 mModemActivity.getPowerCounter().addCountLocked(
11214 (long) (activityInfo.getEnergyUsed() / opVolt));
11215 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011216 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011217 }
11218 }
11219
11220 /**
11221 * Distribute Bluetooth energy info and network traffic to apps.
11222 * @param info The energy information from the bluetooth controller.
11223 */
11224 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011225 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011226 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011227 }
11228
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011229 if (info == null || !mOnBatteryInternal) {
11230 return;
11231 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011232
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011233 mHasBluetoothReporting = true;
11234
Bookatz867c0d72017-03-07 18:23:42 -080011235 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011236 final long rxTimeMs = info.getControllerRxTimeMillis();
11237 final long txTimeMs = info.getControllerTxTimeMillis();
11238
11239 if (DEBUG_ENERGY) {
11240 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11241 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11242 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11243 Slog.d(TAG, " Idle Time: " + info.getControllerIdleTimeMillis() + " ms");
11244 }
11245
11246 long totalScanTimeMs = 0;
11247
11248 final int uidCount = mUidStats.size();
11249 for (int i = 0; i < uidCount; i++) {
11250 final Uid u = mUidStats.valueAt(i);
11251 if (u.mBluetoothScanTimer == null) {
11252 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011253 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011254
Bookatzaa4594a2017-03-24 12:39:56 -070011255 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011256 elapsedRealtimeMs * 1000) / 1000;
11257 }
11258
11259 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11260 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11261
11262 if (DEBUG_ENERGY) {
11263 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11264 + " TX=" + normalizeScanTxTime);
11265 }
11266
11267 long leftOverRxTimeMs = rxTimeMs;
11268 long leftOverTxTimeMs = txTimeMs;
11269
11270 for (int i = 0; i < uidCount; i++) {
11271 final Uid u = mUidStats.valueAt(i);
11272 if (u.mBluetoothScanTimer == null) {
11273 continue;
11274 }
11275
Bookatzaa4594a2017-03-24 12:39:56 -070011276 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011277 elapsedRealtimeMs * 1000) / 1000;
11278 if (scanTimeSinceMarkMs > 0) {
11279 // Set the new mark so that next time we get new data since this point.
11280 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11281
11282 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11283 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11284
11285 if (normalizeScanRxTime) {
11286 // Scan time is longer than the total rx time in the controller,
11287 // so distribute the scan time proportionately. This means regular traffic
11288 // will not blamed, but scans are more expensive anyways.
11289 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11290 }
11291
11292 if (normalizeScanTxTime) {
11293 // Scan time is longer than the total tx time in the controller,
11294 // so distribute the scan time proportionately. This means regular traffic
11295 // will not blamed, but scans are more expensive anyways.
11296 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11297 }
11298
11299 final ControllerActivityCounterImpl counter =
11300 u.getOrCreateBluetoothControllerActivityLocked();
11301 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11302 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11303
11304 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11305 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11306 }
11307 }
11308
11309 if (DEBUG_ENERGY) {
11310 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs
11311 + " TX=" + leftOverTxTimeMs);
11312 }
11313
11314 //
11315 // Now distribute blame to apps that did bluetooth traffic.
11316 //
11317
11318 long totalTxBytes = 0;
11319 long totalRxBytes = 0;
11320
11321 final UidTraffic[] uidTraffic = info.getUidTraffic();
11322 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11323 for (int i = 0; i < numUids; i++) {
11324 final UidTraffic traffic = uidTraffic[i];
11325
11326 // Add to the global counters.
11327 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(
11328 traffic.getRxBytes());
11329 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(
11330 traffic.getTxBytes());
11331
11332 // Add to the UID counters.
11333 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
11334 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, traffic.getRxBytes(), 0);
11335 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, traffic.getTxBytes(), 0);
11336
11337 // Calculate the total traffic.
11338 totalTxBytes += traffic.getTxBytes();
11339 totalRxBytes += traffic.getRxBytes();
11340 }
11341
11342 if ((totalTxBytes != 0 || totalRxBytes != 0) &&
11343 (leftOverRxTimeMs != 0 || leftOverTxTimeMs != 0)) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011344 for (int i = 0; i < numUids; i++) {
11345 final UidTraffic traffic = uidTraffic[i];
11346
Adam Lesinski50e47602015-12-04 17:04:54 -080011347 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011348 final ControllerActivityCounterImpl counter =
11349 u.getOrCreateBluetoothControllerActivityLocked();
11350
11351 if (totalRxBytes > 0 && traffic.getRxBytes() > 0) {
11352 final long timeRxMs = (leftOverRxTimeMs * traffic.getRxBytes()) / totalRxBytes;
11353
11354 if (DEBUG_ENERGY) {
11355 Slog.d(TAG, "UID=" + traffic.getUid() + " rx_bytes=" + traffic.getRxBytes()
11356 + " rx_time=" + timeRxMs);
11357 }
11358 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11359 leftOverRxTimeMs -= timeRxMs;
11360 }
11361
11362 if (totalTxBytes > 0 && traffic.getTxBytes() > 0) {
11363 final long timeTxMs = (leftOverTxTimeMs * traffic.getTxBytes()) / totalTxBytes;
11364
11365 if (DEBUG_ENERGY) {
11366 Slog.d(TAG, "UID=" + traffic.getUid() + " tx_bytes=" + traffic.getTxBytes()
11367 + " tx_time=" + timeTxMs);
11368 }
11369
11370 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11371 leftOverTxTimeMs -= timeTxMs;
11372 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011373 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011374 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011375
11376 mBluetoothActivity.getRxTimeCounter().addCountLocked(
11377 info.getControllerRxTimeMillis());
11378 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(
11379 info.getControllerTxTimeMillis());
11380 mBluetoothActivity.getIdleTimeCounter().addCountLocked(
11381 info.getControllerIdleTimeMillis());
11382
11383 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11384 final double opVolt = mPowerProfile.getAveragePower(
11385 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11386 if (opVolt != 0) {
11387 // We store the power drain as mAms.
11388 mBluetoothActivity.getPowerCounter().addCountLocked(
11389 (long) (info.getControllerEnergyUsed() / opVolt));
11390 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011391 }
11392
11393 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011394 * Read and record Resource Power Manager (RPM) state and voter times.
11395 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11396 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011397 */
11398 public void updateRpmStatsLocked() {
11399 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011400 long now = SystemClock.elapsedRealtime();
11401 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11402 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11403 mLastRpmStatsUpdateTimeMs = now;
11404 }
Bookatz50df7112017-08-04 14:53:26 -070011405
11406 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11407 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11408
11409 // Update values for this platform state.
11410 final String pName = pstate.getKey();
11411 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11412 final int pCount = pstate.getValue().mCount;
11413 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011414 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11415 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11416 }
Bookatz50df7112017-08-04 14:53:26 -070011417
11418 // Update values for each voter of this platform state.
11419 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11420 : pstate.getValue().mVoters.entrySet()) {
11421 final String vName = pName + "." + voter.getKey();
11422 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11423 final int vCount = voter.getValue().mCount;
11424 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011425 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11426 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11427 }
Bookatz50df7112017-08-04 14:53:26 -070011428 }
11429 }
11430
11431 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11432 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11433
11434 final String subsysName = subsys.getKey();
11435 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11436 : subsys.getValue().mStates.entrySet()) {
11437 final String name = subsysName + "." + sstate.getKey();
11438 final long timeUs = sstate.getValue().mTimeMs * 1000;
11439 final int count = sstate.getValue().mCount;
11440 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011441 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11442 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11443 }
Bookatz50df7112017-08-04 14:53:26 -070011444 }
11445 }
11446 }
11447
11448 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011449 * Read and distribute kernel wake lock use across apps.
11450 */
11451 public void updateKernelWakelocksLocked() {
11452 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11453 mTmpWakelockStats);
11454 if (wakelockStats == null) {
11455 // Not crashing might make board bringup easier.
11456 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11457 return;
11458 }
11459
11460 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11461 String name = ent.getKey();
11462 KernelWakelockStats.Entry kws = ent.getValue();
11463
11464 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11465 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011466 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011467 mKernelWakelockStats.put(name, kwlt);
11468 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011469
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011470 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011471 kwlt.setUpdateVersion(kws.mVersion);
11472 }
11473
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011474 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011475 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11476 // this time.
11477 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11478 SamplingTimer st = ent.getValue();
11479 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11480 st.endSample();
11481 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011482 }
11483 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011484
Adam Lesinskid84ad302016-05-17 18:31:02 -070011485 // Record whether we've seen a non-zero time (for debugging b/22716723).
11486 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011487 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11488 }
11489
11490 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11491 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11492 wakelockStats.kernelWakelockVersion);
11493 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011494 }
11495
Adam Lesinski72478f02015-06-17 15:39:43 -070011496 // We use an anonymous class to access these variables,
11497 // so they can't live on the stack or they'd have to be
11498 // final MutableLong objects (more allocations).
11499 // Used in updateCpuTimeLocked().
11500 long mTempTotalCpuUserTimeUs;
11501 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011502 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011503
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011504 /**
James Carr3a226052016-07-01 14:49:52 -070011505 * Reads the newest memory stats from the kernel.
11506 */
11507 public void updateKernelMemoryBandwidthLocked() {
11508 mKernelMemoryBandwidthStats.updateStats();
11509 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11510 final int bandwidthEntryCount = bandwidthEntries.size();
11511 int index;
11512 for (int i = 0; i < bandwidthEntryCount; i++) {
11513 SamplingTimer timer;
11514 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11515 timer = mKernelMemoryStats.valueAt(index);
11516 } else {
11517 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11518 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11519 }
11520 timer.update(bandwidthEntries.valueAt(i), 1);
11521 if (DEBUG_MEMORY) {
11522 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11523 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11524 mKernelMemoryStats.get(
11525 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11526 mKernelMemoryStats.size()));
11527 }
11528 }
11529 }
11530
11531 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011532 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11533 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11534 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011535 */
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011536 public void updateCpuTimeLocked() {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011537 if (mPowerProfile == null) {
11538 return;
11539 }
11540
Adam Lesinski72478f02015-06-17 15:39:43 -070011541 if (DEBUG_ENERGY_CPU) {
11542 Slog.d(TAG, "!Cpu updating!");
11543 }
11544
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011545 if (mCpuFreqs == null) {
11546 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11547 }
11548
Sudheer Shanka38383232017-07-25 09:55:03 -070011549 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11550 // usually holding the wakelock on behalf of an app.
11551 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11552 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Adam Lesinski72478f02015-06-17 15:39:43 -070011553 if (mOnBatteryScreenOffTimeBase.isRunning()) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011554 partialTimersToConsider = new ArrayList<>();
11555 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011556 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011557 // Since the collection and blaming of wakelocks can be scheduled to run after
11558 // some delay, the mPartialTimers list may have new entries. We can't blame
11559 // the newly added timer for past cpu time, so we only consider timers that
11560 // were present for one round of collection. Once a timer has gone through
11561 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011562 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011563 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011564 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011565 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011566 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011567 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011568
Sudheer Shanka38383232017-07-25 09:55:03 -070011569 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11570 // need to take the snapshots.
11571 if (!mOnBatteryInternal) {
11572 mKernelUidCpuTimeReader.readDelta(null);
11573 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Ma3d422c32017-10-25 11:08:57 -070011574 mKernelUidCpuActiveTimeReader.readDelta(null);
11575 mKernelUidCpuClusterTimeReader.readDelta(null);
Sudheer Shanka38383232017-07-25 09:55:03 -070011576 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
11577 mKernelCpuSpeedReaders[cluster].readDelta();
11578 }
11579 return;
11580 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011581
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011582 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011583 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
11584 ? null : new SparseLongArray();
Sudheer Shanka38383232017-07-25 09:55:03 -070011585 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011586 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
11587 // freqs, so no need to approximate these values.
11588 if (updatedUids != null) {
11589 updateClusterSpeedTimes(updatedUids);
Sudheer Shanka671985f2017-05-19 11:33:42 -070011590 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011591 readKernelUidCpuFreqTimesLocked(partialTimersToConsider);
Mike Ma3d422c32017-10-25 11:08:57 -070011592 readKernelUidCpuActiveTimesLocked();
11593 readKernelUidCpuClusterTimesLocked();
Sudheer Shanka38383232017-07-25 09:55:03 -070011594 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011595
Sudheer Shanka38383232017-07-25 09:55:03 -070011596 /**
11597 * Mark the current partial timers as gone through a collection so that they will be
11598 * considered in the next cpu times distribution to wakelock holders.
11599 */
11600 @VisibleForTesting
11601 public void markPartialTimersAsEligible() {
11602 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
11603 // No difference, so each timer is now considered for the next collection.
11604 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
11605 mPartialTimers.get(i).mInList = true;
11606 }
11607 } else {
11608 // The lists are different, meaning we added (or removed a timer) since the last
11609 // collection.
11610 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
11611 mLastPartialTimers.get(i).mInList = false;
11612 }
11613 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070011614
Sudheer Shanka38383232017-07-25 09:55:03 -070011615 // Mark the current timers as gone through a collection.
11616 final int numPartialTimers = mPartialTimers.size();
11617 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011618 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011619 timer.mInList = true;
11620 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070011621 }
11622 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011623 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011624
Sudheer Shanka38383232017-07-25 09:55:03 -070011625 /**
11626 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
11627 * calculate cpu times spent by each uid at different frequencies.
11628 *
11629 * @param updatedUids The uids for which times spent at different frequencies are calculated.
11630 */
11631 @VisibleForTesting
11632 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011633 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011634 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070011635 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011636 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011637 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
11638 if (clusterSpeedTimesMs[cluster] != null) {
11639 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
11640 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011641 }
11642 }
11643 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011644 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011645 // We have cpu times per freq aggregated over all uids but we need the times per uid.
11646 // So, we distribute total time spent by an uid to different cpu freqs based on the
11647 // amount of time cpu was running at that freq.
11648 final int updatedUidsCount = updatedUids.size();
11649 for (int i = 0; i < updatedUidsCount; ++i) {
11650 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070011651 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011652 // Add the cpu speeds to this UID.
11653 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070011654 if (u.mCpuClusterSpeedTimesUs == null ||
11655 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011656 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011657 }
11658
Sudheer Shankaaf857412017-07-21 00:14:24 -070011659 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
11660 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
11661 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
11662 u.mCpuClusterSpeedTimesUs[cluster].length) {
11663 u.mCpuClusterSpeedTimesUs[cluster]
11664 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011665 }
11666
Sudheer Shankaaf857412017-07-21 00:14:24 -070011667 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011668 for (int speed = 0; speed < speedsInCluster; speed++) {
11669 if (cpuSpeeds[speed] == null) {
11670 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11671 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011672 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
11673 * clusterSpeedTimesMs[cluster][speed]
11674 / totalCpuClustersTimeMs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011675 }
11676 }
11677 }
11678 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011679 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011680
Sudheer Shanka38383232017-07-25 09:55:03 -070011681 /**
11682 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
11683 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
11684 * wakelock holders.
11685 *
11686 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
11687 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
11688 */
11689 @VisibleForTesting
11690 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
11691 @Nullable SparseLongArray updatedUids) {
11692 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
11693 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11694 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070011695
Sudheer Shanka38383232017-07-25 09:55:03 -070011696 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
11697 uid = mapUid(uid);
11698 if (Process.isIsolated(uid)) {
11699 // This could happen if the isolated uid mapping was removed before that process
11700 // was actually killed.
11701 mKernelUidCpuTimeReader.removeUid(uid);
11702 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
11703 return;
11704 }
11705 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11706 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
11707 mKernelUidCpuTimeReader.removeUid(uid);
11708 return;
11709 }
11710 final Uid u = getUidStatsLocked(uid);
11711
11712 // Accumulate the total system and user time.
11713 mTempTotalCpuUserTimeUs += userTimeUs;
11714 mTempTotalCpuSystemTimeUs += systemTimeUs;
11715
11716 StringBuilder sb = null;
11717 if (DEBUG_ENERGY_CPU) {
11718 sb = new StringBuilder();
11719 sb.append(" got time for uid=").append(u.mUid).append(": u=");
11720 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11721 sb.append(" s=");
11722 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11723 sb.append("\n");
11724 }
11725
11726 if (numWakelocks > 0) {
11727 // We have wakelocks being held, so only give a portion of the
11728 // time to the process. The rest will be distributed among wakelock
11729 // holders.
11730 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
11731 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
11732 }
11733
11734 if (sb != null) {
11735 sb.append(" adding to uid=").append(u.mUid).append(": u=");
11736 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11737 sb.append(" s=");
11738 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11739 Slog.d(TAG, sb.toString());
11740 }
11741
11742 u.mUserCpuTime.addCountLocked(userTimeUs);
11743 u.mSystemCpuTime.addCountLocked(systemTimeUs);
11744 if (updatedUids != null) {
11745 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
11746 }
11747 });
11748
11749 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11750 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11751 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
11752 }
11753
11754 if (numWakelocks > 0) {
11755 // Distribute a portion of the total cpu time to wakelock holders.
11756 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11757 mTempTotalCpuSystemTimeUs =
11758 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11759
11760 for (int i = 0; i < numWakelocks; ++i) {
11761 final StopwatchTimer timer = partialTimers.get(i);
11762 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
11763 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
11764
11765 if (DEBUG_ENERGY_CPU) {
11766 final StringBuilder sb = new StringBuilder();
11767 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
11768 .append(": u=");
11769 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11770 sb.append(" s=");
11771 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11772 Slog.d(TAG, sb.toString());
11773 }
11774
11775 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs);
11776 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs);
11777 if (updatedUids != null) {
11778 final int uid = timer.mUid.getUid();
11779 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
11780 }
11781
11782 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
11783 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000);
11784
11785 mTempTotalCpuUserTimeUs -= userTimeUs;
11786 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011787 }
11788 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011789 }
11790
Sudheer Shanka38383232017-07-25 09:55:03 -070011791 /**
11792 * Take a snapshot of the cpu times spent by each uid in each freq and update the
11793 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011794 *
11795 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070011796 */
11797 @VisibleForTesting
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011798 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers) {
11799 final boolean perClusterTimesAvailable =
11800 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
11801 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11802 final int numClusters = mPowerProfile.getNumCpuClusters();
11803 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080011804 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011805 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
11806 uid = mapUid(uid);
11807 if (Process.isIsolated(uid)) {
11808 mKernelUidCpuFreqTimeReader.removeUid(uid);
11809 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
11810 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070011811 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011812 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11813 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
11814 mKernelUidCpuFreqTimeReader.removeUid(uid);
11815 return;
11816 }
11817 final Uid u = getUidStatsLocked(uid);
11818 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
11819 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
11820 }
11821 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
11822 if (u.mScreenOffCpuFreqTimeMs == null ||
11823 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
11824 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
11825 mOnBatteryScreenOffTimeBase);
11826 }
11827 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011828
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011829 if (perClusterTimesAvailable) {
11830 if (u.mCpuClusterSpeedTimesUs == null ||
11831 u.mCpuClusterSpeedTimesUs.length != numClusters) {
11832 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070011833 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011834 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
11835 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070011836 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011837
11838 int freqIndex = 0;
11839 for (int cluster = 0; cluster < numClusters; ++cluster) {
11840 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
11841 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
11842 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
11843 u.mCpuClusterSpeedTimesUs[cluster]
11844 = new LongSamplingCounter[speedsInCluster];
11845 }
11846 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
11847 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
11848 }
11849 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
11850 for (int speed = 0; speed < speedsInCluster; ++speed) {
11851 if (cpuTimesUs[speed] == null) {
11852 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11853 }
11854 final long appAllocationUs;
11855 if (mWakeLockAllocationsUs != null) {
11856 appAllocationUs =
11857 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
11858 mWakeLockAllocationsUs[cluster][speed] +=
11859 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
11860 } else {
11861 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
11862 }
11863 cpuTimesUs[speed].addCountLocked(appAllocationUs);
11864 freqIndex++;
11865 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011866 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011867 }
11868 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011869
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080011870 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11871 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11872 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
11873 }
11874
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011875 if (mWakeLockAllocationsUs != null) {
11876 for (int i = 0; i < numWakelocks; ++i) {
11877 final Uid u = partialTimers.get(i).mUid;
11878 if (u.mCpuClusterSpeedTimesUs == null ||
11879 u.mCpuClusterSpeedTimesUs.length != numClusters) {
11880 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
11881 }
11882
11883 for (int cluster = 0; cluster < numClusters; ++cluster) {
11884 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
11885 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
11886 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
11887 u.mCpuClusterSpeedTimesUs[cluster]
11888 = new LongSamplingCounter[speedsInCluster];
11889 }
11890 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
11891 for (int speed = 0; speed < speedsInCluster; ++speed) {
11892 if (cpuTimeUs[speed] == null) {
11893 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11894 }
11895 final long allocationUs =
11896 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
11897 cpuTimeUs[speed].addCountLocked(allocationUs);
11898 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
11899 }
11900 }
11901 }
11902 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011903 }
11904
Mike Ma3d422c32017-10-25 11:08:57 -070011905 /**
11906 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
11907 * counters.
11908 */
11909 @VisibleForTesting
11910 public void readKernelUidCpuActiveTimesLocked() {
11911 final long startTimeMs = mClocks.uptimeMillis();
11912 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesUs) -> {
11913 uid = mapUid(uid);
11914 if (Process.isIsolated(uid)) {
11915 mKernelUidCpuActiveTimeReader.removeUid(uid);
11916 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
11917 return;
11918 }
11919 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11920 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
11921 mKernelUidCpuActiveTimeReader.removeUid(uid);
11922 return;
11923 }
11924 final Uid u = getUidStatsLocked(uid);
11925 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesUs);
11926 });
11927
11928 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11929 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11930 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
11931 }
11932 }
11933
11934 /**
11935 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
11936 * counters.
11937 */
11938 @VisibleForTesting
11939 public void readKernelUidCpuClusterTimesLocked() {
11940 final long startTimeMs = mClocks.uptimeMillis();
11941 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesUs) -> {
11942 uid = mapUid(uid);
11943 if (Process.isIsolated(uid)) {
11944 mKernelUidCpuClusterTimeReader.removeUid(uid);
11945 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
11946 return;
11947 }
11948 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11949 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
11950 mKernelUidCpuClusterTimeReader.removeUid(uid);
11951 return;
11952 }
11953 final Uid u = getUidStatsLocked(uid);
11954 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesUs);
11955 });
11956
11957 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11958 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11959 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
11960 }
11961 }
11962
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011963 boolean setChargingLocked(boolean charging) {
11964 if (mCharging != charging) {
11965 mCharging = charging;
11966 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070011967 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011968 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070011969 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011970 }
11971 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
11972 return true;
11973 }
11974 return false;
11975 }
11976
Mike Mac2f518a2017-09-19 16:06:03 -070011977 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
11978 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011979 boolean doWrite = false;
11980 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
11981 m.arg1 = onBattery ? 1 : 0;
11982 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011983
Dianne Hackborn40c87252014-03-19 16:55:40 -070011984 final long uptime = mSecUptime * 1000;
11985 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070011986 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011987 if (onBattery) {
11988 // We will reset our status if we are unplugging after the
11989 // battery was last full, or the level is at 100, or
11990 // we have gone through a significant charge (from a very low
11991 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011992 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070011993 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011994 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070011995 || (mDischargeCurrentLevel < 20 && level >= 80)
11996 || (getHighDischargeAmountSinceCharge() >= 200
11997 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070011998 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070011999 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012000 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12001 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012002 // Before we write, collect a snapshot of the final aggregated
12003 // stats to be reported in the next checkin. Only do this if we have
12004 // a sufficient amount of data to make it interesting.
12005 if (getLowDischargeAmountSinceCharge() >= 20) {
12006 final Parcel parcel = Parcel.obtain();
12007 writeSummaryToParcel(parcel, true);
12008 BackgroundThread.getHandler().post(new Runnable() {
12009 @Override public void run() {
12010 synchronized (mCheckinFile) {
12011 FileOutputStream stream = null;
12012 try {
12013 stream = mCheckinFile.startWrite();
12014 stream.write(parcel.marshall());
12015 stream.flush();
12016 FileUtils.sync(stream);
12017 stream.close();
12018 mCheckinFile.finishWrite(stream);
12019 } catch (IOException e) {
12020 Slog.w("BatteryStats",
12021 "Error writing checkin battery statistics", e);
12022 mCheckinFile.failWrite(stream);
12023 } finally {
12024 parcel.recycle();
12025 }
12026 }
12027 }
12028 });
12029 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012030 doWrite = true;
12031 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012032 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012033 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012034 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012035 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012036 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012037 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012038 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012039 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012040 if (mCharging) {
12041 setChargingLocked(false);
12042 }
12043 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012044 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012045 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012046 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012047 mDischargeStepTracker.clearTime();
12048 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012049 mInitStepMode = mCurStepMode;
12050 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012051 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012052 mHistoryCur.batteryLevel = (byte)level;
12053 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12054 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12055 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012056 if (reset) {
12057 mRecordingHistory = true;
12058 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12059 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012060 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012061 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012062 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012063 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012064 mDischargeScreenDozeUnplugLevel = 0;
12065 mDischargeScreenOffUnplugLevel = 0;
12066 } else if (isScreenDoze(screenState)) {
12067 mDischargeScreenOnUnplugLevel = 0;
12068 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012069 mDischargeScreenOffUnplugLevel = 0;
12070 } else {
12071 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012072 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012073 mDischargeScreenOffUnplugLevel = level;
12074 }
12075 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012076 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012077 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012078 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012079 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012080 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012081 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012082 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012083 mHistoryCur.batteryLevel = (byte)level;
12084 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12085 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12086 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012087 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012088 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012089 if (level < mDischargeUnplugLevel) {
12090 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12091 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12092 }
Mike Mac2f518a2017-09-19 16:06:03 -070012093 updateDischargeScreenLevelsLocked(screenState, screenState);
12094 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012095 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012096 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012097 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012098 mInitStepMode = mCurStepMode;
12099 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012100 }
12101 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12102 if (mFile != null) {
12103 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012104 }
12105 }
12106 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012107
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012108 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12109 boolean reset) {
12110 mRecordingHistory = true;
12111 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn37de0982014-05-09 09:32:18 -070012112 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs,
12113 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012114 mHistoryCur);
12115 mHistoryCur.currentTime = 0;
12116 if (reset) {
12117 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12118 }
12119 }
12120
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012121 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12122 final long uptimeMs) {
12123 if (mRecordingHistory) {
12124 mHistoryCur.currentTime = currentTime;
12125 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_CURRENT_TIME,
12126 mHistoryCur);
12127 mHistoryCur.currentTime = 0;
12128 }
12129 }
12130
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012131 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12132 if (mRecordingHistory) {
12133 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012134 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_SHUTDOWN,
12135 mHistoryCur);
12136 mHistoryCur.currentTime = 0;
12137 }
12138 }
12139
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012140 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012141 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012142 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012143 }
12144 }
12145
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012146 // This should probably be exposed in the API, though it's not critical
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012147 public static final int BATTERY_PLUGGED_NONE = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012148
Bookatz8c6571b2017-10-24 15:04:41 -070012149 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12150 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12151 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012152 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12153 temp = Math.max(0, temp);
12154
Bookatz8c6571b2017-10-24 15:04:41 -070012155 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
12156 status, plugType, level, temp);
12157
Todd Poynor1acf06a2017-12-07 19:19:35 -080012158 final boolean onBattery =
12159 plugType == BATTERY_PLUGGED_NONE &&
12160 status != BatteryManager.BATTERY_STATUS_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080012161 final long uptime = mClocks.uptimeMillis();
12162 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012163 if (!mHaveBatteryLevel) {
12164 mHaveBatteryLevel = true;
12165 // We start out assuming that the device is plugged in (not
12166 // on battery). If our first report is now that we are indeed
12167 // plugged in, then twiddle our state to correctly reflect that
12168 // since we won't be going through the full setOnBattery().
12169 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012170 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012171 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012172 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012173 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012174 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012175 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012176 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012177 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012178 mHistoryCur.batteryStatus = (byte)status;
12179 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012180 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012181 mMaxChargeStepLevel = mMinDischargeStepLevel =
12182 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012183 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012184 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12185 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12186 }
12187 int oldStatus = mHistoryCur.batteryStatus;
12188 if (onBattery) {
12189 mDischargeCurrentLevel = level;
12190 if (!mRecordingHistory) {
12191 mRecordingHistory = true;
12192 startRecordingHistory(elapsedRealtime, uptime, true);
12193 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012194 } else if (level < 96 &&
12195 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012196 if (!mRecordingHistory) {
12197 mRecordingHistory = true;
12198 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012199 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012200 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012201 mCurrentBatteryLevel = level;
12202 if (mDischargePlugLevel < 0) {
12203 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012204 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012205
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012206 if (onBattery != mOnBattery) {
12207 mHistoryCur.batteryLevel = (byte)level;
12208 mHistoryCur.batteryStatus = (byte)status;
12209 mHistoryCur.batteryHealth = (byte)health;
12210 mHistoryCur.batteryPlugType = (byte)plugType;
12211 mHistoryCur.batteryTemperature = (short)temp;
12212 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012213 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12214 // Only record discharges
12215 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12216 mDischargeCounter.addCountLocked(chargeDiff);
12217 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012218 if (isScreenDoze(mScreenState)) {
12219 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12220 }
Mike Ma15313c92017-11-15 17:58:21 -080012221 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12222 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12223 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12224 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12225 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012226 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012227 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012228 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012229 } else {
12230 boolean changed = false;
12231 if (mHistoryCur.batteryLevel != level) {
12232 mHistoryCur.batteryLevel = (byte)level;
12233 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012234
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012235 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12236 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012237 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070012238 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012239 if (mHistoryCur.batteryStatus != status) {
12240 mHistoryCur.batteryStatus = (byte)status;
12241 changed = true;
12242 }
12243 if (mHistoryCur.batteryHealth != health) {
12244 mHistoryCur.batteryHealth = (byte)health;
12245 changed = true;
12246 }
12247 if (mHistoryCur.batteryPlugType != plugType) {
12248 mHistoryCur.batteryPlugType = (byte)plugType;
12249 changed = true;
12250 }
12251 if (temp >= (mHistoryCur.batteryTemperature+10)
12252 || temp <= (mHistoryCur.batteryTemperature-10)) {
12253 mHistoryCur.batteryTemperature = (short)temp;
12254 changed = true;
12255 }
12256 if (volt > (mHistoryCur.batteryVoltage+20)
12257 || volt < (mHistoryCur.batteryVoltage-20)) {
12258 mHistoryCur.batteryVoltage = (char)volt;
12259 changed = true;
12260 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012261 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12262 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012263 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12264 // Only record discharges
12265 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12266 mDischargeCounter.addCountLocked(chargeDiff);
12267 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012268 if (isScreenDoze(mScreenState)) {
12269 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12270 }
Mike Ma15313c92017-11-15 17:58:21 -080012271 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12272 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12273 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12274 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12275 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012276 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012277 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012278 changed = true;
12279 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012280 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12281 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12282 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12283 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012284 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012285 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12286 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12287 modeBits, elapsedRealtime);
12288 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12289 modeBits, elapsedRealtime);
12290 mLastDischargeStepLevel = level;
12291 mMinDischargeStepLevel = level;
12292 mInitStepMode = mCurStepMode;
12293 mModStepMode = 0;
12294 }
12295 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012296 if (level >= 90) {
12297 // If the battery level is at least 90%, always consider the device to be
12298 // charging even if it happens to go down a level.
12299 changed |= setChargingLocked(true);
12300 mLastChargeStepLevel = level;
12301 } if (!mCharging) {
12302 if (mLastChargeStepLevel < level) {
12303 // We have not reporting that we are charging, but the level has now
12304 // gone up, so consider the state to be charging.
12305 changed |= setChargingLocked(true);
12306 mLastChargeStepLevel = level;
12307 }
12308 } else {
12309 if (mLastChargeStepLevel > level) {
12310 // We had reported that the device was charging, but here we are with
12311 // power connected and the level going down. Looks like the current
12312 // power supplied isn't enough, so consider the device to now be
12313 // discharging.
12314 changed |= setChargingLocked(false);
12315 mLastChargeStepLevel = level;
12316 }
12317 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012318 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12319 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12320 modeBits, elapsedRealtime);
12321 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12322 modeBits, elapsedRealtime);
12323 mLastChargeStepLevel = level;
12324 mMaxChargeStepLevel = level;
12325 mInitStepMode = mCurStepMode;
12326 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012327 }
12328 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012329 if (changed) {
12330 addHistoryRecordLocked(elapsedRealtime, uptime);
12331 }
Evan Millarc64edde2009-04-18 12:26:32 -070012332 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012333 if (!onBattery &&
12334 (status == BatteryManager.BATTERY_STATUS_FULL ||
12335 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12336 // We don't record history while we are plugged in and fully charged
12337 // (or when battery is not present). The next time we are
12338 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012339 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012340 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012341
Jocelyn Dangc627d102017-04-14 13:15:14 -070012342 if (mMinLearnedBatteryCapacity == -1) {
12343 mMinLearnedBatteryCapacity = chargeFullUAh;
12344 } else {
12345 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012346 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012347 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012348 }
12349
Bookatz8c6571b2017-10-24 15:04:41 -070012350 // Inform StatsLog of setBatteryState changes.
12351 // If this is the first reporting, pass in recentPast == null.
12352 private void reportChangesToStatsLog(HistoryItem recentPast,
12353 final int status, final int plugType, final int level, final int temp) {
12354
12355 if (recentPast == null || recentPast.batteryStatus != status) {
12356 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12357 }
12358 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12359 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12360 }
12361 if (recentPast == null || recentPast.batteryLevel != level) {
12362 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12363 }
12364 // Let's just always print the temperature, regardless of whether it changed.
12365 StatsLog.write(StatsLog.DEVICE_TEMPERATURE_REPORTED, temp);
12366 }
12367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012368 public long getAwakeTimeBattery() {
12369 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12370 }
12371
12372 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012373 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012374 }
12375
12376 @Override
12377 public long computeUptime(long curTime, int which) {
12378 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012379 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012380 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012381 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012382 }
12383 return 0;
12384 }
12385
12386 @Override
12387 public long computeRealtime(long curTime, int which) {
12388 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012389 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012390 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012391 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012392 }
12393 return 0;
12394 }
12395
12396 @Override
12397 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012398 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012399 }
12400
12401 @Override
12402 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012403 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012404 }
12405
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012406 @Override
12407 public long computeBatteryScreenOffUptime(long curTime, int which) {
12408 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12409 }
12410
12411 @Override
12412 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12413 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012414 }
12415
Dianne Hackborn260c5022014-04-29 11:23:16 -070012416 private long computeTimePerLevel(long[] steps, int numSteps) {
12417 // For now we'll do a simple average across all steps.
12418 if (numSteps <= 0) {
12419 return -1;
12420 }
12421 long total = 0;
12422 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012423 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012424 }
12425 return total / numSteps;
12426 /*
12427 long[] buckets = new long[numSteps];
12428 int numBuckets = 0;
12429 int numToAverage = 4;
12430 int i = 0;
12431 while (i < numSteps) {
12432 long totalTime = 0;
12433 int num = 0;
12434 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012435 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012436 num++;
12437 }
12438 buckets[numBuckets] = totalTime / num;
12439 numBuckets++;
12440 numToAverage *= 2;
12441 i += num;
12442 }
12443 if (numBuckets < 1) {
12444 return -1;
12445 }
12446 long averageTime = buckets[numBuckets-1];
12447 for (i=numBuckets-2; i>=0; i--) {
12448 averageTime = (averageTime + buckets[i]) / 2;
12449 }
12450 return averageTime;
12451 */
12452 }
12453
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012454 @Override
12455 public long computeBatteryTimeRemaining(long curTime) {
12456 if (!mOnBattery) {
12457 return -1;
12458 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012459 /* Simple implementation just looks at the average discharge per level across the
12460 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012461 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12462 if (discharge < 2) {
12463 return -1;
12464 }
12465 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12466 if (duration < 1000*1000) {
12467 return -1;
12468 }
12469 long usPerLevel = duration/discharge;
12470 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012471 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012472 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012473 return -1;
12474 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012475 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012476 if (msPerLevel <= 0) {
12477 return -1;
12478 }
12479 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012480 }
12481
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012482 @Override
12483 public LevelStepTracker getDischargeLevelStepTracker() {
12484 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012485 }
12486
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012487 @Override
12488 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12489 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012490 }
12491
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012492 @Override
12493 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012494 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012495 // Not yet working.
12496 return -1;
12497 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012498 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012499 int curLevel = mCurrentBatteryLevel;
12500 int plugLevel = mDischargePlugLevel;
12501 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12502 return -1;
12503 }
12504 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12505 if (duration < 1000*1000) {
12506 return -1;
12507 }
12508 long usPerLevel = duration/(curLevel-plugLevel);
12509 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012510 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012511 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012512 return -1;
12513 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012514 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012515 if (msPerLevel <= 0) {
12516 return -1;
12517 }
12518 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012519 }
12520
Siddharth Raya1fd0572017-11-13 14:20:47 -080012521 /*@hide */
12522 public CellularBatteryStats getCellularBatteryStats() {
12523 CellularBatteryStats s = new CellularBatteryStats();
12524 final int which = STATS_SINCE_CHARGED;
12525 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12526 final ControllerActivityCounter counter = getModemControllerActivity();
12527 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12528 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12529 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12530 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12531 for (int i = 0; i < timeInRatMs.length; i++) {
12532 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12533 }
12534 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12535 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12536 timeInRxSignalStrengthLevelMs[i]
12537 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12538 }
12539 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12540 counter.getTxTimeCounters().length)];
12541 long totalTxTimeMs = 0;
12542 for (int i = 0; i < txTimeMs.length; i++) {
12543 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12544 totalTxTimeMs += txTimeMs[i];
12545 }
12546 final long totalControllerActivityTimeMs
12547 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12548 final long sleepTimeMs
12549 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + totalTxTimeMs);
12550 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12551 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12552 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12553 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12554 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12555 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
12556 s.setSleepTimeMs(sleepTimeMs);
12557 s.setIdleTimeMs(idleTimeMs);
12558 s.setRxTimeMs(rxTimeMs);
12559 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12560 s.setTimeInRatMs(timeInRatMs);
12561 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
12562 s.setTxTimeMs(txTimeMs);
12563 return s;
12564 }
12565
Siddharth Rayb50a6842017-12-14 15:15:28 -080012566 /*@hide */
12567 public WifiBatteryStats getWifiBatteryStats() {
12568 WifiBatteryStats s = new WifiBatteryStats();
12569 final int which = STATS_SINCE_CHARGED;
12570 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12571 final ControllerActivityCounter counter = getWifiControllerActivity();
12572 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12573 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
12574 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12575 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
12576 final long totalControllerActivityTimeMs
12577 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12578 final long sleepTimeMs
12579 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
12580 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12581 long numAppScanRequest = 0;
12582 for (int i = 0; i < mUidStats.size(); i++) {
12583 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
12584 }
12585 long[] timeInStateMs = new long[NUM_WIFI_STATES];
12586 for (int i=0; i<NUM_WIFI_STATES; i++) {
12587 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
12588 }
12589 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
12590 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12591 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
12592 }
12593 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
12594 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12595 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
12596 }
12597 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12598 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
12599 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
12600 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
12601 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
12602 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
12603 s.setSleepTimeMs(sleepTimeMs);
12604 s.setIdleTimeMs(idleTimeMs);
12605 s.setRxTimeMs(rxTimeMs);
12606 s.setTxTimeMs(txTimeMs);
12607 s.setScanTimeMs(scanTimeMs);
12608 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12609 s.setNumAppScanRequest(numAppScanRequest);
12610 s.setTimeInStateMs(timeInStateMs);
12611 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
12612 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
12613 return s;
12614 }
12615
Siddharth Ray78ccaf52017-12-23 16:16:21 -080012616 /*@hide */
12617 public GpsBatteryStats getGpsBatteryStats() {
12618 GpsBatteryStats s = new GpsBatteryStats();
12619 final int which = STATS_SINCE_CHARGED;
12620 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12621 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12622 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
12623 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
12624 for (int i=0; i<time.length; i++) {
12625 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
12626 }
12627 s.setTimeInGpsSignalQualityLevel(time);
12628 return s;
12629 }
12630
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012631 @Override
12632 public LevelStepTracker getChargeLevelStepTracker() {
12633 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012634 }
12635
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012636 @Override
12637 public LevelStepTracker getDailyChargeLevelStepTracker() {
12638 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012639 }
12640
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012641 @Override
12642 public ArrayList<PackageChange> getDailyPackageChanges() {
12643 return mDailyPackageChanges;
12644 }
12645
Joe Onoratoe1acd632016-02-23 13:25:10 -080012646 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012647 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012648 }
12649
12650 @Override
12651 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012652 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012653 }
12654
12655 @Override
12656 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012657 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012658 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070012659
The Android Open Source Project10592532009-03-18 17:39:46 -070012660 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012661 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012662 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012663 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012664 }
12665 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012666
Evan Millar633a1742009-04-02 16:36:33 -070012667 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012668 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012669 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012670
The Android Open Source Project10592532009-03-18 17:39:46 -070012671 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012672 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012673 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012674 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012675 }
12676 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012677
Evan Millar633a1742009-04-02 16:36:33 -070012678 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012679 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012681
Amith Yamasanie43530a2009-08-21 13:11:37 -070012682 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012683 public int getLowDischargeAmountSinceCharge() {
12684 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012685 int val = mLowDischargeAmountSinceCharge;
12686 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12687 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
12688 }
12689 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012690 }
12691 }
12692
12693 @Override
12694 public int getHighDischargeAmountSinceCharge() {
12695 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012696 int val = mHighDischargeAmountSinceCharge;
12697 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12698 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
12699 }
12700 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012701 }
12702 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012703
12704 @Override
12705 public int getDischargeAmount(int which) {
12706 int dischargeAmount = which == STATS_SINCE_CHARGED
12707 ? getHighDischargeAmountSinceCharge()
12708 : (getDischargeStartLevel() - getDischargeCurrentLevel());
12709 if (dischargeAmount < 0) {
12710 dischargeAmount = 0;
12711 }
12712 return dischargeAmount;
12713 }
12714
Mike Mac2f518a2017-09-19 16:06:03 -070012715 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012716 public int getDischargeAmountScreenOn() {
12717 synchronized(this) {
12718 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070012719 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012720 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12721 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12722 }
12723 return val;
12724 }
12725 }
12726
Mike Mac2f518a2017-09-19 16:06:03 -070012727 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012728 public int getDischargeAmountScreenOnSinceCharge() {
12729 synchronized(this) {
12730 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070012731 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012732 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12733 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12734 }
12735 return val;
12736 }
12737 }
12738
Mike Mac2f518a2017-09-19 16:06:03 -070012739 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012740 public int getDischargeAmountScreenOff() {
12741 synchronized(this) {
12742 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070012743 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012744 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12745 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12746 }
Mike Mac2f518a2017-09-19 16:06:03 -070012747 // For backward compatibility, doze discharge is counted into screen off.
12748 return val + getDischargeAmountScreenDoze();
12749 }
12750 }
12751
12752 @Override
12753 public int getDischargeAmountScreenOffSinceCharge() {
12754 synchronized(this) {
12755 int val = mDischargeAmountScreenOffSinceCharge;
12756 if (mOnBattery && isScreenOff(mScreenState)
12757 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12758 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12759 }
12760 // For backward compatibility, doze discharge is counted into screen off.
12761 return val + getDischargeAmountScreenDozeSinceCharge();
12762 }
12763 }
12764
12765 @Override
12766 public int getDischargeAmountScreenDoze() {
12767 synchronized(this) {
12768 int val = mDischargeAmountScreenDoze;
12769 if (mOnBattery && isScreenDoze(mScreenState)
12770 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
12771 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
12772 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012773 return val;
12774 }
12775 }
12776
Mike Mac2f518a2017-09-19 16:06:03 -070012777 @Override
12778 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012779 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070012780 int val = mDischargeAmountScreenDozeSinceCharge;
12781 if (mOnBattery && isScreenDoze(mScreenState)
12782 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
12783 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012784 }
12785 return val;
12786 }
12787 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012789 /**
12790 * Retrieve the statistics object for a particular uid, creating if needed.
12791 */
12792 public Uid getUidStatsLocked(int uid) {
12793 Uid u = mUidStats.get(uid);
12794 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080012795 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012796 mUidStats.put(uid, u);
12797 }
12798 return u;
12799 }
12800
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012801 /**
12802 * Retrieve the statistics object for a particular uid. Returns null if the object is not
12803 * available.
12804 */
12805 public Uid getAvailableUidStatsLocked(int uid) {
12806 Uid u = mUidStats.get(uid);
12807 return u;
12808 }
12809
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012810 public void onCleanupUserLocked(int userId) {
12811 final int firstUidForUser = UserHandle.getUid(userId, 0);
12812 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
12813 mKernelUidCpuFreqTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
12814 mKernelUidCpuTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012815 if (mKernelSingleUidTimeReader != null) {
12816 mKernelSingleUidTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
12817 }
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012818 }
12819
12820 public void onUserRemovedLocked(int userId) {
12821 final int firstUidForUser = UserHandle.getUid(userId, 0);
12822 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
12823 mUidStats.put(firstUidForUser, null);
12824 mUidStats.put(lastUidForUser, null);
12825 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
12826 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
12827 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
12828 }
12829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012830 /**
12831 * Remove the statistics object for a particular uid.
12832 */
12833 public void removeUidStatsLocked(int uid) {
Adam Lesinskib83ffee2015-05-12 14:43:47 -070012834 mKernelUidCpuTimeReader.removeUid(uid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -070012835 mKernelUidCpuFreqTimeReader.removeUid(uid);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012836 if (mKernelSingleUidTimeReader != null) {
12837 mKernelSingleUidTimeReader.removeUid(uid);
12838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012839 mUidStats.remove(uid);
12840 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070012841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012842 /**
12843 * Retrieve the statistics object for a particular process, creating
12844 * if needed.
12845 */
12846 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012847 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012848 Uid u = getUidStatsLocked(uid);
12849 return u.getProcessStatsLocked(name);
12850 }
12851
12852 /**
12853 * Retrieve the statistics object for a particular process, creating
12854 * if needed.
12855 */
12856 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012857 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012858 Uid u = getUidStatsLocked(uid);
12859 return u.getPackageStatsLocked(pkg);
12860 }
12861
12862 /**
12863 * Retrieve the statistics object for a particular service, creating
12864 * if needed.
12865 */
12866 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012867 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012868 Uid u = getUidStatsLocked(uid);
12869 return u.getServiceStatsLocked(pkg, name);
12870 }
12871
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012872 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012873 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012874 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012875 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012876 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012877
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012878 public boolean trackPerProcStateCpuTimes() {
12879 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
12880 }
12881
12882 public void systemServicesReady(Context context) {
12883 mConstants.startObserving(context.getContentResolver());
12884 }
12885
12886 @VisibleForTesting
12887 public final class Constants extends ContentObserver {
12888 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
12889 = "track_cpu_times_by_proc_state";
12890
12891 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
12892
12893 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
12894
12895 private ContentResolver mResolver;
12896 private final KeyValueListParser mParser = new KeyValueListParser(',');
12897
12898 public Constants(Handler handler) {
12899 super(handler);
12900 }
12901
12902 public void startObserving(ContentResolver resolver) {
12903 mResolver = resolver;
12904 mResolver.registerContentObserver(
12905 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
12906 false /* notifyForDescendants */, this);
12907 updateConstants();
12908 }
12909
12910 @Override
12911 public void onChange(boolean selfChange, Uri uri) {
12912 updateConstants();
12913 }
12914
12915 private void updateConstants() {
12916 synchronized (BatteryStatsImpl.this) {
12917 try {
12918 mParser.setString(Settings.Global.getString(mResolver,
12919 Settings.Global.BATTERY_STATS_CONSTANTS));
12920 } catch (IllegalArgumentException e) {
12921 // Failed to parse the settings string, log this and move on
12922 // with defaults.
12923 Slog.e(TAG, "Bad batterystats settings", e);
12924 }
12925
12926 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
12927 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
12928 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
12929 }
12930 }
12931
12932 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
12933 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
12934 if (isEnabled && !wasEnabled) {
12935 mKernelSingleUidTimeReader.markDataAsStale(true);
12936 mExternalSync.scheduleCpuSyncDueToSettingChange();
12937 }
12938 }
12939
12940 public void dumpLocked(PrintWriter pw) {
12941 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
12942 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
12943 }
12944 }
12945
12946 public void dumpConstantsLocked(PrintWriter pw) {
12947 mConstants.dumpLocked(pw);
12948 }
12949
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012950 Parcel mPendingWrite = null;
12951 final ReentrantLock mWriteLock = new ReentrantLock();
12952
12953 public void writeAsyncLocked() {
12954 writeLocked(false);
12955 }
12956
12957 public void writeSyncLocked() {
12958 writeLocked(true);
12959 }
12960
12961 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012962 if (mFile == null) {
12963 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012964 return;
12965 }
12966
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012967 if (mShuttingDown) {
12968 return;
12969 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012970
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012971 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012972 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080012973 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012974
12975 if (mPendingWrite != null) {
12976 mPendingWrite.recycle();
12977 }
12978 mPendingWrite = out;
12979
12980 if (sync) {
12981 commitPendingDataToDisk();
12982 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012983 BackgroundThread.getHandler().post(new Runnable() {
12984 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012985 commitPendingDataToDisk();
12986 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012987 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012988 }
12989 }
12990
12991 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070012992 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012993 synchronized (this) {
12994 next = mPendingWrite;
12995 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070012996 if (next == null) {
12997 return;
12998 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012999 }
13000
Amith Yamasanid2450862017-02-07 15:58:24 -080013001 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013002 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013003 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013004 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013005 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013006 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013007 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013008 mFile.commit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013009 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013010 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013011 mFile.rollback();
13012 } finally {
13013 next.recycle();
13014 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013016 }
13017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013018 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013019 if (mDailyFile != null) {
13020 readDailyStatsLocked();
13021 }
13022
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013023 if (mFile == null) {
13024 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013025 return;
13026 }
13027
13028 mUidStats.clear();
13029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013030 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013031 File file = mFile.chooseForRead();
13032 if (!file.exists()) {
13033 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013034 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013035 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013036
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013037 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013038 Parcel in = Parcel.obtain();
13039 in.unmarshall(raw, 0, raw.length);
13040 in.setDataPosition(0);
13041 stream.close();
13042
13043 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013044 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013045 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013046 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013047 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013048
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013049 mEndPlatformVersion = Build.ID;
13050
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013051 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013052 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013053 final long elapsedRealtime = mClocks.elapsedRealtime();
13054 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013055 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013056 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013057 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013058 addHistoryBufferLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
13059 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013060 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013061
13062 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063 }
13064
13065 public int describeContents() {
13066 return 0;
13067 }
13068
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013069 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013070 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013071
13072 mHistoryBuffer.setDataSize(0);
13073 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013074 mHistoryTagPool.clear();
13075 mNextHistoryTagIdx = 0;
13076 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013077
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013078 int numTags = in.readInt();
13079 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013080 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013081 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013082 if (str == null) {
13083 throw new ParcelFormatException("null history tag string");
13084 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013085 int uid = in.readInt();
13086 HistoryTag tag = new HistoryTag();
13087 tag.string = str;
13088 tag.uid = uid;
13089 tag.poolIdx = idx;
13090 mHistoryTagPool.put(tag, idx);
13091 if (idx >= mNextHistoryTagIdx) {
13092 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013093 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013094 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013095 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013096
13097 int bufSize = in.readInt();
13098 int curPos = in.dataPosition();
13099 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013100 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13101 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013102 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013103 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13104 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013105 } else {
13106 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13107 + " bytes at " + curPos);
13108 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13109 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013110 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013111
Dianne Hackbornae384452011-06-28 12:33:48 -070013112 if (andOldHistory) {
13113 readOldHistory(in);
13114 }
13115
13116 if (DEBUG_HISTORY) {
13117 StringBuilder sb = new StringBuilder(128);
13118 sb.append("****************** OLD mHistoryBaseTime: ");
13119 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13120 Slog.i(TAG, sb.toString());
13121 }
13122 mHistoryBaseTime = historyBaseTime;
13123 if (DEBUG_HISTORY) {
13124 StringBuilder sb = new StringBuilder(128);
13125 sb.append("****************** NEW mHistoryBaseTime: ");
13126 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13127 Slog.i(TAG, sb.toString());
13128 }
13129
13130 // We are just arbitrarily going to insert 1 minute from the sample of
13131 // the last run until samples in this run.
13132 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013133 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013134 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013135 if (DEBUG_HISTORY) {
13136 StringBuilder sb = new StringBuilder(128);
13137 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13138 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13139 Slog.i(TAG, sb.toString());
13140 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013141 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013142 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013143
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013144 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013145 if (!USE_OLD_HISTORY) {
13146 return;
13147 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013148 mHistory = mHistoryEnd = mHistoryCache = null;
13149 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013150 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013151 HistoryItem rec = new HistoryItem(time, in);
13152 addHistoryRecordLocked(rec);
13153 }
13154 }
13155
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013156 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013157 if (DEBUG_HISTORY) {
13158 StringBuilder sb = new StringBuilder(128);
13159 sb.append("****************** WRITING mHistoryBaseTime: ");
13160 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013161 sb.append(" mLastHistoryElapsedRealtime: ");
13162 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013163 Slog.i(TAG, sb.toString());
13164 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013165 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013166 if (!inclData) {
13167 out.writeInt(0);
13168 out.writeInt(0);
13169 return;
13170 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013171 out.writeInt(mHistoryTagPool.size());
13172 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13173 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013174 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013175 out.writeString(tag.string);
13176 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013177 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013178 out.writeInt(mHistoryBuffer.dataSize());
13179 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13180 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13181 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013182
13183 if (andOldHistory) {
13184 writeOldHistory(out);
13185 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013186 }
13187
13188 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013189 if (!USE_OLD_HISTORY) {
13190 return;
13191 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013192 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013193 while (rec != null) {
13194 if (rec.time >= 0) rec.writeToParcel(out, 0);
13195 rec = rec.next;
13196 }
13197 out.writeLong(-1);
13198 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013199
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013200 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013201 final int version = in.readInt();
13202 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013203 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013204 + ", expected " + VERSION + "; erasing old stats");
13205 return;
13206 }
13207
Dianne Hackbornae384452011-06-28 12:33:48 -070013208 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013210 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013211 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013212 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013213 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013214 mStartPlatformVersion = in.readString();
13215 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013216 mOnBatteryTimeBase.readSummaryFromParcel(in);
13217 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013218 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013219 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013220 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013221 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013222 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013223 mMinLearnedBatteryCapacity = in.readInt();
13224 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013225 mLowDischargeAmountSinceCharge = in.readInt();
13226 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013227 mDischargeAmountScreenOnSinceCharge = in.readInt();
13228 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013229 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013230 mDischargeStepTracker.readFromParcel(in);
13231 mChargeStepTracker.readFromParcel(in);
13232 mDailyDischargeStepTracker.readFromParcel(in);
13233 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013234 mDischargeCounter.readSummaryFromParcelLocked(in);
13235 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013236 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013237 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13238 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013239 int NPKG = in.readInt();
13240 if (NPKG > 0) {
13241 mDailyPackageChanges = new ArrayList<>(NPKG);
13242 while (NPKG > 0) {
13243 NPKG--;
13244 PackageChange pc = new PackageChange();
13245 pc.mPackageName = in.readString();
13246 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013247 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013248 mDailyPackageChanges.add(pc);
13249 }
13250 } else {
13251 mDailyPackageChanges = null;
13252 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013253 mDailyStartTime = in.readLong();
13254 mNextMinDailyDeadline = in.readLong();
13255 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013257 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013258
Jeff Browne95c3cd2014-05-02 16:59:26 -070013259 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013260 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013261 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013262 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13263 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13264 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013265 mInteractive = false;
13266 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013267 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013268 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013269 mLongestLightIdleTime = in.readLong();
13270 mLongestFullIdleTime = in.readLong();
13271 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13272 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13273 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013274 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013275 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013276 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013277 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13278 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013279 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013280 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13281 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13282 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013283 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013284 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13285 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013286 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013287 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013288 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013289 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013290 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013291 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13292 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013293 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013294 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013295 mWifiOn = false;
13296 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013297 mGlobalWifiRunning = false;
13298 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013299 for (int i=0; i<NUM_WIFI_STATES; i++) {
13300 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13301 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013302 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13303 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13304 }
13305 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13306 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13307 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013308 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13309 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013310 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13311 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13312 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013313 mBluetoothActivity.readSummaryFromParcel(in);
13314 mModemActivity.readSummaryFromParcel(in);
13315 mHasWifiReporting = in.readInt() != 0;
13316 mHasBluetoothReporting = in.readInt() != 0;
13317 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013318
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013319 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013320 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013321 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013322 mCameraOnNesting = 0;
13323 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013324 mBluetoothScanNesting = 0;
13325 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013326
Bookatz50df7112017-08-04 14:53:26 -070013327 int NRPMS = in.readInt();
13328 if (NRPMS > 10000) {
13329 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13330 }
13331 for (int irpm = 0; irpm < NRPMS; irpm++) {
13332 if (in.readInt() != 0) {
13333 String rpmName = in.readString();
13334 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13335 }
13336 }
13337 int NSORPMS = in.readInt();
13338 if (NSORPMS > 10000) {
13339 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13340 }
13341 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13342 if (in.readInt() != 0) {
13343 String rpmName = in.readString();
13344 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13345 }
13346 }
13347
Evan Millarc64edde2009-04-18 12:26:32 -070013348 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013349 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013350 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013351 }
Evan Millarc64edde2009-04-18 12:26:32 -070013352 for (int ikw = 0; ikw < NKW; ikw++) {
13353 if (in.readInt() != 0) {
13354 String kwltName = in.readString();
13355 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13356 }
13357 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013358
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013359 int NWR = in.readInt();
13360 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013361 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013362 }
13363 for (int iwr = 0; iwr < NWR; iwr++) {
13364 if (in.readInt() != 0) {
13365 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013366 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013367 }
13368 }
13369
James Carr3a226052016-07-01 14:49:52 -070013370 int NMS = in.readInt();
13371 for (int ims = 0; ims < NMS; ims++) {
13372 if (in.readInt() != 0) {
13373 long kmstName = in.readLong();
13374 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13375 }
13376 }
13377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013378 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013379 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013380 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013382 for (int iu = 0; iu < NU; iu++) {
13383 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013384 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013385 mUidStats.put(uid, u);
13386
Bookatz867c0d72017-03-07 18:23:42 -080013387 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013388 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013389
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013390 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013391 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013392 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013393 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013394 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013395 if (in.readInt() != 0) {
13396 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13397 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013398 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013399 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013400 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013401 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013402 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13403 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13404 if (in.readInt() != 0) {
13405 u.makeWifiBatchedScanBin(i, null);
13406 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13407 }
13408 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013409 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013410 if (in.readInt() != 0) {
13411 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13412 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013413 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013414 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013415 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013416 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013417 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13418 }
13419 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013420 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13421 }
13422 if (in.readInt() != 0) {
13423 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13424 }
13425 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013426 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13427 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013428 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013429 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13430 }
13431 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013432 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13433 }
13434 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013435 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13436 }
Bookatz956f36bf2017-04-28 09:48:17 -070013437 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013438 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13439 }
13440 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013441 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13442 }
Bookatzb1f04f32017-05-19 13:57:32 -070013443 if (in.readInt() != 0) {
13444 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13445 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013446 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013447 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13448 if (in.readInt() != 0) {
13449 u.makeProcessState(i, null);
13450 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13451 }
13452 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013453 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013454 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013455 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013456
Dianne Hackborn617f8772009-03-31 15:04:46 -070013457 if (in.readInt() != 0) {
13458 if (u.mUserActivityCounters == null) {
13459 u.initUserActivityLocked();
13460 }
13461 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13462 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13463 }
13464 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013465
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013466 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013467 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013468 u.initNetworkActivityLocked();
13469 }
13470 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013471 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13472 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013473 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013474 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13475 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013476 }
13477
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013478 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13479 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13480
Adam Lesinski6832f392015-09-05 18:05:40 -070013481 if (in.readInt() != 0) {
13482 final int numClusters = in.readInt();
13483 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13484 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013485 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013486
Sudheer Shankaaf857412017-07-21 00:14:24 -070013487 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013488 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013489 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013490 final int NSB = in.readInt();
13491 if (mPowerProfile != null &&
13492 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13493 throw new ParcelFormatException("File corrupt: too many speed bins " +
13494 NSB);
13495 }
13496
Sudheer Shankaaf857412017-07-21 00:14:24 -070013497 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070013498 for (int speed = 0; speed < NSB; speed++) {
13499 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013500 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070013501 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013502 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070013503 }
13504 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070013505 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013506 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070013507 }
13508 }
13509 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013510 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013511 }
13512
Sudheer Shanka59f5c002017-05-15 10:57:15 -070013513 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13514 in, mOnBatteryTimeBase);
13515 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13516 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070013517
13518 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
13519 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
13520
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013521 int length = in.readInt();
13522 if (length == Uid.NUM_PROCESS_STATE) {
13523 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
13524 for (int procState = 0; procState < length; ++procState) {
13525 u.mProcStateTimeMs[procState]
13526 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13527 in, mOnBatteryTimeBase);
13528 }
13529 } else {
13530 u.mProcStateTimeMs = null;
13531 }
13532 length = in.readInt();
13533 if (length == Uid.NUM_PROCESS_STATE) {
13534 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
13535 for (int procState = 0; procState < length; ++procState) {
13536 u.mProcStateScreenOffTimeMs[procState]
13537 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13538 in, mOnBatteryScreenOffTimeBase);
13539 }
13540 } else {
13541 u.mProcStateScreenOffTimeMs = null;
13542 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070013543
13544 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070013545 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13546 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
13547 } else {
13548 u.mMobileRadioApWakeupCount = null;
13549 }
13550
13551 if (in.readInt() != 0) {
13552 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13553 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
13554 } else {
13555 u.mWifiRadioApWakeupCount = null;
13556 }
13557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013558 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013559 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013560 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013562 for (int iw = 0; iw < NW; iw++) {
13563 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013564 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013565 }
13566
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013567 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013568 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013569 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013570 }
13571 for (int is = 0; is < NS; is++) {
13572 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013573 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013574 }
13575
13576 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013577 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013578 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013579 }
13580 for (int ij = 0; ij < NJ; ij++) {
13581 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013582 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013583 }
13584
Dianne Hackborn94326cb2017-06-28 16:17:20 -070013585 u.readJobCompletionsFromParcelLocked(in);
13586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013587 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013588 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013589 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013591 for (int is = 0; is < NP; is++) {
13592 int seNumber = in.readInt();
13593 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080013594 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013595 }
13596 }
13597
13598 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013599 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013600 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013602 for (int ip = 0; ip < NP; ip++) {
13603 String procName = in.readString();
13604 Uid.Proc p = u.getProcessStatsLocked(procName);
13605 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013606 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013607 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013609 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
13610 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013611 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013612 }
13613
13614 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013615 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013616 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013618 for (int ip = 0; ip < NP; ip++) {
13619 String pkgName = in.readString();
13620 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013621 final int NWA = in.readInt();
13622 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013623 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013624 }
13625 p.mWakeupAlarms.clear();
13626 for (int iwa=0; iwa<NWA; iwa++) {
13627 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070013628 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013629 c.readSummaryFromParcelLocked(in);
13630 p.mWakeupAlarms.put(tag, c);
13631 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013632 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013633 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013634 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013636 for (int is = 0; is < NS; is++) {
13637 String servName = in.readString();
13638 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
13639 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013640 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013641 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013642 }
13643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013644 }
13645 }
13646
13647 /**
13648 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
13649 * disk. This format does not allow a lossless round-trip.
13650 *
13651 * @param out the Parcel to be written to.
13652 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013653 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013654 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013655
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013656 // Pull the clock time. This may update the time and make a new history entry
13657 // if we had originally pulled a time before the RTC was set.
13658 long startClockTime = getStartClockTime();
13659
Joe Onoratoabded112016-02-08 16:49:39 -080013660 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
13661 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013662
13663 out.writeInt(VERSION);
13664
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013665 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013667 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013668 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013669 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013670 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013671 out.writeString(mStartPlatformVersion);
13672 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013673 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
13674 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013675 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013676 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070013677 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013678 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013679 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070013680 out.writeInt(mMinLearnedBatteryCapacity);
13681 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080013682 out.writeInt(getLowDischargeAmountSinceCharge());
13683 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013684 out.writeInt(getDischargeAmountScreenOnSinceCharge());
13685 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070013686 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013687 mDischargeStepTracker.writeToParcel(out);
13688 mChargeStepTracker.writeToParcel(out);
13689 mDailyDischargeStepTracker.writeToParcel(out);
13690 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070013691 mDischargeCounter.writeSummaryFromParcelLocked(out);
13692 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070013693 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080013694 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
13695 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013696 if (mDailyPackageChanges != null) {
13697 final int NPKG = mDailyPackageChanges.size();
13698 out.writeInt(NPKG);
13699 for (int i=0; i<NPKG; i++) {
13700 PackageChange pc = mDailyPackageChanges.get(i);
13701 out.writeString(pc.mPackageName);
13702 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070013703 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013704 }
13705 } else {
13706 out.writeInt(0);
13707 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013708 out.writeLong(mDailyStartTime);
13709 out.writeLong(mNextMinDailyDeadline);
13710 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013711
13712 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070013713 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013714 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013715 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013716 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013717 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013718 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013719 out.writeLong(mLongestLightIdleTime);
13720 out.writeLong(mLongestFullIdleTime);
13721 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13722 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13723 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013724 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013725 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080013726 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013727 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013728 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013729 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013730 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013731 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013732 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013733 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013734 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
13735 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013736 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013737 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13738 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013739 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013740 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
13741 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013742 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013743 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13744 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013745 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013746 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013747 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013748 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13749 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13750 }
13751 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13752 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13753 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013754 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13755 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013756 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13757 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13758 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013759 mBluetoothActivity.writeSummaryToParcel(out);
13760 mModemActivity.writeSummaryToParcel(out);
13761 out.writeInt(mHasWifiReporting ? 1 : 0);
13762 out.writeInt(mHasBluetoothReporting ? 1 : 0);
13763 out.writeInt(mHasModemReporting ? 1 : 0);
13764
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013765 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013766 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013767 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013768 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013769
Bookatz50df7112017-08-04 14:53:26 -070013770 out.writeInt(mRpmStats.size());
13771 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
13772 Timer rpmt = ent.getValue();
13773 if (rpmt != null) {
13774 out.writeInt(1);
13775 out.writeString(ent.getKey());
13776 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13777 } else {
13778 out.writeInt(0);
13779 }
13780 }
13781 out.writeInt(mScreenOffRpmStats.size());
13782 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
13783 Timer rpmt = ent.getValue();
13784 if (rpmt != null) {
13785 out.writeInt(1);
13786 out.writeString(ent.getKey());
13787 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13788 } else {
13789 out.writeInt(0);
13790 }
13791 }
13792
Evan Millarc64edde2009-04-18 12:26:32 -070013793 out.writeInt(mKernelWakelockStats.size());
13794 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
13795 Timer kwlt = ent.getValue();
13796 if (kwlt != null) {
13797 out.writeInt(1);
13798 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013799 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13800 } else {
13801 out.writeInt(0);
13802 }
13803 }
13804
13805 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013806 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
13807 SamplingTimer timer = ent.getValue();
13808 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013809 out.writeInt(1);
13810 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013811 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070013812 } else {
13813 out.writeInt(0);
13814 }
13815 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013816
James Carr3a226052016-07-01 14:49:52 -070013817 out.writeInt(mKernelMemoryStats.size());
13818 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
13819 Timer kmt = mKernelMemoryStats.valueAt(i);
13820 if (kmt != null) {
13821 out.writeInt(1);
13822 out.writeLong(mKernelMemoryStats.keyAt(i));
13823 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13824 } else {
13825 out.writeInt(0);
13826 }
13827 }
13828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013829 final int NU = mUidStats.size();
13830 out.writeInt(NU);
13831 for (int iu = 0; iu < NU; iu++) {
13832 out.writeInt(mUidStats.keyAt(iu));
13833 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013834
Bookatz867c0d72017-03-07 18:23:42 -080013835 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070013836 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080013837
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013838 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013839 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013840 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013841 } else {
13842 out.writeInt(0);
13843 }
13844 if (u.mFullWifiLockTimer != null) {
13845 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013846 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013847 } else {
13848 out.writeInt(0);
13849 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013850 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013851 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013852 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013853 } else {
13854 out.writeInt(0);
13855 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013856 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13857 if (u.mWifiBatchedScanTimer[i] != null) {
13858 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013859 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070013860 } else {
13861 out.writeInt(0);
13862 }
13863 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013864 if (u.mWifiMulticastTimer != null) {
13865 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013866 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013867 } else {
13868 out.writeInt(0);
13869 }
13870 if (u.mAudioTurnedOnTimer != null) {
13871 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013872 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013873 } else {
13874 out.writeInt(0);
13875 }
13876 if (u.mVideoTurnedOnTimer != null) {
13877 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013878 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013879 } else {
13880 out.writeInt(0);
13881 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013882 if (u.mFlashlightTurnedOnTimer != null) {
13883 out.writeInt(1);
13884 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13885 } else {
13886 out.writeInt(0);
13887 }
13888 if (u.mCameraTurnedOnTimer != null) {
13889 out.writeInt(1);
13890 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13891 } else {
13892 out.writeInt(0);
13893 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013894 if (u.mForegroundActivityTimer != null) {
13895 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013896 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013897 } else {
13898 out.writeInt(0);
13899 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013900 if (u.mForegroundServiceTimer != null) {
13901 out.writeInt(1);
13902 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13903 } else {
13904 out.writeInt(0);
13905 }
Bookatzc8c44962017-05-11 12:12:54 -070013906 if (u.mAggregatedPartialWakelockTimer != null) {
13907 out.writeInt(1);
13908 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13909 } else {
13910 out.writeInt(0);
13911 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013912 if (u.mBluetoothScanTimer != null) {
13913 out.writeInt(1);
13914 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13915 } else {
13916 out.writeInt(0);
13917 }
Bookatzb1f04f32017-05-19 13:57:32 -070013918 if (u.mBluetoothUnoptimizedScanTimer != null) {
13919 out.writeInt(1);
13920 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13921 } else {
13922 out.writeInt(0);
13923 }
Bookatz956f36bf2017-04-28 09:48:17 -070013924 if (u.mBluetoothScanResultCounter != null) {
13925 out.writeInt(1);
13926 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
13927 } else {
13928 out.writeInt(0);
13929 }
Bookatzb1f04f32017-05-19 13:57:32 -070013930 if (u.mBluetoothScanResultBgCounter != null) {
13931 out.writeInt(1);
13932 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
13933 } else {
13934 out.writeInt(0);
13935 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070013936 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13937 if (u.mProcessStateTimer[i] != null) {
13938 out.writeInt(1);
13939 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13940 } else {
13941 out.writeInt(0);
13942 }
13943 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013944 if (u.mVibratorOnTimer != null) {
13945 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013946 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013947 } else {
13948 out.writeInt(0);
13949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013950
Dianne Hackborn617f8772009-03-31 15:04:46 -070013951 if (u.mUserActivityCounters == null) {
13952 out.writeInt(0);
13953 } else {
13954 out.writeInt(1);
13955 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13956 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
13957 }
13958 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013959
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013960 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013961 out.writeInt(0);
13962 } else {
13963 out.writeInt(1);
13964 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013965 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
13966 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013967 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013968 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
13969 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013970 }
13971
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013972 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
13973 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
13974
Sudheer Shankaaf857412017-07-21 00:14:24 -070013975 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013976 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013977 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
13978 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013979 if (cpuSpeeds != null) {
13980 out.writeInt(1);
13981 out.writeInt(cpuSpeeds.length);
13982 for (LongSamplingCounter c : cpuSpeeds) {
13983 if (c != null) {
13984 out.writeInt(1);
13985 c.writeSummaryFromParcelLocked(out);
13986 } else {
13987 out.writeInt(0);
13988 }
13989 }
13990 } else {
13991 out.writeInt(0);
13992 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013993 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013994 } else {
13995 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013996 }
13997
Sudheer Shanka59f5c002017-05-15 10:57:15 -070013998 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
13999 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014000
Mike Ma3d422c32017-10-25 11:08:57 -070014001 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14002 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14003
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014004 if (u.mProcStateTimeMs != null) {
14005 out.writeInt(u.mProcStateTimeMs.length);
14006 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14007 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14008 }
14009 } else {
14010 out.writeInt(0);
14011 }
14012 if (u.mProcStateScreenOffTimeMs != null) {
14013 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14014 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14015 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14016 }
14017 } else {
14018 out.writeInt(0);
14019 }
14020
Adam Lesinski5f056f62016-07-14 16:56:08 -070014021 if (u.mMobileRadioApWakeupCount != null) {
14022 out.writeInt(1);
14023 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14024 } else {
14025 out.writeInt(0);
14026 }
14027
14028 if (u.mWifiRadioApWakeupCount != null) {
14029 out.writeInt(1);
14030 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14031 } else {
14032 out.writeInt(0);
14033 }
14034
Dianne Hackbornd953c532014-08-16 18:17:38 -070014035 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14036 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014037 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014038 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014039 out.writeString(wakeStats.keyAt(iw));
14040 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014041 if (wl.mTimerFull != null) {
14042 out.writeInt(1);
14043 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14044 } else {
14045 out.writeInt(0);
14046 }
14047 if (wl.mTimerPartial != null) {
14048 out.writeInt(1);
14049 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14050 } else {
14051 out.writeInt(0);
14052 }
14053 if (wl.mTimerWindow != null) {
14054 out.writeInt(1);
14055 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14056 } else {
14057 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014058 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014059 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014060 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014061 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014062 } else {
14063 out.writeInt(0);
14064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014065 }
14066
Bookatz2bffb5b2017-04-13 11:59:33 -070014067 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014068 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014069 out.writeInt(NS);
14070 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014071 out.writeString(syncStats.keyAt(is));
14072 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014073 }
14074
Bookatzaa4594a2017-03-24 12:39:56 -070014075 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014076 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014077 out.writeInt(NJ);
14078 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014079 out.writeString(jobStats.keyAt(ij));
14080 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014081 }
14082
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014083 u.writeJobCompletionsToParcelLocked(out);
14084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014085 int NSE = u.mSensorStats.size();
14086 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014087 for (int ise=0; ise<NSE; ise++) {
14088 out.writeInt(u.mSensorStats.keyAt(ise));
14089 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14090 if (se.mTimer != null) {
14091 out.writeInt(1);
14092 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14093 } else {
14094 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014095 }
14096 }
14097
14098 int NP = u.mProcessStats.size();
14099 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014100 for (int ip=0; ip<NP; ip++) {
14101 out.writeString(u.mProcessStats.keyAt(ip));
14102 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14103 out.writeLong(ps.mUserTime);
14104 out.writeLong(ps.mSystemTime);
14105 out.writeLong(ps.mForegroundTime);
14106 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014107 out.writeInt(ps.mNumCrashes);
14108 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014109 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014110 }
14111
14112 NP = u.mPackageStats.size();
14113 out.writeInt(NP);
14114 if (NP > 0) {
14115 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14116 : u.mPackageStats.entrySet()) {
14117 out.writeString(ent.getKey());
14118 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014119 final int NWA = ps.mWakeupAlarms.size();
14120 out.writeInt(NWA);
14121 for (int iwa=0; iwa<NWA; iwa++) {
14122 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14123 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14124 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014125 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014126 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014127 for (int is=0; is<NS; is++) {
14128 out.writeString(ps.mServiceStats.keyAt(is));
14129 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14130 long time = ss.getStartTimeToNowLocked(
14131 mOnBatteryTimeBase.getUptime(NOW_SYS));
14132 out.writeLong(time);
14133 out.writeInt(ss.mStarts);
14134 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014135 }
14136 }
14137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014138 }
14139 }
14140
14141 public void readFromParcel(Parcel in) {
14142 readFromParcelLocked(in);
14143 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014145 void readFromParcelLocked(Parcel in) {
14146 int magic = in.readInt();
14147 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014148 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014149 }
14150
Dianne Hackbornae384452011-06-28 12:33:48 -070014151 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014153 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014154 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014155 mStartPlatformVersion = in.readString();
14156 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014157 mUptime = in.readLong();
14158 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014159 mRealtime = in.readLong();
14160 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014161 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014162 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014163 mMinLearnedBatteryCapacity = in.readInt();
14164 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014165 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014166 mOnBatteryTimeBase.readFromParcel(in);
14167 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14168
Jeff Browne95c3cd2014-05-02 16:59:26 -070014169 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014170 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014171 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014172 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014173 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14174 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014175 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014176 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014177 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014178 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014179 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14180 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014181 mLongestLightIdleTime = in.readLong();
14182 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014183 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14184 mOnBatteryTimeBase, in);
14185 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14186 mOnBatteryTimeBase, in);
14187 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14188 mOnBatteryTimeBase, in);
14189 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14190 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014191 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014192 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014193 null, mOnBatteryTimeBase, in);
14194 }
Joe Onoratoabded112016-02-08 16:49:39 -080014195 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14196 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014197 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014198 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014199 null, mOnBatteryTimeBase, in);
14200 }
14201 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14202 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14203 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14204 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014205 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014206 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14207 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014208 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014209 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014210 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014211 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14212 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014213 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14214 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014215 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014216 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014217 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014218 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014219 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14220 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014221 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014222 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014223 null, mOnBatteryTimeBase, in);
14224 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014225 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014226 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014227 null, mOnBatteryTimeBase, in);
14228 }
14229 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014230 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014231 null, mOnBatteryTimeBase, in);
14232 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014233 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14234 mOnBatteryTimeBase, in);
14235 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14236 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014237 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14238 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14239 null, mOnBatteryTimeBase, in);
14240 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014241 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14242 NUM_BT_TX_LEVELS, in);
14243 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14244 ModemActivityInfo.TX_POWER_LEVELS, in);
14245 mHasWifiReporting = in.readInt() != 0;
14246 mHasBluetoothReporting = in.readInt() != 0;
14247 mHasModemReporting = in.readInt() != 0;
14248
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014249 mNumConnectivityChange = in.readInt();
14250 mLoadedNumConnectivityChange = in.readInt();
14251 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014252 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014253 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014254 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014255 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014256 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014257 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014258 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014259 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014260 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014261 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014262 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014263 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014264 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014265 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014266 mLowDischargeAmountSinceCharge = in.readInt();
14267 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014268 mDischargeAmountScreenOn = in.readInt();
14269 mDischargeAmountScreenOnSinceCharge = in.readInt();
14270 mDischargeAmountScreenOff = in.readInt();
14271 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014272 mDischargeAmountScreenDoze = in.readInt();
14273 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014274 mDischargeStepTracker.readFromParcel(in);
14275 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014276 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014277 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14278 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014279 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14280 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014281 mLastWriteTime = in.readLong();
14282
Bookatz50df7112017-08-04 14:53:26 -070014283 mRpmStats.clear();
14284 int NRPMS = in.readInt();
14285 for (int irpm = 0; irpm < NRPMS; irpm++) {
14286 if (in.readInt() != 0) {
14287 String rpmName = in.readString();
14288 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14289 mRpmStats.put(rpmName, rpmt);
14290 }
14291 }
14292 mScreenOffRpmStats.clear();
14293 int NSORPMS = in.readInt();
14294 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14295 if (in.readInt() != 0) {
14296 String rpmName = in.readString();
14297 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14298 mScreenOffRpmStats.put(rpmName, rpmt);
14299 }
14300 }
14301
Evan Millarc64edde2009-04-18 12:26:32 -070014302 mKernelWakelockStats.clear();
14303 int NKW = in.readInt();
14304 for (int ikw = 0; ikw < NKW; ikw++) {
14305 if (in.readInt() != 0) {
14306 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014307 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014308 mKernelWakelockStats.put(wakelockName, kwlt);
14309 }
14310 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014311
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014312 mWakeupReasonStats.clear();
14313 int NWR = in.readInt();
14314 for (int iwr = 0; iwr < NWR; iwr++) {
14315 if (in.readInt() != 0) {
14316 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014317 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014318 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014319 }
14320 }
14321
James Carr3a226052016-07-01 14:49:52 -070014322 mKernelMemoryStats.clear();
14323 int nmt = in.readInt();
14324 for (int imt = 0; imt < nmt; imt++) {
14325 if (in.readInt() != 0) {
14326 Long bucket = in.readLong();
14327 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14328 mKernelMemoryStats.put(bucket, kmt);
14329 }
14330 }
14331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014332 mPartialTimers.clear();
14333 mFullTimers.clear();
14334 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014335 mWifiRunningTimers.clear();
14336 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014337 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014338 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014339 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014340 mAudioTurnedOnTimers.clear();
14341 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014342 mFlashlightTurnedOnTimers.clear();
14343 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014344
14345 int numUids = in.readInt();
14346 mUidStats.clear();
14347 for (int i = 0; i < numUids; i++) {
14348 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014349 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014350 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014351 mUidStats.append(uid, u);
14352 }
14353 }
14354
14355 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014356 writeToParcelLocked(out, true, flags);
14357 }
14358
14359 public void writeToParcelWithoutUids(Parcel out, int flags) {
14360 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014361 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014362
14363 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014364 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014365 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014366 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014367
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014368 // Pull the clock time. This may update the time and make a new history entry
14369 // if we had originally pulled a time before the RTC was set.
14370 long startClockTime = getStartClockTime();
14371
Joe Onoratoabded112016-02-08 16:49:39 -080014372 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14373 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014374 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14375 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014377 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014378
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014379 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014381 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014382 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014383 out.writeString(mStartPlatformVersion);
14384 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014385 out.writeLong(mUptime);
14386 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014387 out.writeLong(mRealtime);
14388 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014389 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014390 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014391 out.writeInt(mMinLearnedBatteryCapacity);
14392 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014393 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14394 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14395
14396 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014397 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014398 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14399 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14400 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014401 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014402 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014403 out.writeLong(mLongestLightIdleTime);
14404 out.writeLong(mLongestFullIdleTime);
14405 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14406 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14407 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014408 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014409 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14410 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14411 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14412 }
14413 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14414 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14415 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14416 }
14417 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14418 mNetworkByteActivityCounters[i].writeToParcel(out);
14419 mNetworkPacketActivityCounters[i].writeToParcel(out);
14420 }
14421 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14422 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014423 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014424 mMobileRadioActiveUnknownTime.writeToParcel(out);
14425 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014426 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014427 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14428 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14429 for (int i=0; i<NUM_WIFI_STATES; i++) {
14430 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14431 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014432 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14433 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14434 }
14435 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14436 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14437 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014438 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
14439 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014440 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14441 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
14442 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014443 mBluetoothActivity.writeToParcel(out, 0);
14444 mModemActivity.writeToParcel(out, 0);
14445 out.writeInt(mHasWifiReporting ? 1 : 0);
14446 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14447 out.writeInt(mHasModemReporting ? 1 : 0);
14448
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014449 out.writeInt(mNumConnectivityChange);
14450 out.writeInt(mLoadedNumConnectivityChange);
14451 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014452 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014453 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014454 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014455 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014456 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014457 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014458 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014459 out.writeInt(mLowDischargeAmountSinceCharge);
14460 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014461 out.writeInt(mDischargeAmountScreenOn);
14462 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14463 out.writeInt(mDischargeAmountScreenOff);
14464 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014465 out.writeInt(mDischargeAmountScreenDoze);
14466 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014467 mDischargeStepTracker.writeToParcel(out);
14468 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014469 mDischargeCounter.writeToParcel(out);
14470 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014471 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080014472 mDischargeLightDozeCounter.writeToParcel(out);
14473 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014474 out.writeLong(mLastWriteTime);
14475
Bookatz50df7112017-08-04 14:53:26 -070014476 out.writeInt(mRpmStats.size());
14477 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14478 SamplingTimer rpmt = ent.getValue();
14479 if (rpmt != null) {
14480 out.writeInt(1);
14481 out.writeString(ent.getKey());
14482 rpmt.writeToParcel(out, uSecRealtime);
14483 } else {
14484 out.writeInt(0);
14485 }
14486 }
14487 out.writeInt(mScreenOffRpmStats.size());
14488 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14489 SamplingTimer rpmt = ent.getValue();
14490 if (rpmt != null) {
14491 out.writeInt(1);
14492 out.writeString(ent.getKey());
14493 rpmt.writeToParcel(out, uSecRealtime);
14494 } else {
14495 out.writeInt(0);
14496 }
14497 }
14498
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014499 if (inclUids) {
14500 out.writeInt(mKernelWakelockStats.size());
14501 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14502 SamplingTimer kwlt = ent.getValue();
14503 if (kwlt != null) {
14504 out.writeInt(1);
14505 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014506 kwlt.writeToParcel(out, uSecRealtime);
14507 } else {
14508 out.writeInt(0);
14509 }
14510 }
14511 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014512 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14513 SamplingTimer timer = ent.getValue();
14514 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014515 out.writeInt(1);
14516 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014517 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014518 } else {
14519 out.writeInt(0);
14520 }
Evan Millarc64edde2009-04-18 12:26:32 -070014521 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014522 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070014523 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014524 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070014525 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070014526
James Carr3a226052016-07-01 14:49:52 -070014527 out.writeInt(mKernelMemoryStats.size());
14528 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14529 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
14530 if (kmt != null) {
14531 out.writeInt(1);
14532 out.writeLong(mKernelMemoryStats.keyAt(i));
14533 kmt.writeToParcel(out, uSecRealtime);
14534 } else {
14535 out.writeInt(0);
14536 }
14537 }
14538
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014539 if (inclUids) {
14540 int size = mUidStats.size();
14541 out.writeInt(size);
14542 for (int i = 0; i < size; i++) {
14543 out.writeInt(mUidStats.keyAt(i));
14544 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014545
Bookatz867c0d72017-03-07 18:23:42 -080014546 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014547 }
14548 } else {
14549 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014550 }
14551 }
14552
14553 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
14554 new Parcelable.Creator<BatteryStatsImpl>() {
14555 public BatteryStatsImpl createFromParcel(Parcel in) {
14556 return new BatteryStatsImpl(in);
14557 }
14558
14559 public BatteryStatsImpl[] newArray(int size) {
14560 return new BatteryStatsImpl[size];
14561 }
14562 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014563
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014564 public void prepareForDumpLocked() {
14565 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014566 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014567
14568 // Pull the clock time. This may update the time and make a new history entry
14569 // if we had originally pulled a time before the RTC was set.
14570 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014571 }
14572
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014573 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014574 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014575 pw.println("mOnBatteryTimeBase:");
14576 mOnBatteryTimeBase.dump(pw, " ");
14577 pw.println("mOnBatteryScreenOffTimeBase:");
14578 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014579 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070014580 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014581 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070014582 pr.println("*** Screen doze timer:");
14583 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014584 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014585 pr.println("*** Screen brightness #" + i + ":");
14586 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014587 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014588 pr.println("*** Interactive timer:");
14589 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014590 pr.println("*** Power save mode timer:");
14591 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014592 pr.println("*** Device idle mode light timer:");
14593 mDeviceIdleModeLightTimer.logState(pr, " ");
14594 pr.println("*** Device idle mode full timer:");
14595 mDeviceIdleModeFullTimer.logState(pr, " ");
14596 pr.println("*** Device light idling timer:");
14597 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014598 pr.println("*** Device idling timer:");
14599 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014600 pr.println("*** Phone timer:");
14601 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080014602 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070014603 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014604 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014605 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070014606 pr.println("*** Signal scanning :");
14607 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014608 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014609 pr.println("*** Data connection type #" + i + ":");
14610 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014611 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014612 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080014613 pr.println("*** Mobile network active timer:");
14614 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014615 pr.println("*** Mobile network active adjusted timer:");
14616 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014617 pr.println("*** Wifi Multicast WakeLock Timer:");
14618 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014619 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014620 pr.println("*** Wifi timer:");
14621 mWifiOnTimer.logState(pr, " ");
14622 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014623 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014624 for (int i=0; i<NUM_WIFI_STATES; i++) {
14625 pr.println("*** Wifi state #" + i + ":");
14626 mWifiStateTimer[i].logState(pr, " ");
14627 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014628 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14629 pr.println("*** Wifi suppl state #" + i + ":");
14630 mWifiSupplStateTimer[i].logState(pr, " ");
14631 }
14632 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14633 pr.println("*** Wifi signal strength #" + i + ":");
14634 mWifiSignalStrengthsTimer[i].logState(pr, " ");
14635 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014636 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14637 pr.println("*** GPS signal quality #" + i + ":");
14638 mGpsSignalQualityTimer[i].logState(pr, " ");
14639 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014640 pr.println("*** Flashlight timer:");
14641 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014642 pr.println("*** Camera timer:");
14643 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014644 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014645 super.dumpLocked(context, pw, flags, reqUid, histStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014647}