blob: b8ff9e4e3ebc219bea46c886fecdd0618d69ca82 [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;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070037import android.os.FileUtils;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070038import android.os.Handler;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080039import android.os.IBatteryPropertiesRegistrar;
Jeff Brown6f357d32014-01-15 20:40:55 -080040import android.os.Looper;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070041import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.Parcel;
43import android.os.ParcelFormatException;
44import android.os.Parcelable;
Evan Millarc64edde2009-04-18 12:26:32 -070045import android.os.Process;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080046import android.os.RemoteException;
47import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.SystemClock;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070049import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070050import android.os.WorkSource;
Narayan Kamath81822022017-12-08 11:56:01 +000051import android.os.WorkSource.WorkChain;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080052import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070053import android.telephony.DataConnectionRealTimeInfo;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080054import android.telephony.ModemActivityInfo;
Amith Yamasanif37447b2009-10-08 18:28:01 -070055import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070056import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070057import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070058import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070059import android.util.ArrayMap;
Sudheer Shankab2f83c12017-11-13 19:25:01 -080060import android.util.IntArray;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080061import android.util.KeyValueListParser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070063import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070064import android.util.LongSparseArray;
65import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070066import android.util.MutableInt;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070067import android.util.Pools;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070068import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070070import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080072import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070073import android.util.SparseLongArray;
Bookatzc1a050a2017-10-10 15:49:28 -070074import android.util.StatsLog;
Dianne Hackbornae384452011-06-28 12:33:48 -070075import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080076import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070077import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078
Adam Lesinski14ae39a2017-05-26 11:50:40 -070079import com.android.internal.annotations.GuardedBy;
Adam Lesinski98f0d462016-04-19 16:46:20 -070080import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070081import com.android.internal.net.NetworkStatsFactory;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080082import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070083import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080084import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070085import com.android.internal.util.JournaledFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080086import com.android.internal.util.XmlUtils;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070087
Narayan Kamath81822022017-12-08 11:56:01 +000088import java.util.List;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070089import libcore.util.EmptyArray;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080090import org.xmlpull.v1.XmlPullParser;
91import org.xmlpull.v1.XmlPullParserException;
92import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070093
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080094import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.io.File;
96import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080097import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import java.io.FileOutputStream;
99import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700100import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100101import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import java.util.ArrayList;
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700103import java.util.Arrays;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800104import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.HashMap;
Evan Millarc64edde2009-04-18 12:26:32 -0700106import java.util.Iterator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.Map;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700108import java.util.concurrent.Future;
Christopher Tate4cee7252010-03-19 14:50:40 -0700109import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700110import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
112/**
113 * All information we are collecting about things that can happen that impact
114 * battery life. All times are represented in microseconds except where indicated
115 * otherwise.
116 */
Joe Onoratoabded112016-02-08 16:49:39 -0800117public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800119 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700120 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800121 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700122 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700123 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700124 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700125
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700126 // TODO: remove "tcp" from network methods, since we measure total stats.
127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700129 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130
131 // Current on-disk Parcel version
Sudheer Shankae544d162017-12-28 17:06:20 -0800132 private static final int VERSION = 173 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700133
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700134 // Maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100135 private static final int MAX_HISTORY_ITEMS;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700136
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700137 // No, really, THIS is the maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100138 private static final int MAX_MAX_HISTORY_ITEMS;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700139
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800140 // The maximum number of names wakelocks we will keep track of
141 // per uid; once the limit is reached, we batch the remaining wakelocks
142 // in to one common name.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100143 private static final int MAX_WAKELOCKS_PER_UID;
144
145 static final int MAX_HISTORY_BUFFER; // 256KB
146 static final int MAX_MAX_HISTORY_BUFFER; // 320KB
147
148 static {
149 if (ActivityManager.isLowRamDeviceStatic()) {
150 MAX_HISTORY_ITEMS = 800;
151 MAX_MAX_HISTORY_ITEMS = 1200;
152 MAX_WAKELOCKS_PER_UID = 40;
153 MAX_HISTORY_BUFFER = 96*1024; // 96KB
154 MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
155 } else {
156 MAX_HISTORY_ITEMS = 2000;
157 MAX_MAX_HISTORY_ITEMS = 3000;
158 MAX_WAKELOCKS_PER_UID = 100;
159 MAX_HISTORY_BUFFER = 256*1024; // 256KB
160 MAX_MAX_HISTORY_BUFFER = 320*1024; // 256KB
161 }
162 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700163
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800164 // Number of transmit power states the Wifi controller can be in.
165 private static final int NUM_WIFI_TX_LEVELS = 1;
166
167 // Number of transmit power states the Bluetooth controller can be in.
168 private static final int NUM_BT_TX_LEVELS = 1;
169
Sudheer Shanka38383232017-07-25 09:55:03 -0700170 /**
171 * Holding a wakelock costs more than just using the cpu.
172 * Currently, we assign only half the cpu time to an app that is running but
173 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
174 * If no app is holding a wakelock, then the distribution is normal.
175 */
176 @VisibleForTesting
177 public static final int WAKE_LOCK_WEIGHT = 50;
178
Joe Onoratoabded112016-02-08 16:49:39 -0800179 protected Clocks mClocks;
180
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700181 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700182 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800183 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700185 static final int MSG_UPDATE_WAKELOCKS = 1;
186 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700187 static final int MSG_REPORT_CHARGING = 3;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700188 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700189
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700190 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
191 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
192
Sudheer Shanka38383232017-07-25 09:55:03 -0700193 @VisibleForTesting
194 protected KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
195 @VisibleForTesting
196 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
197 @VisibleForTesting
198 protected KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700199 new KernelUidCpuFreqTimeReader();
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800200 @VisibleForTesting
201 protected KernelSingleUidTimeReader mKernelSingleUidTimeReader;
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700202
James Carr3a226052016-07-01 14:49:52 -0700203 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
204 = new KernelMemoryBandwidthStats();
205 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
206 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
207 return mKernelMemoryStats;
208 }
209
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800210 @GuardedBy("this")
211 public boolean mPerProcStateCpuTimesAvailable = true;
212
213 /**
214 * Uids for which per-procstate cpu times need to be updated.
215 *
216 * Contains uid -> procState mappings.
217 */
218 @GuardedBy("this")
219 @VisibleForTesting
220 protected final SparseIntArray mPendingUids = new SparseIntArray();
221
Bookatz0b8a0502017-09-13 11:51:52 -0700222 /** Container for Resource Power Manager stats. Updated by updateRpmStatsLocked. */
Bookatz50df7112017-08-04 14:53:26 -0700223 private final RpmStats mTmpRpmStats = new RpmStats();
Bookatz0b8a0502017-09-13 11:51:52 -0700224 /** The soonest the RPM stats can be updated after it was last updated. */
225 private static final long RPM_STATS_UPDATE_FREQ_MS = 1000;
226 /** Last time that RPM stats were updated by updateRpmStatsLocked. */
227 private long mLastRpmStatsUpdateTimeMs = -RPM_STATS_UPDATE_FREQ_MS;
Bookatz50df7112017-08-04 14:53:26 -0700228
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700229 public interface BatteryCallback {
230 public void batteryNeedsCpuUpdate();
231 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700232 public void batterySendBroadcast(Intent intent);
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700233 }
234
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700235 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700236 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700237 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000238 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700239 }
240
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700241 public static abstract class UserInfoProvider {
242 private int[] userIds;
243 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700244 @VisibleForTesting
245 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700246 userIds = getUserIds();
247 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700248 @VisibleForTesting
249 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700250 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
251 }
252 }
253
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700254 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
255
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700256 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800257 public MyHandler(Looper looper) {
258 super(looper, null, true);
259 }
260
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700261 @Override
262 public void handleMessage(Message msg) {
263 BatteryCallback cb = mCallback;
264 switch (msg.what) {
265 case MSG_UPDATE_WAKELOCKS:
Adam Lesinski72478f02015-06-17 15:39:43 -0700266 synchronized (BatteryStatsImpl.this) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -0700267 updateCpuTimeLocked();
Adam Lesinski72478f02015-06-17 15:39:43 -0700268 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700269 if (cb != null) {
270 cb.batteryNeedsCpuUpdate();
271 }
272 break;
273 case MSG_REPORT_POWER_CHANGE:
274 if (cb != null) {
275 cb.batteryPowerChanged(msg.arg1 != 0);
276 }
277 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700278 case MSG_REPORT_CHARGING:
279 if (cb != null) {
280 final String action;
281 synchronized (BatteryStatsImpl.this) {
282 action = mCharging ? BatteryManager.ACTION_CHARGING
283 : BatteryManager.ACTION_DISCHARGING;
284 }
285 Intent intent = new Intent(action);
286 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
287 cb.batterySendBroadcast(intent);
288 }
289 break;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700290 }
291 }
292 }
293
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800294 /**
295 * Update per-freq cpu times for all the uids in {@link #mPendingUids}.
296 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800297 public void updateProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800298 final SparseIntArray uidStates;
299 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800300 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
301 return;
302 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800303 if(!initKernelSingleUidTimeReaderLocked()) {
304 return;
305 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800306 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
307 // compute deltas since it might result in mis-attributing cpu times to wrong states.
308 if (mKernelSingleUidTimeReader.hasStaleData()) {
309 mPendingUids.clear();
310 return;
311 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800312
313 if (mPendingUids.size() == 0) {
314 return;
315 }
316 uidStates = mPendingUids.clone();
317 mPendingUids.clear();
318 }
319 for (int i = uidStates.size() - 1; i >= 0; --i) {
320 final int uid = uidStates.keyAt(i);
321 final int procState = uidStates.valueAt(i);
322 final int[] isolatedUids;
323 final Uid u;
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800324 synchronized (BatteryStatsImpl.this) {
325 // It's possible that uid no longer exists and any internal references have
326 // already been deleted, so using {@link #getAvailableUidStatsLocked} to avoid
327 // creating an UidStats object if it doesn't already exist.
328 u = getAvailableUidStatsLocked(uid);
329 if (u == null) {
330 continue;
331 }
332 if (u.mChildUids == null) {
333 isolatedUids = null;
334 } else {
335 isolatedUids = u.mChildUids.toArray();
336 for (int j = isolatedUids.length - 1; j >= 0; --j) {
337 isolatedUids[j] = u.mChildUids.get(j);
338 }
339 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800340 }
341 long[] cpuTimesMs = mKernelSingleUidTimeReader.readDeltaMs(uid);
342 if (isolatedUids != null) {
343 for (int j = isolatedUids.length - 1; j >= 0; --j) {
344 cpuTimesMs = addCpuTimes(cpuTimesMs,
345 mKernelSingleUidTimeReader.readDeltaMs(isolatedUids[j]));
346 }
347 }
348 if (onBattery && cpuTimesMs != null) {
349 synchronized (BatteryStatsImpl.this) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800350 u.addProcStateTimesMs(procState, cpuTimesMs, onBattery);
351 u.addProcStateScreenOffTimesMs(procState, cpuTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800352 }
353 }
354 }
355 }
356
Sudheer Shankae544d162017-12-28 17:06:20 -0800357 public void copyFromAllUidsCpuTimes() {
358 synchronized (BatteryStatsImpl.this) {
359 copyFromAllUidsCpuTimes(
360 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
361 }
362 }
363
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800364 /**
365 * When the battery/screen state changes, we don't attribute the cpu times to any process
366 * but we still need to snapshots of all uids to get correct deltas later on. Since we
367 * already read this data for updating per-freq cpu times, we can use the same data for
368 * per-procstate cpu times.
369 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800370 public void copyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800371 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800372 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
373 return;
374 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800375 if(!initKernelSingleUidTimeReaderLocked()) {
376 return;
377 }
378
379 final SparseArray<long[]> allUidCpuFreqTimesMs =
380 mKernelUidCpuFreqTimeReader.getAllUidCpuFreqTimeMs();
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800381 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
382 // compute deltas since it might result in mis-attributing cpu times to wrong states.
383 if (mKernelSingleUidTimeReader.hasStaleData()) {
384 mKernelSingleUidTimeReader.setAllUidsCpuTimesMs(allUidCpuFreqTimesMs);
385 mKernelSingleUidTimeReader.markDataAsStale(false);
386 mPendingUids.clear();
387 return;
388 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800389 for (int i = allUidCpuFreqTimesMs.size() - 1; i >= 0; --i) {
390 final int uid = allUidCpuFreqTimesMs.keyAt(i);
391 final Uid u = getAvailableUidStatsLocked(mapUid(uid));
392 if (u == null) {
393 continue;
394 }
395 final long[] cpuTimesMs = allUidCpuFreqTimesMs.valueAt(i);
396 if (cpuTimesMs == null) {
397 continue;
398 }
399 final long[] deltaTimesMs = mKernelSingleUidTimeReader.computeDelta(
400 uid, cpuTimesMs.clone());
Sudheer Shankae544d162017-12-28 17:06:20 -0800401 if (onBattery && deltaTimesMs != null) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800402 final int procState;
403 final int idx = mPendingUids.indexOfKey(uid);
404 if (idx >= 0) {
405 procState = mPendingUids.valueAt(idx);
406 mPendingUids.removeAt(idx);
407 } else {
408 procState = u.mProcessState;
409 }
410 if (procState >= 0 && procState < Uid.NUM_PROCESS_STATE) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800411 u.addProcStateTimesMs(procState, deltaTimesMs, onBattery);
412 u.addProcStateScreenOffTimesMs(procState, deltaTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800413 }
414 }
415 }
416 }
417 }
418
419 @VisibleForTesting
420 public long[] addCpuTimes(long[] timesA, long[] timesB) {
421 if (timesA != null && timesB != null) {
422 for (int i = timesA.length - 1; i >= 0; --i) {
423 timesA[i] += timesB[i];
424 }
425 return timesA;
426 }
427 return timesA == null ? (timesB == null ? null : timesB) : timesA;
428 }
429
430 @GuardedBy("this")
431 private boolean initKernelSingleUidTimeReaderLocked() {
432 if (mKernelSingleUidTimeReader == null) {
433 if (mPowerProfile == null) {
434 return false;
435 }
436 if (mCpuFreqs == null) {
437 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
438 }
439 if (mCpuFreqs != null) {
440 mKernelSingleUidTimeReader = new KernelSingleUidTimeReader(mCpuFreqs.length);
441 } else {
442 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable();
443 return false;
444 }
445 }
446 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable()
447 && mKernelSingleUidTimeReader.singleUidCpuTimesAvailable();
448 return true;
449 }
450
Joe Onoratoabded112016-02-08 16:49:39 -0800451 public interface Clocks {
452 public long elapsedRealtime();
453 public long uptimeMillis();
454 }
455
456 public static class SystemClocks implements Clocks {
457 public long elapsedRealtime() {
458 return SystemClock.elapsedRealtime();
459 }
460
461 public long uptimeMillis() {
462 return SystemClock.uptimeMillis();
463 }
464 }
465
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700466 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700467 int UPDATE_CPU = 0x01;
468 int UPDATE_WIFI = 0x02;
469 int UPDATE_RADIO = 0x04;
470 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700471 int UPDATE_RPM = 0x10; // 16
472 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800473
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700474 Future<?> scheduleSync(String reason, int flags);
475 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Sudheer Shankae544d162017-12-28 17:06:20 -0800476 Future<?> scheduleReadProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
477 Future<?> scheduleCopyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800478 Future<?> scheduleCpuSyncDueToSettingChange();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700479 }
480
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800481 public Handler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700482 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700483 @VisibleForTesting
484 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700485
486 private BatteryCallback mCallback;
487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800489 * Mapping isolated uids to the actual owning app uid.
490 */
491 final SparseIntArray mIsolatedUids = new SparseIntArray();
492
493 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 * The statistics we have collected organized by uids.
495 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800496 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497
498 // A set of pools of currently active timers. When a timer is queried, we will divide the
499 // elapsed time by the number of active timers to arrive at that timer's share of the time.
500 // In order to do this, we must refresh each timer whenever the number of active timers
501 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700502 @VisibleForTesting
503 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700504 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
505 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700506 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700507 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
508 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
509 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
510 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
511 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
512 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
513 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
514 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700515 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
516 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800517 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700519 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700520 @VisibleForTesting
521 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 // These are the objects that will want to do something when the device
524 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800525 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800526
527 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700528 // is unplugged from power *and* the screen is off or doze.
529 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800530
531 // Set to true when we want to distribute CPU across wakelocks for the next
532 // CPU update, even if we aren't currently running wake locks.
533 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700534
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700535 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700536
Dianne Hackborn37de0982014-05-09 09:32:18 -0700537 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800538
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700539 long mHistoryBaseTime;
Narayan Kamath695cf722017-12-21 18:32:47 +0000540 protected boolean mHaveBatteryLevel = false;
541 protected boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700542 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700543
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700544 final Parcel mHistoryBuffer = Parcel.obtain();
545 final HistoryItem mHistoryLastWritten = new HistoryItem();
546 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700547 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700548 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700549 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800550 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800551 int[] mReadHistoryUids;
552 int mReadHistoryChars;
553 int mNextHistoryTagIdx = 0;
554 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700555 int mHistoryBufferLastPos = -1;
556 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700557 int mActiveHistoryStates = 0xffffffff;
558 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700559 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700560 long mTrackRunningHistoryElapsedRealtime = 0;
561 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700562
563 final HistoryItem mHistoryCur = new HistoryItem();
564
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700565 HistoryItem mHistory;
566 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700567 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700568 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700569
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800570 // Used by computeHistoryStepDetails
571 HistoryStepDetails mLastHistoryStepDetails = null;
572 byte mLastHistoryStepLevel = 0;
573 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
574 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
575 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700576
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800577 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700578 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800579 */
580 long mLastStepCpuUserTime;
581 long mCurStepCpuUserTime;
582 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700583 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800584 */
585 long mLastStepCpuSystemTime;
586 long mCurStepCpuSystemTime;
587 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700588 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800589 */
590 long mLastStepStatUserTime;
591 long mLastStepStatSystemTime;
592 long mLastStepStatIOWaitTime;
593 long mLastStepStatIrqTime;
594 long mLastStepStatSoftIrqTime;
595 long mLastStepStatIdleTime;
596 long mCurStepStatUserTime;
597 long mCurStepStatSystemTime;
598 long mCurStepStatIOWaitTime;
599 long mCurStepStatIrqTime;
600 long mCurStepStatSoftIrqTime;
601 long mCurStepStatIdleTime;
602
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700603 private HistoryItem mHistoryIterator;
604 private boolean mReadOverflow;
605 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 int mStartCount;
608
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800609 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700610 String mStartPlatformVersion;
611 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 long mUptime;
614 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 long mRealtime;
616 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700617
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800618 int mWakeLockNesting;
619 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700620 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700621 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800622
Mike Mac2f518a2017-09-19 16:06:03 -0700623 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
624 protected int mScreenState = Display.STATE_UNKNOWN;
625 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
626 protected StopwatchTimer mScreenOnTimer;
627 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
628 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700629
Dianne Hackborn617f8772009-03-31 15:04:46 -0700630 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700631 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700632
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800633 boolean mPretendScreenOff;
634
Jeff Browne95c3cd2014-05-02 16:59:26 -0700635 boolean mInteractive;
636 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700637
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700638 boolean mPowerSaveModeEnabled;
639 StopwatchTimer mPowerSaveModeEnabledTimer;
640
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700641 boolean mDeviceIdling;
642 StopwatchTimer mDeviceIdlingTimer;
643
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700644 boolean mDeviceLightIdling;
645 StopwatchTimer mDeviceLightIdlingTimer;
646
647 int mDeviceIdleMode;
648 long mLastIdleTimeStart;
649 long mLongestLightIdleTime;
650 long mLongestFullIdleTime;
651 StopwatchTimer mDeviceIdleModeLightTimer;
652 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700655 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700656
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700657 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700658 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700659
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700660 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700661 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700662
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700663 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700664 StopwatchTimer mFlashlightOnTimer;
665
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700666 int mCameraOnNesting;
667 StopwatchTimer mCameraOnTimer;
668
Dianne Hackborn627bba72009-03-24 22:32:56 -0700669 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800670 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700671 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800672 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700673
674 StopwatchTimer mPhoneSignalScanningTimer;
675
Dianne Hackborn627bba72009-03-24 22:32:56 -0700676 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700677 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700678 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700679
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800680 final LongSamplingCounter[] mNetworkByteActivityCounters =
681 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
682 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700683 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
684
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800685 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800686 * The WiFi Overall wakelock timer
687 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
688 * since addition of per UID timers would not result in an accurate value due to overlapp of
689 * per uid wakelock timers
690 */
691 StopwatchTimer mWifiMulticastWakelockTimer;
692
693 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800694 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
695 */
696 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700697
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800698 /**
699 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
700 */
701 ControllerActivityCounterImpl mBluetoothActivity;
702
703 /**
704 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
705 */
706 ControllerActivityCounterImpl mModemActivity;
707
708 /**
709 * Whether the device supports WiFi controller energy reporting. This is set to true on
710 * the first WiFi energy report. See {@link #mWifiActivity}.
711 */
712 boolean mHasWifiReporting = false;
713
714 /**
715 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
716 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
717 */
718 boolean mHasBluetoothReporting = false;
719
720 /**
721 * Whether the device supports Modem controller energy reporting. This is set to true on
722 * the first Modem energy report. See {@link #mModemActivity}.
723 */
724 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700725
The Android Open Source Project10592532009-03-18 17:39:46 -0700726 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700727 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700728
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700729 boolean mGlobalWifiRunning;
730 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700731
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800732 int mWifiState = -1;
733 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
734
Dianne Hackborn3251b902014-06-20 14:40:53 -0700735 int mWifiSupplState = -1;
736 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
737
738 int mWifiSignalStrengthBin = -1;
739 final StopwatchTimer[] mWifiSignalStrengthsTimer =
740 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
741
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800742 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800743 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
744 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800745
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700746 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700747 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800748 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800749 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700750 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800751 LongSamplingCounter mMobileRadioActiveUnknownTime;
752 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800753
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700754 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 /**
757 * These provide time bases that discount the time the device is plugged
758 * in to power.
759 */
760 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700761 @VisibleForTesting
762 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700763
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700764 /**
765 * External reporting of whether the device is actually charging.
766 */
767 boolean mCharging = true;
768 int mLastChargingStateLevel;
769
The Android Open Source Project10592532009-03-18 17:39:46 -0700770 /*
771 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
772 */
Evan Millar633a1742009-04-02 16:36:33 -0700773 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700774 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700775 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700776 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700777 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700778 int mLowDischargeAmountSinceCharge;
779 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800780 int mDischargeScreenOnUnplugLevel;
781 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700782 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800783 int mDischargeAmountScreenOn;
784 int mDischargeAmountScreenOnSinceCharge;
785 int mDischargeAmountScreenOff;
786 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700787 int mDischargeAmountScreenDoze;
788 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700789
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700790 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700791 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700792 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800793 private LongSamplingCounter mDischargeLightDozeCounter;
794 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700795
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700796 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700797
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700798 int mInitStepMode = 0;
799 int mCurStepMode = 0;
800 int mModStepMode = 0;
801
Dianne Hackborn260c5022014-04-29 11:23:16 -0700802 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700803 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800804 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
805 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700806 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700807
808 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700809 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800810 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
811 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
812
813 static final int MAX_DAILY_ITEMS = 10;
814
815 long mDailyStartTime = 0;
816 long mNextMinDailyDeadline = 0;
817 long mNextMaxDailyDeadline = 0;
818
819 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700822
Amith Yamasanif37447b2009-10-08 18:28:01 -0700823 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800824 private int mPhoneServiceStateRaw = -1;
825 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700826
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800827 private int mNumConnectivityChange;
828 private int mLoadedNumConnectivityChange;
829 private int mUnpluggedNumConnectivityChange;
830
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700831 private int mEstimatedBatteryCapacity = -1;
832
Jocelyn Dangc627d102017-04-14 13:15:14 -0700833 private int mMinLearnedBatteryCapacity = -1;
834 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800835
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700836 private long[] mCpuFreqs;
837
Sudheer Shanka38383232017-07-25 09:55:03 -0700838 @VisibleForTesting
839 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700840
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800841 @GuardedBy("this")
842 private final Constants mConstants;
843
Evan Millarc64edde2009-04-18 12:26:32 -0700844 /*
Bookatz50df7112017-08-04 14:53:26 -0700845 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
846 * recording their times when on-battery (regardless of screen state).
847 */
848 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
849 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
850 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
851
852 @Override
853 public Map<String, ? extends Timer> getRpmStats() {
854 return mRpmStats;
855 }
856
Bookatz82b341172017-09-07 19:06:08 -0700857 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700858 @Override
859 public Map<String, ? extends Timer> getScreenOffRpmStats() {
860 return mScreenOffRpmStats;
861 }
862
863 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700864 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
865 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700866 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700867
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700868 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700869 return mKernelWakelockStats;
870 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700871
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700872 String mLastWakeupReason = null;
873 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700874 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700875
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700876 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700877 return mWakeupReasonStats;
878 }
879
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700880 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700881 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700882 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700883 }
884
885 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700886 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700887 return mDischargeScreenOffCounter.getCountLocked(which);
888 }
889
890 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700891 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700892 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700893 }
894
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700895 @Override
Mike Ma15313c92017-11-15 17:58:21 -0800896 public long getUahDischargeLightDoze(int which) {
897 return mDischargeLightDozeCounter.getCountLocked(which);
898 }
899
900 @Override
901 public long getUahDischargeDeepDoze(int which) {
902 return mDischargeDeepDozeCounter.getCountLocked(which);
903 }
904
905 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700906 public int getEstimatedBatteryCapacity() {
907 return mEstimatedBatteryCapacity;
908 }
909
Jocelyn Dangc627d102017-04-14 13:15:14 -0700910 @Override
911 public int getMinLearnedBatteryCapacity() {
912 return mMinLearnedBatteryCapacity;
913 }
914
915 @Override
916 public int getMaxLearnedBatteryCapacity() {
917 return mMaxLearnedBatteryCapacity;
918 }
919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -0800921 this(new SystemClocks());
922 }
923
924 public BatteryStatsImpl(Clocks clocks) {
925 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700926 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700927 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800928 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700929 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700930 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700931 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800932 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700933 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 }
935
Joe Onoratoabded112016-02-08 16:49:39 -0800936 private void init(Clocks clocks) {
937 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -0800938 }
939
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700940 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800941 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
942 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
943 }
944
Joe Onoratoabded112016-02-08 16:49:39 -0800945 // methods are protected not private to be VisibleForTesting
946 public static class TimeBase {
947 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800948
Joe Onoratoabded112016-02-08 16:49:39 -0800949 protected long mUptime;
950 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800951
Joe Onoratoabded112016-02-08 16:49:39 -0800952 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800953
Joe Onoratoabded112016-02-08 16:49:39 -0800954 protected long mPastUptime;
955 protected long mUptimeStart;
956 protected long mPastRealtime;
957 protected long mRealtimeStart;
958 protected long mUnpluggedUptime;
959 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800960
961 public void dump(PrintWriter pw, String prefix) {
962 StringBuilder sb = new StringBuilder(128);
963 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
964 sb.setLength(0);
965 sb.append(prefix);
966 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700967 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800968 pw.println(sb.toString());
969 sb.setLength(0);
970 sb.append(prefix);
971 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700972 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800973 pw.println(sb.toString());
974 sb.setLength(0);
975 sb.append(prefix);
976 sb.append("mPastUptime=");
977 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
978 formatTimeMs(sb, mUptimeStart / 1000);
979 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
980 pw.println(sb.toString());
981 sb.setLength(0);
982 sb.append(prefix);
983 sb.append("mPastRealtime=");
984 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
985 formatTimeMs(sb, mRealtimeStart / 1000);
986 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
987 pw.println(sb.toString());
988 }
989
990 public void add(TimeBaseObs observer) {
991 mObservers.add(observer);
992 }
993
994 public void remove(TimeBaseObs observer) {
995 if (!mObservers.remove(observer)) {
996 Slog.wtf(TAG, "Removed unknown observer: " + observer);
997 }
998 }
999
Joe Onoratoabded112016-02-08 16:49:39 -08001000 public boolean hasObserver(TimeBaseObs observer) {
1001 return mObservers.contains(observer);
1002 }
1003
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001004 public void init(long uptime, long realtime) {
1005 mRealtime = 0;
1006 mUptime = 0;
1007 mPastUptime = 0;
1008 mPastRealtime = 0;
1009 mUptimeStart = uptime;
1010 mRealtimeStart = realtime;
1011 mUnpluggedUptime = getUptime(mUptimeStart);
1012 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1013 }
1014
1015 public void reset(long uptime, long realtime) {
1016 if (!mRunning) {
1017 mPastUptime = 0;
1018 mPastRealtime = 0;
1019 } else {
1020 mUptimeStart = uptime;
1021 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001022 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1023 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001024 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001025 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001026 mUnpluggedRealtime = getRealtime(realtime);
1027 }
1028 }
1029
1030 public long computeUptime(long curTime, int which) {
1031 switch (which) {
1032 case STATS_SINCE_CHARGED:
1033 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001034 case STATS_CURRENT:
1035 return getUptime(curTime);
1036 case STATS_SINCE_UNPLUGGED:
1037 return getUptime(curTime) - mUnpluggedUptime;
1038 }
1039 return 0;
1040 }
1041
1042 public long computeRealtime(long curTime, int which) {
1043 switch (which) {
1044 case STATS_SINCE_CHARGED:
1045 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001046 case STATS_CURRENT:
1047 return getRealtime(curTime);
1048 case STATS_SINCE_UNPLUGGED:
1049 return getRealtime(curTime) - mUnpluggedRealtime;
1050 }
1051 return 0;
1052 }
1053
1054 public long getUptime(long curTime) {
1055 long time = mPastUptime;
1056 if (mRunning) {
1057 time += curTime - mUptimeStart;
1058 }
1059 return time;
1060 }
1061
1062 public long getRealtime(long curTime) {
1063 long time = mPastRealtime;
1064 if (mRunning) {
1065 time += curTime - mRealtimeStart;
1066 }
1067 return time;
1068 }
1069
1070 public long getUptimeStart() {
1071 return mUptimeStart;
1072 }
1073
1074 public long getRealtimeStart() {
1075 return mRealtimeStart;
1076 }
1077
1078 public boolean isRunning() {
1079 return mRunning;
1080 }
1081
1082 public boolean setRunning(boolean running, long uptime, long realtime) {
1083 if (mRunning != running) {
1084 mRunning = running;
1085 if (running) {
1086 mUptimeStart = uptime;
1087 mRealtimeStart = realtime;
1088 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1089 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
1090
1091 for (int i = mObservers.size() - 1; i >= 0; i--) {
1092 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
1093 }
1094 } else {
1095 mPastUptime += uptime - mUptimeStart;
1096 mPastRealtime += realtime - mRealtimeStart;
1097
1098 long batteryUptime = getUptime(uptime);
1099 long batteryRealtime = getRealtime(realtime);
1100
1101 for (int i = mObservers.size() - 1; i >= 0; i--) {
1102 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
1103 }
1104 }
1105 return true;
1106 }
1107 return false;
1108 }
1109
1110 public void readSummaryFromParcel(Parcel in) {
1111 mUptime = in.readLong();
1112 mRealtime = in.readLong();
1113 }
1114
1115 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1116 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1117 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1118 }
1119
1120 public void readFromParcel(Parcel in) {
1121 mRunning = false;
1122 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001123 mPastUptime = in.readLong();
1124 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001125 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001126 mPastRealtime = in.readLong();
1127 mRealtimeStart = in.readLong();
1128 mUnpluggedUptime = in.readLong();
1129 mUnpluggedRealtime = in.readLong();
1130 }
1131
1132 public void writeToParcel(Parcel out, long uptime, long realtime) {
1133 final long runningUptime = getUptime(uptime);
1134 final long runningRealtime = getRealtime(realtime);
1135 out.writeLong(mUptime);
1136 out.writeLong(runningUptime);
1137 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001138 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001139 out.writeLong(runningRealtime);
1140 out.writeLong(mRealtimeStart);
1141 out.writeLong(mUnpluggedUptime);
1142 out.writeLong(mUnpluggedRealtime);
1143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001147 * State for keeping track of counting information.
1148 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001149 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -07001150 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001151 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001152 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001153 int mUnpluggedCount;
1154 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001155
Bookatz8c6f3c52017-05-24 12:00:17 -07001156 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001157 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -07001158 mPluggedCount = in.readInt();
1159 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001160 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001161 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001162 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001163 }
1164
Bookatz8c6f3c52017-05-24 12:00:17 -07001165 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001166 mTimeBase = timeBase;
1167 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001168 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001169
Dianne Hackborn617f8772009-03-31 15:04:46 -07001170 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001171 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001172 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001173 out.writeInt(mUnpluggedCount);
1174 }
1175
Bookatz8c6f3c52017-05-24 12:00:17 -07001176 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001177 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001178 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001179 }
1180
Bookatz8c6f3c52017-05-24 12:00:17 -07001181 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001182 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001183 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001184 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001185
Dianne Hackborn617f8772009-03-31 15:04:46 -07001186 /**
1187 * Writes a possibly null Counter to a Parcel.
1188 *
1189 * @param out the Parcel to be written to.
1190 * @param counter a Counter, or null.
1191 */
1192 public static void writeCounterToParcel(Parcel out, Counter counter) {
1193 if (counter == null) {
1194 out.writeInt(0); // indicates null
1195 return;
1196 }
1197 out.writeInt(1); // indicates non-null
1198
1199 counter.writeToParcel(out);
1200 }
1201
1202 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001203 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001204 int val = mCount.get();
1205 if (which == STATS_SINCE_UNPLUGGED) {
1206 val -= mUnpluggedCount;
1207 } else if (which != STATS_SINCE_CHARGED) {
1208 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001209 }
1210
1211 return val;
1212 }
1213
1214 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001215 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001216 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001217 + " mUnpluggedCount=" + mUnpluggedCount
1218 + " mPluggedCount=" + mPluggedCount);
1219 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001220
Bookatz8c6f3c52017-05-24 12:00:17 -07001221 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1222 public void stepAtomic() {
1223 if (mTimeBase.isRunning()) {
1224 mCount.incrementAndGet();
1225 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001226 }
1227
Bookatz4ebc0642017-05-11 12:21:19 -07001228 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001229 if (mTimeBase.isRunning()) {
1230 mCount.addAndGet(delta);
1231 }
Bookatz4ebc0642017-05-11 12:21:19 -07001232 }
1233
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001234 /**
1235 * Clear state of this counter.
1236 */
1237 void reset(boolean detachIfReset) {
1238 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001239 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001240 if (detachIfReset) {
1241 detach();
1242 }
1243 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001244
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001245 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001246 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001247 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001248
Bookatz8c6f3c52017-05-24 12:00:17 -07001249 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1250 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001251 int count = mCount.get();
1252 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001253 }
1254
Bookatz8c6f3c52017-05-24 12:00:17 -07001255 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1256 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001257 mLoadedCount = in.readInt();
1258 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001259 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001260 }
1261 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001262
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001263 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001264 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1265 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001266 public long[] mCounts;
1267 public long[] mLoadedCounts;
1268 public long[] mUnpluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001269
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001270 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001271 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001272 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001273 mLoadedCounts = in.createLongArray();
1274 mUnpluggedCounts = in.createLongArray();
1275 timeBase.add(this);
1276 }
1277
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001278 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001279 mTimeBase = timeBase;
1280 timeBase.add(this);
1281 }
1282
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001283 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001284 out.writeLongArray(mCounts);
1285 out.writeLongArray(mLoadedCounts);
1286 out.writeLongArray(mUnpluggedCounts);
1287 }
1288
1289 @Override
1290 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001291 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001292 }
1293
1294 @Override
1295 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001296 }
1297
1298 @Override
1299 public long[] getCountsLocked(int which) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001300 long[] val = copyArray(mCounts, null);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001301 if (which == STATS_SINCE_UNPLUGGED) {
1302 subtract(val, mUnpluggedCounts);
1303 } else if (which != STATS_SINCE_CHARGED) {
1304 subtract(val, mLoadedCounts);
1305 }
1306 return val;
1307 }
1308
1309 @Override
1310 public void logState(Printer pw, String prefix) {
1311 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1312 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
Sudheer Shankae544d162017-12-28 17:06:20 -08001313 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001314 }
1315
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001316 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001317 addCountLocked(counts, mTimeBase.isRunning());
1318 }
1319
1320 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001321 if (counts == null) {
1322 return;
1323 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001324 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001325 if (mCounts == null) {
1326 mCounts = new long[counts.length];
1327 }
1328 for (int i = 0; i < counts.length; ++i) {
1329 mCounts[i] += counts[i];
1330 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001331 }
1332 }
1333
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001334 public int getSize() {
1335 return mCounts == null ? 0 : mCounts.length;
1336 }
1337
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001338 /**
1339 * Clear state of this counter.
1340 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001341 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001342 fillArray(mCounts, 0);
1343 fillArray(mLoadedCounts, 0);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001344 fillArray(mUnpluggedCounts, 0);
1345 if (detachIfReset) {
1346 detach();
1347 }
1348 }
1349
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001350 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001351 mTimeBase.remove(this);
1352 }
1353
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001354 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001355 out.writeLongArray(mCounts);
1356 }
1357
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001358 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001359 mCounts = in.createLongArray();
1360 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1361 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001362 }
1363
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001364 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1365 if (counterArray != null) {
1366 out.writeInt(1);
1367 counterArray.writeToParcel(out);
1368 } else {
1369 out.writeInt(0);
1370 }
1371 }
1372
1373 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1374 if (in.readInt() != 0) {
1375 return new LongSamplingCounterArray(timeBase, in);
1376 } else {
1377 return null;
1378 }
1379 }
1380
1381 public static void writeSummaryToParcelLocked(Parcel out,
1382 LongSamplingCounterArray counterArray) {
1383 if (counterArray != null) {
1384 out.writeInt(1);
1385 counterArray.writeSummaryToParcelLocked(out);
1386 } else {
1387 out.writeInt(0);
1388 }
1389 }
1390
1391 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1392 TimeBase timeBase) {
1393 if (in.readInt() != 0) {
1394 final LongSamplingCounterArray counterArray
1395 = new LongSamplingCounterArray(timeBase);
1396 counterArray.readSummaryFromParcelLocked(in);
1397 return counterArray;
1398 } else {
1399 return null;
1400 }
1401 }
1402
Bookatz8c6f3c52017-05-24 12:00:17 -07001403 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001404 if (a != null) {
1405 Arrays.fill(a, val);
1406 }
1407 }
1408
Bookatz8c6f3c52017-05-24 12:00:17 -07001409 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001410 if (toSubtract == null) {
1411 return;
1412 }
1413 for (int i = 0; i < val.length; i++) {
1414 val[i] -= toSubtract[i];
1415 }
1416 }
1417
Bookatz8c6f3c52017-05-24 12:00:17 -07001418 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001419 if (src == null) {
1420 return null;
1421 } else {
1422 if (dest == null) {
1423 dest = new long[src.length];
1424 }
1425 System.arraycopy(src, 0, dest, 0, src.length);
1426 return dest;
1427 }
1428 }
1429 }
1430
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001431 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001432 final TimeBase mTimeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001433 long mCount;
1434 long mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001435 long mUnpluggedCount;
1436 long mPluggedCount;
1437
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001438 LongSamplingCounter(TimeBase timeBase, Parcel in) {
1439 mTimeBase = timeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001440 mPluggedCount = in.readLong();
1441 mCount = mPluggedCount;
1442 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001443 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001444 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001445 }
1446
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001447 LongSamplingCounter(TimeBase timeBase) {
1448 mTimeBase = timeBase;
1449 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001450 }
1451
1452 public void writeToParcel(Parcel out) {
1453 out.writeLong(mCount);
1454 out.writeLong(mLoadedCount);
1455 out.writeLong(mUnpluggedCount);
1456 }
1457
1458 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001459 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001460 mUnpluggedCount = mPluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001461 }
1462
1463 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001464 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001465 mPluggedCount = mCount;
1466 }
1467
1468 public long getCountLocked(int which) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001469 long val = mTimeBase.isRunning() ? mCount : mPluggedCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001470 if (which == STATS_SINCE_UNPLUGGED) {
1471 val -= mUnpluggedCount;
1472 } else if (which != STATS_SINCE_CHARGED) {
1473 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001474 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001475 return val;
1476 }
1477
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001478 @Override
1479 public void logState(Printer pw, String prefix) {
1480 pw.println(prefix + "mCount=" + mCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001481 + " mLoadedCount=" + mLoadedCount
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001482 + " mUnpluggedCount=" + mUnpluggedCount
1483 + " mPluggedCount=" + mPluggedCount);
1484 }
1485
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001486 void addCountLocked(long count) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001487 if (mTimeBase.isRunning()) {
1488 mCount += count;
1489 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001490 }
1491
1492 /**
1493 * Clear state of this counter.
1494 */
1495 void reset(boolean detachIfReset) {
1496 mCount = 0;
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001497 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001498 if (detachIfReset) {
1499 detach();
1500 }
1501 }
1502
1503 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001504 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001505 }
1506
1507 void writeSummaryFromParcelLocked(Parcel out) {
1508 out.writeLong(mCount);
1509 }
1510
1511 void readSummaryFromParcelLocked(Parcel in) {
1512 mLoadedCount = in.readLong();
1513 mCount = mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001514 mUnpluggedCount = mPluggedCount = mLoadedCount;
1515 }
1516 }
1517
Dianne Hackborn617f8772009-03-31 15:04:46 -07001518 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 * State for keeping track of timing information.
1520 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001521 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001522 protected final Clocks mClocks;
1523 protected final int mType;
1524 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001525
Joe Onoratoabded112016-02-08 16:49:39 -08001526 protected int mCount;
1527 protected int mLoadedCount;
1528 protected int mLastCount;
1529 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 // Times are in microseconds for better accuracy when dividing by the
1532 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 /**
1535 * The total time we have accumulated since the start of the original
1536 * boot, to the last time something interesting happened in the
1537 * current run.
1538 */
Joe Onoratoabded112016-02-08 16:49:39 -08001539 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 /**
1542 * The total time we loaded for the previous runs. Subtract this from
1543 * mTotalTime to find the time for the current run of the system.
1544 */
Joe Onoratoabded112016-02-08 16:49:39 -08001545 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 /**
1548 * The run time of the last run of the system, as loaded from the
1549 * saved data.
1550 */
Joe Onoratoabded112016-02-08 16:49:39 -08001551 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 /**
1554 * The value of mTotalTime when unplug() was last called. Subtract
1555 * this from mTotalTime to find the time since the last unplug from
1556 * power.
1557 */
Joe Onoratoabded112016-02-08 16:49:39 -08001558 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001559
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001560 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001561 * The total time this timer has been running until the latest mark has been set.
1562 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1563 */
Joe Onoratoabded112016-02-08 16:49:39 -08001564 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001565
1566 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001567 * Constructs from a parcel.
1568 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001569 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001570 * @param in
1571 */
Joe Onoratoabded112016-02-08 16:49:39 -08001572 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1573 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001575 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 mCount = in.readInt();
1578 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001579 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 mUnpluggedCount = in.readInt();
1581 mTotalTime = in.readLong();
1582 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001583 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001585 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001586 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001587 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 }
1589
Joe Onoratoabded112016-02-08 16:49:39 -08001590 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1591 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001593 mTimeBase = timeBase;
1594 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 }
Evan Millarc64edde2009-04-18 12:26:32 -07001596
1597 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001598
Evan Millarc64edde2009-04-18 12:26:32 -07001599 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001600
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001601 /**
1602 * Clear state of this timer. Returns true if the timer is inactive
1603 * so can be completely dropped.
1604 */
Joe Onoratoabded112016-02-08 16:49:39 -08001605 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001606 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001607 mCount = mLoadedCount = mLastCount = 0;
1608 if (detachIfReset) {
1609 detach();
1610 }
1611 return true;
1612 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001613
Joe Onoratoabded112016-02-08 16:49:39 -08001614 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001615 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001616 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001617
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001618 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001619 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1620 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001621 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001624 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001627 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
1629
Adam Lesinskie08af192015-03-25 16:42:59 -07001630 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001631 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001633 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 + " old mUnpluggedTime=" + mUnpluggedTime
1635 + " old mUnpluggedCount=" + mUnpluggedCount);
1636 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001637 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001638 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 if (DEBUG && mType < 0) {
1640 Log.v(TAG, "unplug #" + mType
1641 + ": new mUnpluggedTime=" + mUnpluggedTime
1642 + " new mUnpluggedCount=" + mUnpluggedCount);
1643 }
1644 }
1645
Adam Lesinskie08af192015-03-25 16:42:59 -07001646 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001647 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001648 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001649 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001650 + " old mTotalTime=" + mTotalTime);
1651 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001652 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001653 mCount = computeCurrentCountLocked();
1654 if (DEBUG && mType < 0) {
1655 Log.v(TAG, "plug #" + mType
1656 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 }
1658 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 /**
1661 * Writes a possibly null Timer to a Parcel.
1662 *
1663 * @param out the Parcel to be written to.
1664 * @param timer a Timer, or null.
1665 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001666 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 if (timer == null) {
1668 out.writeInt(0); // indicates null
1669 return;
1670 }
1671 out.writeInt(1); // indicates non-null
1672
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001673 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 }
1675
1676 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001677 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001678 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1679 if (which == STATS_SINCE_UNPLUGGED) {
1680 val -= mUnpluggedTime;
1681 } else if (which != STATS_SINCE_CHARGED) {
1682 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 }
1684
1685 return val;
1686 }
1687
1688 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001689 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001690 int val = computeCurrentCountLocked();
1691 if (which == STATS_SINCE_UNPLUGGED) {
1692 val -= mUnpluggedCount;
1693 } else if (which != STATS_SINCE_CHARGED) {
1694 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 }
1696
1697 return val;
1698 }
1699
Adam Lesinskie08af192015-03-25 16:42:59 -07001700 @Override
1701 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1702 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1703 return val - mTimeBeforeMark;
1704 }
1705
1706 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001707 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001708 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1710 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001711 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001713 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001715 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001716
1717
Joe Onoratoabded112016-02-08 16:49:39 -08001718 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001719 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1720 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001721 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001722 }
1723
Joe Onoratoabded112016-02-08 16:49:39 -08001724 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001725 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001726 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001727 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001728 mUnpluggedTime = mTotalTime;
1729 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001730 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001731 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001732
1733 // When reading the summary, we set the mark to be the latest information.
1734 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001735 }
1736 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001737
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001738 /**
1739 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1740 * method. The state of the timer according to its {@link TimeBase} will determine how much
1741 * of the value is recorded.
1742 *
1743 * If the value being recorded resets, {@link #endSample()} can be called in order to
1744 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1745 * between calls, the {@link #endSample()} is automatically called and the new value is
1746 * expected to increase monotonically from that point on.
1747 */
Joe Onoratoabded112016-02-08 16:49:39 -08001748 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001749
Evan Millarc64edde2009-04-18 12:26:32 -07001750 /**
1751 * The most recent reported count from /proc/wakelocks.
1752 */
1753 int mCurrentReportedCount;
1754
1755 /**
1756 * The reported count from /proc/wakelocks when unplug() was last
1757 * called.
1758 */
1759 int mUnpluggedReportedCount;
1760
1761 /**
1762 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001763 */
Evan Millarc64edde2009-04-18 12:26:32 -07001764 long mCurrentReportedTotalTime;
1765
1766
1767 /**
1768 * The reported total_time from /proc/wakelocks when unplug() was last
1769 * called.
1770 */
1771 long mUnpluggedReportedTotalTime;
1772
1773 /**
1774 * Whether we are currently in a discharge cycle.
1775 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001776 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001777
1778 /**
1779 * Whether we are currently recording reported values.
1780 */
1781 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001782
Evan Millarc64edde2009-04-18 12:26:32 -07001783 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001784 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001785 */
1786 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001787
Adam Lesinski98f0d462016-04-19 16:46:20 -07001788 @VisibleForTesting
1789 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001790 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001791 mCurrentReportedCount = in.readInt();
1792 mUnpluggedReportedCount = in.readInt();
1793 mCurrentReportedTotalTime = in.readLong();
1794 mUnpluggedReportedTotalTime = in.readLong();
1795 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001796 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001797 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001798
Adam Lesinski98f0d462016-04-19 16:46:20 -07001799 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001800 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001801 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001802 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001803 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001804 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001805
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001806 /**
1807 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1808 * be less than the values used for a previous invocation.
1809 */
1810 public void endSample() {
1811 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1812 mCount = computeCurrentCountLocked();
1813 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1814 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001815 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001816
Evan Millarc64edde2009-04-18 12:26:32 -07001817 public void setUpdateVersion(int version) {
1818 mUpdateVersion = version;
1819 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001820
Evan Millarc64edde2009-04-18 12:26:32 -07001821 public int getUpdateVersion() {
1822 return mUpdateVersion;
1823 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001824
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001825 /**
1826 * Updates the current recorded values. These are meant to be monotonically increasing
1827 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1828 *
1829 * If the values being recorded have been reset, the monotonically increasing requirement
1830 * will be broken. In this case, {@link #endSample()} is automatically called and
1831 * the total value of totalTime and count are recorded, starting a new monotonically
1832 * increasing sample.
1833 *
1834 * @param totalTime total time of sample in microseconds.
1835 * @param count total number of times the event being sampled occurred.
1836 */
1837 public void update(long totalTime, int count) {
1838 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001839 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001840 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001841 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001842 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001843
1844 mTrackingReportedValues = true;
1845
1846 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1847 endSample();
1848 }
1849
1850 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001851 mCurrentReportedCount = count;
1852 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001853
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001854 /**
1855 * Adds deltaTime and deltaCount to the current sample.
1856 *
1857 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1858 * @param deltaCount additional number of times the event being sampled occurred.
1859 */
1860 public void add(long deltaTime, int deltaCount) {
1861 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001862 }
1863
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001864 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001865 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
1866 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001867 if (mTrackingReportedValues) {
1868 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
1869 mUnpluggedReportedCount = mCurrentReportedCount;
1870 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001871 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07001872 }
1873
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001874 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001875 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1876 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1877 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07001878 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001879
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001880 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001881 public void logState(Printer pw, String prefix) {
1882 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001883 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07001884 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
1885 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
1886 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
1887 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001888
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001889 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001890 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001891 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001892 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
1893 }
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 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001897 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001898 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
1899 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001900
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001901 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001902 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1903 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001904 out.writeInt(mCurrentReportedCount);
1905 out.writeInt(mUnpluggedReportedCount);
1906 out.writeLong(mCurrentReportedTotalTime);
1907 out.writeLong(mUnpluggedReportedTotalTime);
1908 out.writeInt(mTrackingReportedValues ? 1 : 0);
1909 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001910
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001911 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001912 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001913 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001914 mTrackingReportedValues = false;
1915 mUnpluggedReportedTotalTime = 0;
1916 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001917 return true;
1918 }
Evan Millarc64edde2009-04-18 12:26:32 -07001919 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001920
Evan Millarc64edde2009-04-18 12:26:32 -07001921 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001922 * A timer that increments in batches. It does not run for durations, but just jumps
1923 * for a pre-determined amount.
1924 */
Joe Onoratoabded112016-02-08 16:49:39 -08001925 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001926 final Uid mUid;
1927
1928 /**
1929 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
1930 */
1931 long mLastAddedTime;
1932
1933 /**
1934 * The last duration that we added to the timer. This is in microseconds.
1935 */
1936 long mLastAddedDuration;
1937
1938 /**
1939 * Whether we are currently in a discharge cycle.
1940 */
1941 boolean mInDischarge;
1942
Joe Onoratoabded112016-02-08 16:49:39 -08001943 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
1944 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001945 mUid = uid;
1946 mLastAddedTime = in.readLong();
1947 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001948 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001949 }
1950
Joe Onoratoabded112016-02-08 16:49:39 -08001951 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
1952 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001953 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001954 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001955 }
1956
1957 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001958 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1959 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001960 out.writeLong(mLastAddedTime);
1961 out.writeLong(mLastAddedDuration);
1962 }
1963
1964 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001965 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001966 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001967 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001968 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001969 }
1970
1971 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001972 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001973 recomputeLastDuration(elapsedRealtime, false);
1974 mInDischarge = true;
1975 // If we are still within the last added duration, then re-added whatever remains.
1976 if (mLastAddedTime == elapsedRealtime) {
1977 mTotalTime += mLastAddedDuration;
1978 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001979 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001980 }
1981
1982 @Override
1983 public void logState(Printer pw, String prefix) {
1984 super.logState(pw, prefix);
1985 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
1986 + " mLastAddedDuration=" + mLastAddedDuration);
1987 }
1988
1989 private long computeOverage(long curTime) {
1990 if (mLastAddedTime > 0) {
1991 return mLastTime + mLastAddedDuration - curTime;
1992 }
1993 return 0;
1994 }
1995
1996 private void recomputeLastDuration(long curTime, boolean abort) {
1997 final long overage = computeOverage(curTime);
1998 if (overage > 0) {
1999 // Aborting before the duration ran out -- roll back the remaining
2000 // duration. Only do this if currently discharging; otherwise we didn't
2001 // actually add the time.
2002 if (mInDischarge) {
2003 mTotalTime -= overage;
2004 }
2005 if (abort) {
2006 mLastAddedTime = 0;
2007 } else {
2008 mLastAddedTime = curTime;
2009 mLastAddedDuration -= overage;
2010 }
2011 }
2012 }
2013
2014 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08002015 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002016 recomputeLastDuration(now, true);
2017 mLastAddedTime = now;
2018 mLastAddedDuration = durationMillis * 1000;
2019 if (mInDischarge) {
2020 mTotalTime += mLastAddedDuration;
2021 mCount++;
2022 }
2023 }
2024
2025 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002026 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002027 recomputeLastDuration(now, true);
2028 }
2029
2030 @Override
2031 protected int computeCurrentCountLocked() {
2032 return mCount;
2033 }
2034
2035 @Override
2036 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002037 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002038 if (overage > 0) {
2039 return mTotalTime = overage;
2040 }
2041 return mTotalTime;
2042 }
2043
2044 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002045 public boolean reset(boolean detachIfReset) {
2046 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002047 recomputeLastDuration(now, true);
2048 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002049 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002050 return !stillActive;
2051 }
2052 }
2053
Joe Onorato92fd23f2016-07-25 11:18:42 -07002054
2055 /**
2056 * A StopwatchTimer that also tracks the total and max individual
2057 * time spent active according to the given timebase. Whereas
2058 * StopwatchTimer apportions the time amongst all in the pool,
2059 * the total and max durations are not apportioned.
2060 */
2061 public static class DurationTimer extends StopwatchTimer {
2062 /**
2063 * The time (in ms) that the timer was last acquired or the time base
2064 * last (re-)started. Increasing the nesting depth does not reset this time.
2065 *
2066 * -1 if the timer is currently not running or the time base is not running.
2067 *
2068 * If written to a parcel, the start time is reset, as is mNesting in the base class
2069 * StopwatchTimer.
2070 */
2071 long mStartTimeMs = -1;
2072
2073 /**
Bookatz867c0d72017-03-07 18:23:42 -08002074 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002075 */
2076 long mMaxDurationMs;
2077
2078 /**
Bookatz867c0d72017-03-07 18:23:42 -08002079 * The time (in ms) that that the timer has been active since most recent
2080 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002081 */
2082 long mCurrentDurationMs;
2083
Bookatz867c0d72017-03-07 18:23:42 -08002084 /**
2085 * The total time (in ms) that that the timer has been active since most recent reset()
2086 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2087 * (but not including the present currentDuration) since reset. Not pooled.
2088 */
2089 long mTotalDurationMs;
2090
Joe Onorato92fd23f2016-07-25 11:18:42 -07002091 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2092 TimeBase timeBase, Parcel in) {
2093 super(clocks, uid, type, timerPool, timeBase, in);
2094 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002095 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002096 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002097 }
2098
2099 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2100 TimeBase timeBase) {
2101 super(clocks, uid, type, timerPool, timeBase);
2102 }
2103
2104 @Override
2105 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2106 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002107 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002108 out.writeLong(mTotalDurationMs);
2109 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002110 }
2111
2112 /**
2113 * Write the summary to the parcel.
2114 *
2115 * Since the time base is probably meaningless after we come back, reading
2116 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002117 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002118 */
2119 @Override
2120 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2121 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002122 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002123 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002124 }
2125
2126 /**
2127 * Read the summary parcel.
2128 *
2129 * Has the side effect of stopping the timer.
2130 */
2131 @Override
2132 public void readSummaryFromParcelLocked(Parcel in) {
2133 super.readSummaryFromParcelLocked(in);
2134 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002135 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002136 mStartTimeMs = -1;
2137 mCurrentDurationMs = 0;
2138 }
2139
2140 /**
2141 * The TimeBase time started (again).
2142 *
2143 * If the timer is also running, store the start time.
2144 */
2145 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2146 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2147 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002148 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002149 }
2150 }
2151
2152 /**
2153 * The TimeBase stopped running.
2154 *
2155 * If the timer is running, add the duration into mCurrentDurationMs.
2156 */
2157 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002158 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2159 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002160 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002161 // baseRealtimeUs has already been converted to the timebase's realtime.
2162 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002163 }
2164 mStartTimeMs = -1;
2165 }
2166
2167 @Override
2168 public void logState(Printer pw, String prefix) {
2169 super.logState(pw, prefix);
2170 }
2171
2172 @Override
2173 public void startRunningLocked(long elapsedRealtimeMs) {
2174 super.startRunningLocked(elapsedRealtimeMs);
2175 if (mNesting == 1 && mTimeBase.isRunning()) {
2176 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002177 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002178 }
2179 }
2180
2181 /**
2182 * Decrements the mNesting ref-count on this timer.
2183 *
2184 * If it actually stopped (mNesting went to 0), then possibly update
2185 * mMaxDuration if the current duration was the longest ever.
2186 */
2187 @Override
2188 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002189 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002190 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002191 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002192 if (durationMs > mMaxDurationMs) {
2193 mMaxDurationMs = durationMs;
2194 }
2195 mStartTimeMs = -1;
2196 mCurrentDurationMs = 0;
2197 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002198 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2199 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2200 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002201 }
2202
2203 @Override
2204 public boolean reset(boolean detachIfReset) {
2205 boolean result = super.reset(detachIfReset);
2206 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002207 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002208 mCurrentDurationMs = 0;
2209 if (mNesting > 0) {
2210 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2211 } else {
2212 mStartTimeMs = -1;
2213 }
2214 return result;
2215 }
2216
2217 /**
2218 * Returns the max duration that this timer has ever seen.
2219 *
2220 * Note that this time is NOT split between the timers in the timer group that
2221 * this timer is attached to. It is the TOTAL time.
2222 */
2223 @Override
2224 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2225 if (mNesting > 0) {
2226 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2227 if (durationMs > mMaxDurationMs) {
2228 return durationMs;
2229 }
2230 }
2231 return mMaxDurationMs;
2232 }
2233
2234 /**
2235 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002236 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002237 *
2238 * Note that this time is NOT split between the timers in the timer group that
2239 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002240 *
2241 * Note that if running timer is parceled and unparceled, this method will return
2242 * current duration value at the time of parceling even though timer may not be
2243 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002244 */
2245 @Override
2246 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2247 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002248 if (mNesting > 0 && mTimeBase.isRunning()) {
2249 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2250 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002251 }
2252 return durationMs;
2253 }
Bookatz867c0d72017-03-07 18:23:42 -08002254
2255 /**
2256 * Returns the total cumulative duration that this timer has been on since reset().
2257 * If mTimerPool == null, this should be the same
2258 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2259 *
2260 * Note that this time is NOT split between the timers in the timer group that
2261 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2262 * the result will not be equivalent to getTotalTimeLocked.
2263 */
2264 @Override
2265 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2266 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2267 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002268 }
2269
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002270 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002271 * State for keeping track of timing information.
2272 */
Joe Onoratoabded112016-02-08 16:49:39 -08002273 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002274 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002275 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002276
Evan Millarc64edde2009-04-18 12:26:32 -07002277 int mNesting;
2278
Evan Millarc64edde2009-04-18 12:26:32 -07002279 /**
2280 * The last time at which we updated the timer. If mNesting is > 0,
2281 * subtract this from the current battery time to find the amount of
2282 * time we have been running since we last computed an update.
2283 */
2284 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002285
Evan Millarc64edde2009-04-18 12:26:32 -07002286 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002287 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002288 * was actually held for an interesting duration. If time base was not running when timer
2289 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002290 */
Bookatzceebafe2017-04-06 11:59:13 -07002291 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002292
Amith Yamasanif37447b2009-10-08 18:28:01 -07002293 long mTimeout;
2294
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002295 /**
2296 * For partial wake locks, keep track of whether we are in the list
2297 * to consume CPU cycles.
2298 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002299 @VisibleForTesting
2300 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002301
Joe Onoratoabded112016-02-08 16:49:39 -08002302 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002303 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002304 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002305 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002306 mTimerPool = timerPool;
2307 mUpdateTime = in.readLong();
2308 }
2309
Joe Onoratoabded112016-02-08 16:49:39 -08002310 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002311 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002312 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002313 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002314 mTimerPool = timerPool;
2315 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002316
Joe Onoratoabded112016-02-08 16:49:39 -08002317 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002318 mTimeout = timeout;
2319 }
2320
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002321 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2322 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002323 out.writeLong(mUpdateTime);
2324 }
2325
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002326 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002327 if (mNesting > 0) {
2328 if (DEBUG && mType < 0) {
2329 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2330 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002331 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2332 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002333 if (DEBUG && mType < 0) {
2334 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2335 }
2336 }
2337 }
2338
2339 public void logState(Printer pw, String prefix) {
2340 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002341 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 + " mAcquireTime=" + mAcquireTime);
2343 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002344
Joe Onoratoabded112016-02-08 16:49:39 -08002345 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002347 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002348 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 if (mTimerPool != null) {
2350 // Accumulate time to all currently active timers before adding
2351 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002352 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 // Add this timer to the active pool
2354 mTimerPool.add(this);
2355 }
Bookatzceebafe2017-04-06 11:59:13 -07002356 if (mTimeBase.isRunning()) {
2357 // Increment the count
2358 mCount++;
2359 mAcquireTime = mTotalTime;
2360 } else {
2361 mAcquireTime = -1;
2362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 if (DEBUG && mType < 0) {
2364 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2365 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2366 + " mAcquireTime=" + mAcquireTime);
2367 }
2368 }
2369 }
2370
Joe Onoratoabded112016-02-08 16:49:39 -08002371 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002372 return mNesting > 0;
2373 }
2374
Joe Onoratoabded112016-02-08 16:49:39 -08002375 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 // Ignore attempt to stop a timer that isn't running
2377 if (mNesting == 0) {
2378 return;
2379 }
2380 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002381 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 if (mTimerPool != null) {
2383 // Accumulate time to all active counters, scaled by the total
2384 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002385 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 // Remove this timer from the active pool
2387 mTimerPool.remove(this);
2388 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 mNesting = 1;
2390 mTotalTime = computeRunTimeLocked(batteryRealtime);
2391 mNesting = 0;
2392 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 if (DEBUG && mType < 0) {
2395 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2396 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2397 + " mAcquireTime=" + mAcquireTime);
2398 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002399
Bookatzceebafe2017-04-06 11:59:13 -07002400 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 // If there was no change in the time, then discard this
2402 // count. A somewhat cheezy strategy, but hey.
2403 mCount--;
2404 }
2405 }
2406 }
2407
Joe Onoratoabded112016-02-08 16:49:39 -08002408 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002409 if (mNesting > 0) {
2410 mNesting = 1;
2411 stopRunningLocked(elapsedRealtimeMs);
2412 }
2413 }
2414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 // Update the total time for all other running Timers with the same type as this Timer
2416 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002417 private static long refreshTimersLocked(long batteryRealtime,
2418 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002419 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 final int N = pool.size();
2421 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002422 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 long heldTime = batteryRealtime - t.mUpdateTime;
2424 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002425 final long myTime = heldTime / N;
2426 if (t == self) {
2427 selfTime = myTime;
2428 }
2429 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 }
2431 t.mUpdateTime = batteryRealtime;
2432 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002433 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 }
2435
Evan Millarc64edde2009-04-18 12:26:32 -07002436 @Override
2437 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002438 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2439 curBatteryRealtime = mUpdateTime + mTimeout;
2440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 return mTotalTime + (mNesting > 0
2442 ? (curBatteryRealtime - mUpdateTime)
2443 / (mTimerPool != null ? mTimerPool.size() : 1)
2444 : 0);
2445 }
2446
Evan Millarc64edde2009-04-18 12:26:32 -07002447 @Override
2448 protected int computeCurrentCountLocked() {
2449 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 }
2451
Adam Lesinskie08af192015-03-25 16:42:59 -07002452 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002453 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002454 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002455 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002456 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002457 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002458 }
Bookatzceebafe2017-04-06 11:59:13 -07002459 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002460 return canDetach;
2461 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002462
Adam Lesinskie08af192015-03-25 16:42:59 -07002463 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002464 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002465 super.detach();
2466 if (mTimerPool != null) {
2467 mTimerPool.remove(this);
2468 }
2469 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002470
Adam Lesinskie08af192015-03-25 16:42:59 -07002471 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002472 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002473 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 mNesting = 0;
2475 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002476
2477 /**
2478 * Set the mark so that we can query later for the total time the timer has
2479 * accumulated since this point. The timer can be running or not.
2480 *
2481 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2482 */
2483 public void setMark(long elapsedRealtimeMs) {
2484 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2485 if (mNesting > 0) {
2486 // We are running.
2487 if (mTimerPool != null) {
2488 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2489 } else {
2490 mTotalTime += batteryRealtime - mUpdateTime;
2491 mUpdateTime = batteryRealtime;
2492 }
2493 }
2494 mTimeBeforeMark = mTotalTime;
2495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002497
Bookatz867c0d72017-03-07 18:23:42 -08002498 /**
2499 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2500 * TimeBase is effectively a subset of the other.
2501 */
Bookatzaa4594a2017-03-24 12:39:56 -07002502 public static class DualTimer extends DurationTimer {
2503 // This class both is a DurationTimer and also holds a second DurationTimer.
2504 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2505 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2506 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002507 // mSubTimer typically tracks only part of the total time, such as background time, as
2508 // determined by a subTimeBase. It is NOT pooled.
2509 private final DurationTimer mSubTimer;
2510
2511 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002512 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2513 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002514 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002515 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002516 */
2517 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2518 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002519 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002520 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2521 }
2522
2523 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002524 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2525 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002526 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002527 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002528 */
2529 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2530 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002531 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002532 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2533 }
2534
Bookatz867c0d72017-03-07 18:23:42 -08002535 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002536 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002537 public DurationTimer getSubTimer() {
2538 return mSubTimer;
2539 }
2540
Bookatzaa4594a2017-03-24 12:39:56 -07002541 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002542 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002543 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002544 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2545 }
2546
Bookatzaa4594a2017-03-24 12:39:56 -07002547 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002548 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002549 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002550 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2551 }
2552
Bookatzaa4594a2017-03-24 12:39:56 -07002553 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002554 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002555 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002556 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2557 }
2558
Bookatzaa4594a2017-03-24 12:39:56 -07002559 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002560 public boolean reset(boolean detachIfReset) {
2561 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002562 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2563 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002564 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002565 return !active;
2566 }
2567
Bookatzaa4594a2017-03-24 12:39:56 -07002568 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002569 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002570 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002571 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002572 }
2573
Bookatzaa4594a2017-03-24 12:39:56 -07002574 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002575 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002576 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002577 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2578 }
2579
Bookatzaa4594a2017-03-24 12:39:56 -07002580 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002581 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002582 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002583 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2584 }
2585
Bookatzaa4594a2017-03-24 12:39:56 -07002586 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002587 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002588 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002589 mSubTimer.readSummaryFromParcelLocked(in);
2590 }
2591 }
2592
2593
Dianne Hackbornd953c532014-08-16 18:17:38 -07002594 public abstract class OverflowArrayMap<T> {
2595 private static final String OVERFLOW_NAME = "*overflow*";
2596
Dianne Hackborn657153b2016-07-29 14:54:14 -07002597 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002598 final ArrayMap<String, T> mMap = new ArrayMap<>();
2599 T mCurOverflow;
2600 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002601 long mLastOverflowTime;
2602 long mLastOverflowFinishTime;
2603 long mLastClearTime;
2604 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002605
Dianne Hackborn657153b2016-07-29 14:54:14 -07002606 public OverflowArrayMap(int uid) {
2607 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002608 }
2609
2610 public ArrayMap<String, T> getMap() {
2611 return mMap;
2612 }
2613
2614 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002615 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002616 mMap.clear();
2617 mCurOverflow = null;
2618 mActiveOverflow = null;
2619 }
2620
2621 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002622 if (name == null) {
2623 name = "";
2624 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002625 mMap.put(name, obj);
2626 if (OVERFLOW_NAME.equals(name)) {
2627 mCurOverflow = obj;
2628 }
2629 }
2630
2631 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002632 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002633 if (mActiveOverflow != null) {
2634 if (mActiveOverflow.size() == 0) {
2635 mActiveOverflow = null;
2636 }
2637 }
2638 if (mActiveOverflow == null) {
2639 // There is no currently active overflow, so we should no longer have
2640 // an overflow entry.
2641 if (mMap.containsKey(OVERFLOW_NAME)) {
2642 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2643 + mMap.get(OVERFLOW_NAME));
2644 mMap.remove(OVERFLOW_NAME);
2645 }
2646 mCurOverflow = null;
2647 } else {
2648 // There is currently active overflow, so we should still have an overflow entry.
2649 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2650 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2651 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2652 }
2653 }
2654 }
2655
2656 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002657 if (name == null) {
2658 name = "";
2659 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002660 T obj = mMap.get(name);
2661 if (obj != null) {
2662 return obj;
2663 }
2664
2665 // No object exists for the given name, but do we currently have it
2666 // running as part of the overflow?
2667 if (mActiveOverflow != null) {
2668 MutableInt over = mActiveOverflow.get(name);
2669 if (over != null) {
2670 // We are already actively counting this name in the overflow object.
2671 obj = mCurOverflow;
2672 if (obj == null) {
2673 // Shouldn't be here, but we'll try to recover.
2674 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2675 obj = mCurOverflow = instantiateObject();
2676 mMap.put(OVERFLOW_NAME, obj);
2677 }
2678 over.value++;
2679 return obj;
2680 }
2681 }
2682
2683 // No object exists for given name nor in the overflow; we need to make
2684 // a new one.
2685 final int N = mMap.size();
2686 if (N >= MAX_WAKELOCKS_PER_UID) {
2687 // Went over the limit on number of objects to track; this one goes
2688 // in to the overflow.
2689 obj = mCurOverflow;
2690 if (obj == null) {
2691 // Need to start overflow now...
2692 obj = mCurOverflow = instantiateObject();
2693 mMap.put(OVERFLOW_NAME, obj);
2694 }
2695 if (mActiveOverflow == null) {
2696 mActiveOverflow = new ArrayMap<>();
2697 }
2698 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002699 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002700 return obj;
2701 }
2702
2703 // Normal case where we just need to make a new object.
2704 obj = instantiateObject();
2705 mMap.put(name, obj);
2706 return obj;
2707 }
2708
2709 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002710 if (name == null) {
2711 name = "";
2712 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002713 T obj = mMap.get(name);
2714 if (obj != null) {
2715 return obj;
2716 }
2717
2718 // No object exists for the given name, but do we currently have it
2719 // running as part of the overflow?
2720 if (mActiveOverflow != null) {
2721 MutableInt over = mActiveOverflow.get(name);
2722 if (over != null) {
2723 // We are already actively counting this name in the overflow object.
2724 obj = mCurOverflow;
2725 if (obj != null) {
2726 over.value--;
2727 if (over.value <= 0) {
2728 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002729 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002730 }
2731 return obj;
2732 }
2733 }
2734 }
2735
2736 // Huh, they are stopping an active operation but we can't find one!
2737 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002738 StringBuilder sb = new StringBuilder();
2739 sb.append("Unable to find object for ");
2740 sb.append(name);
2741 sb.append(" in uid ");
2742 sb.append(mUid);
2743 sb.append(" mapsize=");
2744 sb.append(mMap.size());
2745 sb.append(" activeoverflow=");
2746 sb.append(mActiveOverflow);
2747 sb.append(" curoverflow=");
2748 sb.append(mCurOverflow);
2749 long now = SystemClock.elapsedRealtime();
2750 if (mLastOverflowTime != 0) {
2751 sb.append(" lastOverflowTime=");
2752 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2753 }
2754 if (mLastOverflowFinishTime != 0) {
2755 sb.append(" lastOverflowFinishTime=");
2756 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2757 }
2758 if (mLastClearTime != 0) {
2759 sb.append(" lastClearTime=");
2760 TimeUtils.formatDuration(mLastClearTime-now, sb);
2761 }
2762 if (mLastCleanupTime != 0) {
2763 sb.append(" lastCleanupTime=");
2764 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2765 }
2766 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002767 return null;
2768 }
2769
2770 public abstract T instantiateObject();
2771 }
2772
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002773 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2774 implements Parcelable {
2775 private final LongSamplingCounter mIdleTimeMillis;
2776 private final LongSamplingCounter mRxTimeMillis;
2777 private final LongSamplingCounter[] mTxTimeMillis;
2778 private final LongSamplingCounter mPowerDrainMaMs;
2779
2780 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2781 mIdleTimeMillis = new LongSamplingCounter(timeBase);
2782 mRxTimeMillis = new LongSamplingCounter(timeBase);
2783 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2784 for (int i = 0; i < numTxStates; i++) {
2785 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2786 }
2787 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2788 }
2789
2790 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2791 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
2792 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2793 final int recordedTxStates = in.readInt();
2794 if (recordedTxStates != numTxStates) {
2795 throw new ParcelFormatException("inconsistent tx state lengths");
2796 }
2797
2798 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2799 for (int i = 0; i < numTxStates; i++) {
2800 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2801 }
2802 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2803 }
2804
2805 public void readSummaryFromParcel(Parcel in) {
2806 mIdleTimeMillis.readSummaryFromParcelLocked(in);
2807 mRxTimeMillis.readSummaryFromParcelLocked(in);
2808 final int recordedTxStates = in.readInt();
2809 if (recordedTxStates != mTxTimeMillis.length) {
2810 throw new ParcelFormatException("inconsistent tx state lengths");
2811 }
2812 for (LongSamplingCounter counter : mTxTimeMillis) {
2813 counter.readSummaryFromParcelLocked(in);
2814 }
2815 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2816 }
2817
2818 @Override
2819 public int describeContents() {
2820 return 0;
2821 }
2822
2823 public void writeSummaryToParcel(Parcel dest) {
2824 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
2825 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2826 dest.writeInt(mTxTimeMillis.length);
2827 for (LongSamplingCounter counter : mTxTimeMillis) {
2828 counter.writeSummaryFromParcelLocked(dest);
2829 }
2830 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2831 }
2832
2833 @Override
2834 public void writeToParcel(Parcel dest, int flags) {
2835 mIdleTimeMillis.writeToParcel(dest);
2836 mRxTimeMillis.writeToParcel(dest);
2837 dest.writeInt(mTxTimeMillis.length);
2838 for (LongSamplingCounter counter : mTxTimeMillis) {
2839 counter.writeToParcel(dest);
2840 }
2841 mPowerDrainMaMs.writeToParcel(dest);
2842 }
2843
2844 public void reset(boolean detachIfReset) {
2845 mIdleTimeMillis.reset(detachIfReset);
2846 mRxTimeMillis.reset(detachIfReset);
2847 for (LongSamplingCounter counter : mTxTimeMillis) {
2848 counter.reset(detachIfReset);
2849 }
2850 mPowerDrainMaMs.reset(detachIfReset);
2851 }
2852
2853 public void detach() {
2854 mIdleTimeMillis.detach();
2855 mRxTimeMillis.detach();
2856 for (LongSamplingCounter counter : mTxTimeMillis) {
2857 counter.detach();
2858 }
2859 mPowerDrainMaMs.detach();
2860 }
2861
2862 /**
2863 * @return a LongSamplingCounter, measuring time spent in the idle state in
2864 * milliseconds.
2865 */
2866 @Override
2867 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07002868 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002869 }
2870
2871 /**
2872 * @return a LongSamplingCounter, measuring time spent in the receive state in
2873 * milliseconds.
2874 */
2875 @Override
2876 public LongSamplingCounter getRxTimeCounter() {
2877 return mRxTimeMillis;
2878 }
2879
2880 /**
2881 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
2882 * milliseconds.
2883 */
2884 @Override
2885 public LongSamplingCounter[] getTxTimeCounters() {
2886 return mTxTimeMillis;
2887 }
2888
2889 /**
2890 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
2891 */
2892 @Override
2893 public LongSamplingCounter getPowerCounter() {
2894 return mPowerDrainMaMs;
2895 }
2896 }
2897
Bookatz50df7112017-08-04 14:53:26 -07002898 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
2899 public SamplingTimer getRpmTimerLocked(String name) {
2900 SamplingTimer rpmt = mRpmStats.get(name);
2901 if (rpmt == null) {
2902 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2903 mRpmStats.put(name, rpmt);
2904 }
2905 return rpmt;
2906 }
2907
2908 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
2909 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
2910 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
2911 if (rpmt == null) {
2912 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
2913 mScreenOffRpmStats.put(name, rpmt);
2914 }
2915 return rpmt;
2916 }
2917
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002918 /*
2919 * Get the wakeup reason counter, and create a new one if one
2920 * doesn't already exist.
2921 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002922 public SamplingTimer getWakeupReasonTimerLocked(String name) {
2923 SamplingTimer timer = mWakeupReasonStats.get(name);
2924 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002925 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002926 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002927 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002928 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002929 }
2930
Evan Millarc64edde2009-04-18 12:26:32 -07002931 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002932 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07002933 * doesn't already exist.
2934 */
2935 public SamplingTimer getKernelWakelockTimerLocked(String name) {
2936 SamplingTimer kwlt = mKernelWakelockStats.get(name);
2937 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002938 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07002939 mKernelWakelockStats.put(name, kwlt);
2940 }
2941 return kwlt;
2942 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07002943
James Carr3a226052016-07-01 14:49:52 -07002944 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
2945 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
2946 if (kmt == null) {
2947 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2948 mKernelMemoryStats.put(bucket, kmt);
2949 }
2950 return kmt;
2951 }
2952
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002953 private int writeHistoryTag(HistoryTag tag) {
2954 Integer idxObj = mHistoryTagPool.get(tag);
2955 int idx;
2956 if (idxObj != null) {
2957 idx = idxObj;
2958 } else {
2959 idx = mNextHistoryTagIdx;
2960 HistoryTag key = new HistoryTag();
2961 key.setTo(tag);
2962 tag.poolIdx = idx;
2963 mHistoryTagPool.put(key, idx);
2964 mNextHistoryTagIdx++;
2965 mNumHistoryTagChars += key.string.length() + 1;
2966 }
2967 return idx;
2968 }
2969
2970 private void readHistoryTag(int index, HistoryTag tag) {
2971 tag.string = mReadHistoryStrings[index];
2972 tag.uid = mReadHistoryUids[index];
2973 tag.poolIdx = index;
2974 }
2975
Adam Lesinski926969b2016-04-28 17:31:12 -07002976 /*
2977 The history delta format uses flags to denote further data in subsequent ints in the parcel.
2978
2979 There is always the first token, which may contain the delta time, or an indicator of
2980 the length of the time (int or long) following this token.
2981
2982 First token: always present,
2983 31 23 15 7 0
2984 â–ˆ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â–ˆ
2985
2986 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
2987 follows containing the time, and 0x7ffff indicates a long immediately follows with the
2988 delta time.
2989 A: battery level changed and an int follows with battery data.
2990 B: state changed and an int follows with state change data.
2991 C: state2 has changed and an int follows with state2 change data.
2992 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
2993 E: event data has changed and an event struct follows.
2994 F: battery charge in coulombs has changed and an int with the charge follows.
2995 G: state flag denoting that the mobile radio was active.
2996 H: state flag denoting that the wifi radio was active.
2997 I: state flag denoting that a wifi scan occurred.
2998 J: state flag denoting that a wifi full lock was held.
2999 K: state flag denoting that the gps was on.
3000 L: state flag denoting that a wakelock was held.
3001 M: state flag denoting that the cpu was running.
3002
3003 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3004 with the time delta.
3005
3006 Battery level int: if A in the first token is set,
3007 31 23 15 7 0
3008 â–ˆ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â–ˆ
3009
3010 D: indicates that extra history details follow.
3011 V: the battery voltage.
3012 T: the battery temperature.
3013 L: the battery level (out of 100).
3014
3015 State change int: if B in the first token is set,
3016 31 23 15 7 0
3017 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3018
3019 A: wifi multicast was on.
3020 B: battery was plugged in.
3021 C: screen was on.
3022 D: phone was scanning for signal.
3023 E: audio was on.
3024 F: a sensor was active.
3025
3026 State2 change int: if C in the first token is set,
3027 31 23 15 7 0
3028 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3029
3030 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3031 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3032 C: a bluetooth scan was active.
3033 D: the camera was active.
3034 E: bluetooth was on.
3035 F: a phone call was active.
3036 G: the device was charging.
3037 H: 2 bits indicating the device-idle (doze) state: off, light, full
3038 I: the flashlight was on.
3039 J: wifi was on.
3040 K: wifi was running.
3041 L: video was playing.
3042 M: power save mode was on.
3043
3044 Wakelock/wakereason struct: if D in the first token is set,
3045 TODO(adamlesinski): describe wakelock/wakereason struct.
3046
3047 Event struct: if E in the first token is set,
3048 TODO(adamlesinski): describe the event struct.
3049
3050 History step details struct: if D in the battery level int is set,
3051 TODO(adamlesinski): describe the history step details struct.
3052
3053 Battery charge int: if F in the first token is set, an int representing the battery charge
3054 in coulombs follows.
3055 */
3056
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003057 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003058 static final int DELTA_TIME_MASK = 0x7ffff;
3059 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3060 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3061 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003062 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003063 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003064 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003065 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003066 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003067 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003068 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003069 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003070 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003071 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003072 // Flag in delta int: contains the battery charge count in uAh.
3073 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003074 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003075 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003076
3077 // These are the pieces of battery state that are packed in to the upper bits of
3078 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003079 // in STATE_BATTERY_MASK.
3080 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003081 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3082 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3083 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3084 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3085 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3086 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003087
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003088 // We use the low bit of the battery state int to indicate that we have full details
3089 // from a battery level change.
3090 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3091
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003092 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003093 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003094 dest.writeInt(DELTA_TIME_ABS);
3095 cur.writeToParcel(dest, 0);
3096 return;
3097 }
3098
3099 final long deltaTime = cur.time - last.time;
3100 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3101 final int lastStateInt = buildStateInt(last);
3102
3103 int deltaTimeToken;
3104 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3105 deltaTimeToken = DELTA_TIME_LONG;
3106 } else if (deltaTime >= DELTA_TIME_ABS) {
3107 deltaTimeToken = DELTA_TIME_INT;
3108 } else {
3109 deltaTimeToken = (int)deltaTime;
3110 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003111 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003112 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3113 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3114 final boolean computeStepDetails = includeStepDetails != 0
3115 || mLastHistoryStepDetails == null;
3116 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003117 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3118 if (batteryLevelIntChanged) {
3119 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3120 }
3121 final int stateInt = buildStateInt(cur);
3122 final boolean stateIntChanged = stateInt != lastStateInt;
3123 if (stateIntChanged) {
3124 firstToken |= DELTA_STATE_FLAG;
3125 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003126 final boolean state2IntChanged = cur.states2 != last.states2;
3127 if (state2IntChanged) {
3128 firstToken |= DELTA_STATE2_FLAG;
3129 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003130 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003131 firstToken |= DELTA_WAKELOCK_FLAG;
3132 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003133 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3134 firstToken |= DELTA_EVENT_FLAG;
3135 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003136
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003137 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3138 if (batteryChargeChanged) {
3139 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003140 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003141 dest.writeInt(firstToken);
3142 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3143 + " deltaTime=" + deltaTime);
3144
3145 if (deltaTimeToken >= DELTA_TIME_INT) {
3146 if (deltaTimeToken == DELTA_TIME_INT) {
3147 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3148 dest.writeInt((int)deltaTime);
3149 } else {
3150 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3151 dest.writeLong(deltaTime);
3152 }
3153 }
3154 if (batteryLevelIntChanged) {
3155 dest.writeInt(batteryLevelInt);
3156 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3157 + Integer.toHexString(batteryLevelInt)
3158 + " batteryLevel=" + cur.batteryLevel
3159 + " batteryTemp=" + cur.batteryTemperature
3160 + " batteryVolt=" + (int)cur.batteryVoltage);
3161 }
3162 if (stateIntChanged) {
3163 dest.writeInt(stateInt);
3164 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3165 + Integer.toHexString(stateInt)
3166 + " batteryStatus=" + cur.batteryStatus
3167 + " batteryHealth=" + cur.batteryHealth
3168 + " batteryPlugType=" + cur.batteryPlugType
3169 + " states=0x" + Integer.toHexString(cur.states));
3170 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003171 if (state2IntChanged) {
3172 dest.writeInt(cur.states2);
3173 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3174 + Integer.toHexString(cur.states2));
3175 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003176 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3177 int wakeLockIndex;
3178 int wakeReasonIndex;
3179 if (cur.wakelockTag != null) {
3180 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3181 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3182 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3183 } else {
3184 wakeLockIndex = 0xffff;
3185 }
3186 if (cur.wakeReasonTag != null) {
3187 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3188 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3189 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3190 } else {
3191 wakeReasonIndex = 0xffff;
3192 }
3193 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003194 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003195 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003196 int index = writeHistoryTag(cur.eventTag);
3197 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003198 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003199 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3200 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3201 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003202 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003203 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003204 if (mPlatformIdleStateCallback != null) {
3205 mCurHistoryStepDetails.statPlatformIdleState =
3206 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3207 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3208 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003209
3210 mCurHistoryStepDetails.statSubsystemPowerState =
3211 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3212 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3213 mCurHistoryStepDetails.statSubsystemPowerState);
3214
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003215 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003216 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3217 if (includeStepDetails != 0) {
3218 mCurHistoryStepDetails.writeToParcel(dest);
3219 }
3220 cur.stepDetails = mCurHistoryStepDetails;
3221 mLastHistoryStepDetails = mCurHistoryStepDetails;
3222 } else {
3223 cur.stepDetails = null;
3224 }
3225 if (mLastHistoryStepLevel < cur.batteryLevel) {
3226 mLastHistoryStepDetails = null;
3227 }
3228 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003229
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003230 if (batteryChargeChanged) {
3231 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3232 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003233 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003234 }
3235
3236 private int buildBatteryLevelInt(HistoryItem h) {
3237 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003238 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3239 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3240 }
3241
3242 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3243 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3244 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3245 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003246 }
3247
3248 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003249 int plugType = 0;
3250 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3251 plugType = 1;
3252 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3253 plugType = 2;
3254 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3255 plugType = 3;
3256 }
3257 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3258 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3259 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003260 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003261 }
3262
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003263 private void computeHistoryStepDetails(final HistoryStepDetails out,
3264 final HistoryStepDetails last) {
3265 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3266
3267 // Perform a CPU update right after we do this collection, so we have started
3268 // collecting good data for the next step.
3269 requestImmediateCpuUpdate();
3270
3271 if (last == null) {
3272 // We are not generating a delta, so all we need to do is reset the stats
3273 // we will later be doing a delta from.
3274 final int NU = mUidStats.size();
3275 for (int i=0; i<NU; i++) {
3276 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3277 uid.mLastStepUserTime = uid.mCurStepUserTime;
3278 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3279 }
3280 mLastStepCpuUserTime = mCurStepCpuUserTime;
3281 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3282 mLastStepStatUserTime = mCurStepStatUserTime;
3283 mLastStepStatSystemTime = mCurStepStatSystemTime;
3284 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3285 mLastStepStatIrqTime = mCurStepStatIrqTime;
3286 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3287 mLastStepStatIdleTime = mCurStepStatIdleTime;
3288 tmp.clear();
3289 return;
3290 }
3291 if (DEBUG) {
3292 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3293 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3294 + " irq=" + mLastStepStatIrqTime + " sirq="
3295 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3296 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3297 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3298 + " irq=" + mCurStepStatIrqTime + " sirq="
3299 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3300 }
3301 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3302 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3303 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3304 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3305 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3306 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3307 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3308 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3309 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3310 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3311 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3312 final int NU = mUidStats.size();
3313 for (int i=0; i<NU; i++) {
3314 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3315 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3316 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3317 final int totalTime = totalUTime + totalSTime;
3318 uid.mLastStepUserTime = uid.mCurStepUserTime;
3319 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3320 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3321 continue;
3322 }
3323 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3324 out.appCpuUid3 = uid.mUid;
3325 out.appCpuUTime3 = totalUTime;
3326 out.appCpuSTime3 = totalSTime;
3327 } else {
3328 out.appCpuUid3 = out.appCpuUid2;
3329 out.appCpuUTime3 = out.appCpuUTime2;
3330 out.appCpuSTime3 = out.appCpuSTime2;
3331 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3332 out.appCpuUid2 = uid.mUid;
3333 out.appCpuUTime2 = totalUTime;
3334 out.appCpuSTime2 = totalSTime;
3335 } else {
3336 out.appCpuUid2 = out.appCpuUid1;
3337 out.appCpuUTime2 = out.appCpuUTime1;
3338 out.appCpuSTime2 = out.appCpuSTime1;
3339 out.appCpuUid1 = uid.mUid;
3340 out.appCpuUTime1 = totalUTime;
3341 out.appCpuSTime1 = totalSTime;
3342 }
3343 }
3344 }
3345 mLastStepCpuUserTime = mCurStepCpuUserTime;
3346 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3347 mLastStepStatUserTime = mCurStepStatUserTime;
3348 mLastStepStatSystemTime = mCurStepStatSystemTime;
3349 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3350 mLastStepStatIrqTime = mCurStepStatIrqTime;
3351 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3352 mLastStepStatIdleTime = mCurStepStatIdleTime;
3353 }
3354
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003355 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3356 int firstToken = src.readInt();
3357 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003358 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003359 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003360 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3361 + " deltaTimeToken=" + deltaTimeToken);
3362
3363 if (deltaTimeToken < DELTA_TIME_ABS) {
3364 cur.time += deltaTimeToken;
3365 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3366 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003367 cur.numReadInts += 2;
3368 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003369 cur.readFromParcel(src);
3370 return;
3371 } else if (deltaTimeToken == DELTA_TIME_INT) {
3372 int delta = src.readInt();
3373 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003374 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003375 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3376 } else {
3377 long delta = src.readLong();
3378 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3379 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003380 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003381 }
3382
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003383 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003384 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003385 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003386 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003387 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003388 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3389 + Integer.toHexString(batteryLevelInt)
3390 + " batteryLevel=" + cur.batteryLevel
3391 + " batteryTemp=" + cur.batteryTemperature
3392 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003393 } else {
3394 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003395 }
3396
3397 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3398 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003399 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003400 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3401 & STATE_BATTERY_STATUS_MASK);
3402 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3403 & STATE_BATTERY_HEALTH_MASK);
3404 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3405 & STATE_BATTERY_PLUG_MASK);
3406 switch (cur.batteryPlugType) {
3407 case 1:
3408 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3409 break;
3410 case 2:
3411 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3412 break;
3413 case 3:
3414 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3415 break;
3416 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003417 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003418 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3419 + Integer.toHexString(stateInt)
3420 + " batteryStatus=" + cur.batteryStatus
3421 + " batteryHealth=" + cur.batteryHealth
3422 + " batteryPlugType=" + cur.batteryPlugType
3423 + " states=0x" + Integer.toHexString(cur.states));
3424 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003425 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003426 }
3427
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003428 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3429 cur.states2 = src.readInt();
3430 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3431 + Integer.toHexString(cur.states2));
3432 }
3433
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003434 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003435 int indexes = src.readInt();
3436 int wakeLockIndex = indexes&0xffff;
3437 int wakeReasonIndex = (indexes>>16)&0xffff;
3438 if (wakeLockIndex != 0xffff) {
3439 cur.wakelockTag = cur.localWakelockTag;
3440 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3441 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3442 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3443 } else {
3444 cur.wakelockTag = null;
3445 }
3446 if (wakeReasonIndex != 0xffff) {
3447 cur.wakeReasonTag = cur.localWakeReasonTag;
3448 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3449 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3450 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3451 } else {
3452 cur.wakeReasonTag = null;
3453 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003454 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003455 } else {
3456 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003457 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003458 }
3459
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003460 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003461 cur.eventTag = cur.localEventTag;
3462 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003463 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003464 final int index = ((codeAndIndex>>16)&0xffff);
3465 readHistoryTag(index, cur.eventTag);
3466 cur.numReadInts += 1;
3467 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3468 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3469 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003470 } else {
3471 cur.eventCode = HistoryItem.EVENT_NONE;
3472 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003473
3474 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3475 cur.stepDetails = mReadHistoryStepDetails;
3476 cur.stepDetails.readFromParcel(src);
3477 } else {
3478 cur.stepDetails = null;
3479 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003480
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003481 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3482 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003483 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003484 }
3485
Dianne Hackbornfc064132014-06-02 12:42:12 -07003486 @Override
3487 public void commitCurrentHistoryBatchLocked() {
3488 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3489 }
3490
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003491 void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003492 if (!mHaveBatteryLevel || !mRecordingHistory) {
3493 return;
3494 }
3495
Dianne Hackborn40c87252014-03-19 16:55:40 -07003496 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003497 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3498 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003499 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003500 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003501 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3502 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003503 + Integer.toHexString(lastDiffStates) + " diff2="
3504 + Integer.toHexString(diffStates2) + " lastDiff2="
3505 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003506 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003507 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003508 && (diffStates2&lastDiffStates2) == 0
3509 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3510 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003511 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003512 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003513 || cur.eventCode == HistoryItem.EVENT_NONE)
3514 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3515 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3516 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3517 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3518 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3519 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003520 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003521 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003522 // as long as no bit has changed both between now and the last entry, as
3523 // well as the last entry and the one before it (so we capture any toggles).
3524 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003525 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3526 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3527 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003528 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003529 // If the last written history had a wakelock tag, we need to retain it.
3530 // Note that the condition above made sure that we aren't in a case where
3531 // both it and the current history item have a wakelock tag.
3532 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003533 cur.wakelockTag = cur.localWakelockTag;
3534 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003535 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003536 // If the last written history had a wake reason tag, we need to retain it.
3537 // Note that the condition above made sure that we aren't in a case where
3538 // both it and the current history item have a wakelock tag.
3539 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003540 cur.wakeReasonTag = cur.localWakeReasonTag;
3541 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003542 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003543 // If the last written history had an event, we need to retain it.
3544 // Note that the condition above made sure that we aren't in a case where
3545 // both it and the current history item have an event.
3546 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003547 cur.eventCode = mHistoryLastWritten.eventCode;
3548 cur.eventTag = cur.localEventTag;
3549 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003550 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003551 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003552 }
3553
Adam Lesinski45489782016-12-15 23:45:17 -08003554 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003555 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003556 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3557 // Clients can't deal with history buffers this large. This only
3558 // really happens when the device is on charger and interacted with
3559 // for long periods of time, like in retail mode. Since the device is
3560 // most likely charged, when unplugged, stats would have reset anyways.
3561 // Reset the stats and mark that we overflowed.
3562 // b/32540341
3563 resetAllStatsLocked();
3564
3565 // Mark that we want to set *OVERFLOW* event and the RESET:START
3566 // events.
3567 recordResetDueToOverflow = true;
3568
3569 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003570 if (!mHistoryOverflow) {
3571 mHistoryOverflow = true;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003572 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
3573 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003574 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003575 }
3576
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003577 // After overflow, we allow various bit-wise states to settle to 0.
3578 boolean writeAnyway = false;
3579 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3580 & mActiveHistoryStates;
3581 if (mHistoryLastWritten.states != curStates) {
3582 // mActiveHistoryStates keeps track of which bits in .states are now being
3583 // forced to 0.
3584 int old = mActiveHistoryStates;
3585 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3586 writeAnyway |= old != mActiveHistoryStates;
3587 }
3588 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3589 & mActiveHistoryStates2;
3590 if (mHistoryLastWritten.states2 != curStates2) {
3591 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3592 // forced to 0.
3593 int old = mActiveHistoryStates2;
3594 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3595 writeAnyway |= old != mActiveHistoryStates2;
3596 }
3597
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003598 // Once we've reached the maximum number of items, we only
3599 // record changes to the battery level and the most interesting states.
3600 // Once we've reached the maximum maximum number of items, we only
3601 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003602 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003603 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003604 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003605 & HistoryItem.MOST_INTERESTING_STATES) == 0
3606 || ((mHistoryLastWritten.states2^cur.states2)
3607 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003608 return;
3609 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003610
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003611 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003612 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003613 }
3614
Adam Lesinski45489782016-12-15 23:45:17 -08003615 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003616 // The history is currently empty; we need it to start with a time stamp.
3617 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003618 if (recordResetDueToOverflow) {
3619 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
3620 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003621 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_RESET, cur);
3622 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003623 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003624 }
3625
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003626 private void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd,
3627 HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003628 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003629 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003630 }
3631 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3632 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003633 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003634 mHistoryLastWritten.states &= mActiveHistoryStates;
3635 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003636 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003637 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003638 cur.wakelockTag = null;
3639 cur.wakeReasonTag = null;
3640 cur.eventCode = HistoryItem.EVENT_NONE;
3641 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003642 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3643 + " now " + mHistoryBuffer.dataPosition()
3644 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003645 }
3646
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003647 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003648 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003649
Dianne Hackborn40c87252014-03-19 16:55:40 -07003650 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003651 if (mTrackRunningHistoryElapsedRealtime != 0) {
3652 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3653 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3654 if (diffUptime < (diffElapsed-20)) {
3655 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3656 mHistoryAddTmp.setTo(mHistoryLastWritten);
3657 mHistoryAddTmp.wakelockTag = null;
3658 mHistoryAddTmp.wakeReasonTag = null;
3659 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3660 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
3661 addHistoryRecordInnerLocked(wakeElapsedTime, uptimeMs, mHistoryAddTmp);
3662 }
3663 }
3664 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3665 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3666 mTrackRunningHistoryUptime = uptimeMs;
3667 addHistoryRecordInnerLocked(elapsedRealtimeMs, uptimeMs, mHistoryCur);
3668 }
3669
3670 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
3671 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003672
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003673 if (!USE_OLD_HISTORY) {
3674 return;
3675 }
3676
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003677 if (!mHaveBatteryLevel || !mRecordingHistory) {
3678 return;
3679 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003680
3681 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003682 // and no states have since the last recorded entry changed and
3683 // are now resetting back to their original value, then just collapse
3684 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003685 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003686 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003687 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3688 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003689 // If the current is the same as the one before, then we no
3690 // longer need the entry.
3691 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003692 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003693 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003694 mHistoryLastEnd.next = null;
3695 mHistoryEnd.next = mHistoryCache;
3696 mHistoryCache = mHistoryEnd;
3697 mHistoryEnd = mHistoryLastEnd;
3698 mHistoryLastEnd = null;
3699 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003700 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3701 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003702 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003703 }
3704 return;
3705 }
3706
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003707 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003708 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003709
3710 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3711 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07003712 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003713 }
3714
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003715 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3716 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003717 // record changes to the battery level and the most interesting states.
3718 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003719 // record changes to the battery level.
3720 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003721 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003722 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003723 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003724 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003725 return;
3726 }
3727 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003728
Dianne Hackborn40c87252014-03-19 16:55:40 -07003729 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003730 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003731
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003732 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003733 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003734 mHistoryCur.eventCode = code;
3735 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3736 mHistoryCur.eventTag.string = name;
3737 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003738 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003739 }
3740
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003741 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003742 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003743 if (rec != null) {
3744 mHistoryCache = rec.next;
3745 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003746 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003747 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003748 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003749
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003750 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003751 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003752
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003753 void addHistoryRecordLocked(HistoryItem rec) {
3754 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003755 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003756 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003757 if (mHistoryEnd != null) {
3758 mHistoryEnd.next = rec;
3759 mHistoryEnd = rec;
3760 } else {
3761 mHistory = mHistoryEnd = rec;
3762 }
3763 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003764
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003765 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003766 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003767 if (USE_OLD_HISTORY) {
3768 if (mHistory != null) {
3769 mHistoryEnd.next = mHistoryCache;
3770 mHistoryCache = mHistory;
3771 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3772 }
3773 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003774 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003775
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003776 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003777 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003778 mTrackRunningHistoryElapsedRealtime = 0;
3779 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003780
3781 mHistoryBuffer.setDataSize(0);
3782 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003783 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003784 mHistoryLastLastWritten.clear();
3785 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003786 mHistoryTagPool.clear();
3787 mNextHistoryTagIdx = 0;
3788 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003789 mHistoryBufferLastPos = -1;
3790 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003791 mActiveHistoryStates = 0xffffffff;
3792 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003793 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003794
Mike Mac2f518a2017-09-19 16:06:03 -07003795 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003796 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003797 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003798 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3799 final boolean updateOnBatteryScreenOffTimeBase =
3800 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003801
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003802 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3803 if (updateOnBatteryScreenOffTimeBase) {
3804 updateKernelWakelocksLocked();
3805 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003806 }
Bookatz82b341172017-09-07 19:06:08 -07003807 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3808 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3809 // improved, remove the surrounding if{}.
3810 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3811 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3812 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003813 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003814 Slog.d(TAG, "Updating cpu time because screen is now "
3815 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003816 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003817 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -07003818 updateCpuTimeLocked();
Sudheer Shankae544d162017-12-28 17:06:20 -08003819 mExternalSync.scheduleCopyFromAllUidsCpuTimes(mOnBatteryTimeBase.isRunning(),
3820 mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003821
3822 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07003823 if (updateOnBatteryTimeBase) {
3824 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3825 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003826 }
Mike Mac2f518a2017-09-19 16:06:03 -07003827 }
3828 if (updateOnBatteryScreenOffTimeBase) {
3829 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
3830 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3831 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003832 }
Bookatzc8c44962017-05-11 12:12:54 -07003833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 }
3835 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003836
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003837 private void updateBatteryPropertiesLocked() {
3838 try {
3839 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
3840 ServiceManager.getService("batteryproperties"));
3841 registrar.scheduleUpdate();
3842 } catch (RemoteException e) {
3843 // Ignore.
3844 }
3845 }
3846
Dianne Hackborn099bc622014-01-22 13:39:16 -08003847 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
3848 mIsolatedUids.put(isolatedUid, appUid);
David Chen21582962017-11-01 17:32:46 -07003849 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid, 1);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003850 final Uid u = getUidStatsLocked(appUid);
3851 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003852 }
3853
Adam Lesinski61db88f2015-07-01 15:05:07 -07003854 /**
3855 * Schedules a read of the latest cpu times before removing the isolated UID.
3856 * @see #removeIsolatedUidLocked(int)
3857 */
3858 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003859 int curUid = mIsolatedUids.get(isolatedUid, -1);
3860 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07003861 if (mExternalSync != null) {
3862 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
3863 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08003864 }
3865 }
3866
Adam Lesinski61db88f2015-07-01 15:05:07 -07003867 /**
3868 * This should only be called after the cpu times have been read.
3869 * @see #scheduleRemoveIsolatedUidLocked(int, int)
3870 */
3871 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003872 StatsLog.write(
3873 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1), isolatedUid, 0);
3874 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
3875 if (idx >= 0) {
3876 final int ownerUid = mIsolatedUids.valueAt(idx);
3877 final Uid u = getUidStatsLocked(ownerUid);
3878 u.removeIsolatedUid(isolatedUid);
3879 mIsolatedUids.removeAt(idx);
3880 }
3881 mKernelUidCpuTimeReader.removeUid(isolatedUid);
3882 mKernelUidCpuFreqTimeReader.removeUid(isolatedUid);
Adam Lesinski61db88f2015-07-01 15:05:07 -07003883 }
3884
Dianne Hackborn099bc622014-01-22 13:39:16 -08003885 public int mapUid(int uid) {
3886 int isolated = mIsolatedUids.get(uid, -1);
3887 return isolated > 0 ? isolated : uid;
3888 }
3889
3890 public void noteEventLocked(int code, String name, int uid) {
3891 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003892 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3893 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003894 }
Joe Onoratoabded112016-02-08 16:49:39 -08003895 final long elapsedRealtime = mClocks.elapsedRealtime();
3896 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003897 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003898 }
3899
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003900 boolean ensureStartClockTime(final long currentTime) {
3901 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
3902 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
3903 // If the start clock time has changed by more than a year, then presumably
3904 // the previous time was completely bogus. So we are going to figure out a
3905 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08003906 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003907 return true;
3908 }
3909 return false;
3910 }
3911
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003912 public void noteCurrentTimeChangedLocked() {
3913 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003914 final long elapsedRealtime = mClocks.elapsedRealtime();
3915 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003916 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003917 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003918 }
3919
Dianne Hackborn61659e52014-07-09 16:13:01 -07003920 public void noteProcessStartLocked(String name, int uid) {
3921 uid = mapUid(uid);
3922 if (isOnBattery()) {
3923 Uid u = getUidStatsLocked(uid);
3924 u.getProcessStatsLocked(name).incStartsLocked();
3925 }
3926 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3927 return;
3928 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003929 if (!mRecordAllHistory) {
3930 return;
3931 }
Joe Onoratoabded112016-02-08 16:49:39 -08003932 final long elapsedRealtime = mClocks.elapsedRealtime();
3933 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07003934 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
3935 }
3936
Dianne Hackborn1e01d162014-12-04 17:46:42 -08003937 public void noteProcessCrashLocked(String name, int uid) {
3938 uid = mapUid(uid);
3939 if (isOnBattery()) {
3940 Uid u = getUidStatsLocked(uid);
3941 u.getProcessStatsLocked(name).incNumCrashesLocked();
3942 }
3943 }
3944
3945 public void noteProcessAnrLocked(String name, int uid) {
3946 uid = mapUid(uid);
3947 if (isOnBattery()) {
3948 Uid u = getUidStatsLocked(uid);
3949 u.getProcessStatsLocked(name).incNumAnrsLocked();
3950 }
3951 }
3952
Dianne Hackborna8d10942015-11-19 17:55:19 -08003953 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07003954 int parentUid = mapUid(uid);
3955 if (uid != parentUid) {
3956 // Isolated UIDs process state is already rolled up into parent, so no need to track
3957 // Otherwise the parent's process state will get downgraded incorrectly
3958 return;
3959 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08003960 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003961 }
3962
3963 public void noteProcessFinishLocked(String name, int uid) {
3964 uid = mapUid(uid);
3965 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
3966 return;
3967 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003968 if (!mRecordAllHistory) {
3969 return;
3970 }
Joe Onoratoabded112016-02-08 16:49:39 -08003971 final long elapsedRealtime = mClocks.elapsedRealtime();
3972 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003973 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003974 }
3975
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003976 public void noteSyncStartLocked(String name, int uid) {
3977 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003978 final long elapsedRealtime = mClocks.elapsedRealtime();
3979 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003980 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
3981 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
3982 return;
3983 }
3984 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
3985 }
3986
3987 public void noteSyncFinishLocked(String name, int uid) {
3988 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003989 final long elapsedRealtime = mClocks.elapsedRealtime();
3990 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003991 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
3992 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
3993 return;
3994 }
3995 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
3996 }
3997
3998 public void noteJobStartLocked(String name, int uid) {
3999 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004000 final long elapsedRealtime = mClocks.elapsedRealtime();
4001 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004002 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4003 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4004 return;
4005 }
4006 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4007 }
4008
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004009 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004010 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004011 final long elapsedRealtime = mClocks.elapsedRealtime();
4012 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004013 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004014 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4015 return;
4016 }
4017 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4018 }
4019
Narayan Kamath695cf722017-12-21 18:32:47 +00004020 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4021 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004022 }
4023
Narayan Kamath695cf722017-12-21 18:32:47 +00004024 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4025 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4026 }
4027
4028 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4029 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004030 if (!mRecordAllHistory) {
4031 return;
4032 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004033
Joe Onoratoabded112016-02-08 16:49:39 -08004034 final long elapsedRealtime = mClocks.elapsedRealtime();
4035 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004036
4037 if (workSource != null) {
4038 for (int i = 0; i < workSource.size(); ++i) {
4039 uid = mapUid(workSource.get(i));
4040 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4041 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4042 }
4043 }
4044
4045 List<WorkChain> workChains = workSource.getWorkChains();
4046 if (workChains != null) {
4047 for (int i = 0; i < workChains.size(); ++i) {
4048 uid = mapUid(workChains.get(i).getAttributionUid());
4049 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4050 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4051 }
4052 }
4053 }
4054 } else {
4055 uid = mapUid(uid);
4056
4057 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4058 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4059 }
4060 }
4061 }
4062
4063 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4064 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004065
4066 if (workSource != null) {
4067 for (int i = 0; i < workSource.size(); ++i) {
4068 uid = workSource.get(i);
4069 final String workSourceName = workSource.getName(i);
4070
Tej Singh6f724c42018-01-03 20:02:03 -08004071 if (isOnBattery()) {
4072 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4073 workSourceName != null ? workSourceName : packageName);
4074 pkg.noteWakeupAlarmLocked(tag);
4075 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004076
4077 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, uid, tag);
4078 }
4079
4080 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4081 if (workChains != null) {
4082 for (int i = 0; i < workChains.size(); ++i) {
4083 final WorkChain wc = workChains.get(i);
4084 uid = wc.getAttributionUid();
4085
Tej Singh6f724c42018-01-03 20:02:03 -08004086 if (isOnBattery()) {
4087 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4088 pkg.noteWakeupAlarmLocked(tag);
4089 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004090
4091 // TODO(statsd): Log the full attribution chain here once it's available
4092 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, uid, tag);
4093 }
4094 }
4095 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004096 if (isOnBattery()) {
4097 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4098 pkg.noteWakeupAlarmLocked(tag);
4099 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004100 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, uid, tag);
4101 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004102 }
4103
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004104 private void requestWakelockCpuUpdate() {
4105 if (!mHandler.hasMessages(MSG_UPDATE_WAKELOCKS)) {
4106 Message m = mHandler.obtainMessage(MSG_UPDATE_WAKELOCKS);
4107 mHandler.sendMessageDelayed(m, DELAY_UPDATE_WAKELOCKS);
4108 }
4109 }
4110
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004111 private void requestImmediateCpuUpdate() {
4112 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
4113 mHandler.sendEmptyMessage(MSG_UPDATE_WAKELOCKS);
4114 }
4115
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004116 public void setRecordAllHistoryLocked(boolean enabled) {
4117 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004118 if (!enabled) {
4119 // Clear out any existing state.
4120 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004121 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004122 // Record the currently running processes as stopping, now that we are no
4123 // longer tracking them.
4124 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4125 HistoryItem.EVENT_PROC);
4126 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004127 long mSecRealtime = mClocks.elapsedRealtime();
4128 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004129 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4130 SparseIntArray uids = ent.getValue();
4131 for (int j=0; j<uids.size(); j++) {
4132 addHistoryEventLocked(mSecRealtime, mSecUptime,
4133 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4134 }
4135 }
4136 }
4137 } else {
4138 // Record the currently running processes as starting, now that we are tracking them.
4139 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4140 HistoryItem.EVENT_PROC);
4141 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004142 long mSecRealtime = mClocks.elapsedRealtime();
4143 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004144 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4145 SparseIntArray uids = ent.getValue();
4146 for (int j=0; j<uids.size(); j++) {
4147 addHistoryEventLocked(mSecRealtime, mSecUptime,
4148 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4149 }
4150 }
4151 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004152 }
4153 }
4154
Dianne Hackborn9a755432014-05-15 17:05:22 -07004155 public void setNoAutoReset(boolean enabled) {
4156 mNoAutoReset = enabled;
4157 }
4158
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004159 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004160 if (mPretendScreenOff != pretendScreenOff) {
4161 mPretendScreenOff = pretendScreenOff;
4162 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4163 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004164 }
4165
Dianne Hackborn9a755432014-05-15 17:05:22 -07004166 private String mInitialAcquireWakeName;
4167 private int mInitialAcquireWakeUid = -1;
4168
Narayan Kamath81822022017-12-08 11:56:01 +00004169 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4170 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004171 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004172 if (type == WAKE_TYPE_PARTIAL) {
4173 // Only care about partial wake locks, since full wake locks
4174 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004175 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004176 if (historyName == null) {
4177 historyName = name;
4178 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004179 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004180 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4181 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004182 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004183 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004184 }
4185 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004186 if (mWakeLockNesting == 0) {
4187 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4188 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4189 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004190 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004191 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004192 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004193 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004194 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004195 } else if (!mWakeLockImportant && !unimportantForLogging
4196 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004197 if (mHistoryLastWritten.wakelockTag != null) {
4198 // We'll try to update the last tag.
4199 mHistoryLastWritten.wakelockTag = null;
4200 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004201 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004202 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004203 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004204 }
4205 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004206 }
4207 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004208 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004209 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004210 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4211 // We only update the cpu time when a wake lock is acquired if the screen is off.
4212 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4213 if (DEBUG_ENERGY_CPU) {
4214 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4215 }
4216 requestWakelockCpuUpdate();
4217 }
Narayan Kamath81822022017-12-08 11:56:01 +00004218
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004219 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004220
Yangster-mac20877162017-12-22 17:19:39 -08004221 if (wc != null) {
4222 StatsLog.write(
4223 StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(), type, name, 1);
Narayan Kamath81822022017-12-08 11:56:01 +00004224 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004225 }
4226 }
4227
Narayan Kamath81822022017-12-08 11:56:01 +00004228 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4229 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004230 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004231 if (type == WAKE_TYPE_PARTIAL) {
4232 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004233 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004234 if (historyName == null) {
4235 historyName = name;
4236 }
4237 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4238 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004239 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004240 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004241 }
4242 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004243 if (mWakeLockNesting == 0) {
4244 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4245 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4246 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004247 mInitialAcquireWakeName = null;
4248 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004249 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004250 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004251 }
4252 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004253 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4254 if (DEBUG_ENERGY_CPU) {
4255 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4256 }
4257 requestWakelockCpuUpdate();
4258 }
Narayan Kamath81822022017-12-08 11:56:01 +00004259
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004260 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004261 if (wc != null) {
4262 StatsLog.write(
4263 StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(), type, name, 0);
Narayan Kamath81822022017-12-08 11:56:01 +00004264 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004265 }
4266 }
4267
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004268 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4269 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004270 final long elapsedRealtime = mClocks.elapsedRealtime();
4271 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004272 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004273 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004274 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4275 unimportantForLogging, elapsedRealtime, uptime);
4276 }
4277
4278 List<WorkChain> wcs = ws.getWorkChains();
4279 if (wcs != null) {
4280 for (int i = 0; i < wcs.size(); ++i) {
4281 final WorkChain wc = wcs.get(i);
4282 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4283 unimportantForLogging, elapsedRealtime, uptime);
4284 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004285 }
4286 }
4287
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004288 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4289 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004290 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004291 final long elapsedRealtime = mClocks.elapsedRealtime();
4292 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004293
4294 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4295
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004296 // For correct semantics, we start the need worksources first, so that we won't
4297 // make inappropriate history items as if all wake locks went away and new ones
4298 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004299 //
4300 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004301 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004302 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004303 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004304 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004305 }
Narayan Kamath81822022017-12-08 11:56:01 +00004306 if (wcs != null) {
4307 List<WorkChain> newChains = wcs[0];
4308 if (newChains != null) {
4309 for (int i = 0; i < newChains.size(); ++i) {
4310 final WorkChain newChain = newChains.get(i);
4311 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4312 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4313 uptime);
4314 }
4315 }
4316 }
4317
4318 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004319 final int NO = ws.size();
4320 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004321 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4322 uptime);
4323 }
4324 if (wcs != null) {
4325 List<WorkChain> goneChains = wcs[1];
4326 if (goneChains != null) {
4327 for (int i = 0; i < goneChains.size(); ++i) {
4328 final WorkChain goneChain = goneChains.get(i);
4329 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4330 historyName, type, elapsedRealtime, uptime);
4331 }
4332 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004333 }
4334 }
4335
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004336 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4337 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004338 final long elapsedRealtime = mClocks.elapsedRealtime();
4339 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004340 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004341 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004342 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4343 uptime);
4344 }
4345
4346 List<WorkChain> wcs = ws.getWorkChains();
4347 if (wcs != null) {
4348 for (int i = 0; i < wcs.size(); ++i) {
4349 final WorkChain wc = wcs.get(i);
4350 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4351 elapsedRealtime, uptime);
4352 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004353 }
4354 }
4355
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004356 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
4357 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004358 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4359 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, name, historyName, 1);
4360 }
4361
4362 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4363 WorkSource workSource) {
4364 final int N = workSource.size();
4365 for (int i = 0; i < N; ++i) {
4366 final int uid = mapUid(workSource.get(i));
4367 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4368 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, name, historyName, 1);
4369 }
4370
4371 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4372 if (workChains != null) {
4373 for (int i = 0; i < workChains.size(); ++i) {
4374 final WorkChain workChain = workChains.get(i);
4375 final int uid = workChain.getAttributionUid();
4376 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4377
4378 // TODO(statsd): the Log WorkChain to statds, and not just the uid.
4379 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, name, historyName,
4380 1);
4381 }
4382 }
4383 }
4384
4385 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004386 final long elapsedRealtime = mClocks.elapsedRealtime();
4387 final long uptime = mClocks.uptimeMillis();
4388 if (historyName == null) {
4389 historyName = name;
4390 }
4391 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4392 0)) {
4393 return;
4394 }
4395 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4396 historyName, uid);
4397 }
4398
4399 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
4400 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004401 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
4402 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, name, historyName, 0);
4403 }
4404
4405 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4406 WorkSource workSource) {
4407 final int N = workSource.size();
4408 for (int i = 0; i < N; ++i) {
4409 final int uid = mapUid(workSource.get(i));
4410 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
4411 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, name, historyName, 0);
4412 }
4413
4414 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4415 if (workChains != null) {
4416 for (int i = 0; i < workChains.size(); ++i) {
4417 final WorkChain workChain = workChains.get(i);
4418 final int uid = workChain.getAttributionUid();
4419
4420 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
4421
4422 // TODO(statsd): the Log WorkChain to statds, and not just the uid.
4423 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, name, historyName,
4424 0);
4425 }
4426 }
4427 }
4428
4429 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004430 final long elapsedRealtime = mClocks.elapsedRealtime();
4431 final long uptime = mClocks.uptimeMillis();
4432 if (historyName == null) {
4433 historyName = name;
4434 }
4435 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4436 0)) {
4437 return;
4438 }
4439 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4440 historyName, uid);
4441 }
4442
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004443 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4444 if (mLastWakeupReason != null) {
4445 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004446 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004447 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz8c6571b2017-10-24 15:04:41 -07004448 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason, deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004449 mLastWakeupReason = null;
4450 }
4451 }
4452
4453 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004454 final long elapsedRealtime = mClocks.elapsedRealtime();
4455 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004456 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004457 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004458 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004459 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4460 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004461 mHistoryCur.wakeReasonTag.uid = 0;
4462 mLastWakeupReason = reason;
4463 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004464 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004465 }
4466
Adam Lesinski72478f02015-06-17 15:39:43 -07004467 public boolean startAddingCpuLocked() {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004468 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
Adam Lesinski72478f02015-06-17 15:39:43 -07004469 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004470 }
4471
Adam Lesinski72478f02015-06-17 15:39:43 -07004472 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4473 int statSystemTime, int statIOWaitTime, int statIrqTime,
4474 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004475 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4476 + " user=" + statUserTime + " sys=" + statSystemTime
4477 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4478 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4479 mCurStepCpuUserTime += totalUTime;
4480 mCurStepCpuSystemTime += totalSTime;
4481 mCurStepStatUserTime += statUserTime;
4482 mCurStepStatSystemTime += statSystemTime;
4483 mCurStepStatIOWaitTime += statIOWaitTime;
4484 mCurStepStatIrqTime += statIrqTime;
4485 mCurStepStatSoftIrqTime += statSoftIrqTime;
4486 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004487 }
4488
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004489 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004490 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004491 Uid u = mUidStats.get(uid);
4492 if (u != null) {
4493 u.mPids.remove(pid);
4494 }
4495 }
4496
4497 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004498 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004499 Uid u = mUidStats.get(uid);
4500 if (u != null) {
4501 Uid.Pid p = u.mPids.get(pid);
4502 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004503 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004504 }
4505 }
4506 return 0;
4507 }
4508
Dianne Hackborn287952c2010-09-22 22:34:31 -07004509 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004510 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004511 Uid u = mUidStats.get(uid);
4512 if (u != null) {
4513 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4514 }
4515 }
4516
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004517 int mSensorNesting;
4518
4519 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004520 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004521 final long elapsedRealtime = mClocks.elapsedRealtime();
4522 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004523 if (mSensorNesting == 0) {
4524 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4525 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4526 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004527 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004528 }
4529 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004530 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004531 }
4532
4533 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004534 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004535 final long elapsedRealtime = mClocks.elapsedRealtime();
4536 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004537 mSensorNesting--;
4538 if (mSensorNesting == 0) {
4539 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4540 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4541 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004542 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004543 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004544 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004545 }
4546
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004547 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004548
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004549 public void noteStartGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004550 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004551 final long elapsedRealtime = mClocks.elapsedRealtime();
4552 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004553 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004554 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004555 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4556 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004557 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004558 }
4559 mGpsNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004560 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004562
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004563 public void noteStopGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004564 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004565 final long elapsedRealtime = mClocks.elapsedRealtime();
4566 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004567 mGpsNesting--;
4568 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004569 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004570 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4571 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004572 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004573 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004574 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004576
Jeff Browne95c3cd2014-05-02 16:59:26 -07004577 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004578 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004579
4580 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4581 // original 4 are mapped to one of the originals.
4582 if (state > MAX_TRACKED_SCREEN_STATE) {
4583 switch (state) {
4584 case Display.STATE_VR:
4585 state = Display.STATE_ON;
4586 break;
4587 default:
4588 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4589 break;
4590 }
4591 }
4592
Jeff Browne95c3cd2014-05-02 16:59:26 -07004593 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004594 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004595 final int oldState = mScreenState;
4596 mScreenState = state;
4597 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4598 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004599
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004600 if (state != Display.STATE_UNKNOWN) {
4601 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004602 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4603 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4604 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004605 } else {
4606 Slog.wtf(TAG, "Unexpected screen state: " + state);
4607 }
4608 }
4609
Mike Mac2f518a2017-09-19 16:06:03 -07004610 final long elapsedRealtime = mClocks.elapsedRealtime();
4611 final long uptime = mClocks.uptimeMillis();
4612
4613 boolean updateHistory = false;
4614 if (isScreenDoze(state)) {
4615 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4616 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4617 updateHistory = true;
4618 } else if (isScreenDoze(oldState)) {
4619 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4620 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4621 updateHistory = true;
4622 }
4623 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004624 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4625 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4626 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004627 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4628 if (mScreenBrightnessBin >= 0) {
4629 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4630 }
Mike Mac2f518a2017-09-19 16:06:03 -07004631 updateHistory = true;
4632 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004633 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4634 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4635 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004636 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4637 if (mScreenBrightnessBin >= 0) {
4638 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4639 }
Mike Mac2f518a2017-09-19 16:06:03 -07004640 updateHistory = true;
4641 }
4642 if (updateHistory) {
4643 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4644 + Display.stateToString(state));
4645 addHistoryRecordLocked(elapsedRealtime, uptime);
4646 }
4647 if (isScreenOn(state)) {
4648 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4649 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4650 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004651 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004652 elapsedRealtime, uptime);
4653 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004654 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004655 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004656 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004657 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004658 }
4659 // Update discharge amounts.
4660 if (mOnBatteryInternal) {
4661 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004662 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004663 }
4664 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004665
Dianne Hackborn617f8772009-03-31 15:04:46 -07004666 public void noteScreenBrightnessLocked(int brightness) {
4667 // Bin the brightness.
4668 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4669 if (bin < 0) bin = 0;
4670 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4671 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004672 final long elapsedRealtime = mClocks.elapsedRealtime();
4673 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004674 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4675 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004676 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4677 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004678 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004679 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004680 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004681 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004682 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004683 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004684 }
4685 mScreenBrightnessBin = bin;
4686 }
4687 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004688
Dianne Hackborn617f8772009-03-31 15:04:46 -07004689 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004690 if (mOnBatteryInternal) {
4691 uid = mapUid(uid);
4692 getUidStatsLocked(uid).noteUserActivityLocked(event);
4693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004695
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004696 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004697 final long elapsedRealtime = mClocks.elapsedRealtime();
4698 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004699 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4700 reason, reasonUid);
4701 }
4702
Jeff Browne95c3cd2014-05-02 16:59:26 -07004703 public void noteInteractiveLocked(boolean interactive) {
4704 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08004705 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004706 mInteractive = interactive;
4707 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
4708 if (interactive) {
4709 mInteractiveTimer.startRunningLocked(elapsedRealtime);
4710 } else {
4711 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
4712 }
4713 }
4714 }
4715
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004716 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004717 final long elapsedRealtime = mClocks.elapsedRealtime();
4718 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004719 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4720 extra, type);
4721 mNumConnectivityChange++;
4722 }
4723
Adam Lesinski5f056f62016-07-14 16:56:08 -07004724 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4725 final long uptimeMillis, int uid) {
4726 uid = mapUid(uid);
4727 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4728 uid);
4729 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4730 }
4731
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004732 /**
4733 * Updates the radio power state and returns true if an external stats collection should occur.
4734 */
4735 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004736 final long elapsedRealtime = mClocks.elapsedRealtime();
4737 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004738 if (mMobileRadioPowerState != powerState) {
4739 long realElapsedRealtimeMs;
4740 final boolean active =
4741 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4742 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4743 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004744 if (uid > 0) {
4745 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4746 }
4747
Adam Lesinski9acfd812016-04-19 18:29:50 -07004748 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004749 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4750 } else {
4751 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004752 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004753 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4754 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4755 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004756 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004757 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4758 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4759 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004760 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004761 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4762 }
4763 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4764 + Integer.toHexString(mHistoryCur.states));
4765 addHistoryRecordLocked(elapsedRealtime, uptime);
4766 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08004767 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004768 if (active) {
4769 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4770 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4771 } else {
4772 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004773 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004774 // Tell the caller to collect radio network/power stats.
4775 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004776 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004777 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004778 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004779 }
4780
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004781 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004782 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004783 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4784 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4785 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004786 final long elapsedRealtime = mClocks.elapsedRealtime();
4787 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004788 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004789 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004790 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4791 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004792 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004793 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004794 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004795 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4796 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004797 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004798 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004799 }
4800 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatzc1a050a2017-10-10 15:49:28 -07004801 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ? 1 : 0);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004802 }
4803 }
4804
Bookatzddccf0a2017-11-28 16:48:14 -08004805 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004806 final long elapsedRealtime = mClocks.elapsedRealtime();
4807 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004808 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004809 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004810 // We don't go out of general idling mode until explicitly taken out of
4811 // device idle through going active or significant motion.
4812 nowIdling = true;
4813 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004814 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
4815 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
4816 // We don't go out of general light idling mode until explicitly taken out of
4817 // device idle through going active or significant motion.
4818 nowLightIdling = true;
4819 }
4820 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
4821 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
4822 activeReason, activeUid);
4823 }
Bookatzddccf0a2017-11-28 16:48:14 -08004824 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
4825 int statsmode;
4826 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
4827 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
4828 else statsmode = DEVICE_IDLE_MODE_OFF;
4829 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
4830 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004831 if (mDeviceIdling != nowIdling) {
4832 mDeviceIdling = nowIdling;
4833 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
4834 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
4835 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004836 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004837 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
4838 } else {
4839 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
4840 }
4841 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004842 if (mDeviceLightIdling != nowLightIdling) {
4843 mDeviceLightIdling = nowLightIdling;
4844 if (nowLightIdling) {
4845 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004846 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004847 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004848 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004849 }
4850 if (mDeviceIdleMode != mode) {
4851 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
4852 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
4853 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
4854 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004855 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004856 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
4857 mLastIdleTimeStart = elapsedRealtime;
4858 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
4859 if (lastDuration > mLongestLightIdleTime) {
4860 mLongestLightIdleTime = lastDuration;
4861 }
4862 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004863 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004864 if (lastDuration > mLongestFullIdleTime) {
4865 mLongestFullIdleTime = lastDuration;
4866 }
4867 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
4868 }
4869 if (mode == DEVICE_IDLE_MODE_LIGHT) {
4870 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004871 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004872 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
4873 }
4874 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08004875 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004876 }
4877 }
4878
Dianne Hackborn3accca02013-09-20 09:32:11 -07004879 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08004880 final long elapsedRealtime = mClocks.elapsedRealtime();
4881 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07004882 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004883 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07004884 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004885 PackageChange pc = new PackageChange();
4886 pc.mPackageName = pkgName;
4887 pc.mUpdate = true;
4888 pc.mVersionCode = versionCode;
4889 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004890 }
4891
4892 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08004893 final long elapsedRealtime = mClocks.elapsedRealtime();
4894 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004895 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
4896 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004897 PackageChange pc = new PackageChange();
4898 pc.mPackageName = pkgName;
4899 pc.mUpdate = true;
4900 addPackageChange(pc);
4901 }
4902
4903 private void addPackageChange(PackageChange pc) {
4904 if (mDailyPackageChanges == null) {
4905 mDailyPackageChanges = new ArrayList<>();
4906 }
4907 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004908 }
4909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004910 public void notePhoneOnLocked() {
4911 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004912 final long elapsedRealtime = mClocks.elapsedRealtime();
4913 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004914 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004915 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
4916 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004917 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004918 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004919 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004920 }
4921 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004923 public void notePhoneOffLocked() {
4924 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004925 final long elapsedRealtime = mClocks.elapsedRealtime();
4926 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004927 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004928 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
4929 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004930 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004932 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004933 }
4934 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07004935
Dianne Hackborn3251b902014-06-20 14:40:53 -07004936 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08004937 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08004938 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004939 if (i == except) {
4940 continue;
4941 }
4942 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004943 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004944 }
4945 }
4946 }
4947
Dianne Hackborne4a59512010-12-07 11:08:07 -08004948 private int fixPhoneServiceState(int state, int signalBin) {
4949 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
4950 // In this case we will always be STATE_OUT_OF_SERVICE, so need
4951 // to infer that we are scanning from other data.
4952 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08004953 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004954 state = ServiceState.STATE_IN_SERVICE;
4955 }
4956 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004957
Dianne Hackborne4a59512010-12-07 11:08:07 -08004958 return state;
4959 }
4960
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004961 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004962 boolean scanning = false;
4963 boolean newHistory = false;
4964
4965 mPhoneServiceStateRaw = state;
4966 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004967 mPhoneSignalStrengthBinRaw = strengthBin;
4968
Joe Onoratoabded112016-02-08 16:49:39 -08004969 final long elapsedRealtime = mClocks.elapsedRealtime();
4970 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08004971
4972 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
4973 // In this case we will always be STATE_OUT_OF_SERVICE, so need
4974 // to infer that we are scanning from other data.
4975 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004976 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004977 state = ServiceState.STATE_IN_SERVICE;
4978 }
4979 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004980
4981 // If the phone is powered off, stop all timers.
4982 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004983 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07004984
Dianne Hackborne4a59512010-12-07 11:08:07 -08004985 // If we are in service, make sure the correct signal string timer is running.
4986 } else if (state == ServiceState.STATE_IN_SERVICE) {
4987 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004988
4989 // If we're out of service, we are in the lowest signal strength
4990 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07004991 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004992 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004993 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07004994 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004995 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08004996 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004997 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
4998 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004999 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005000 }
5001 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005002
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005003 if (!scanning) {
5004 // If we are no longer scanning, then stop the scanning timer.
5005 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5006 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5007 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5008 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005009 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005010 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005011 }
5012 }
5013
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005014 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005015 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5016 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005017 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005018 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005019 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005020 mPhoneServiceState = state;
5021 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005022
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005023 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005024 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005025 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005026 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005027 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005028 if (strengthBin >= 0) {
5029 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005030 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005031 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005032 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5033 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005034 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005035 + Integer.toHexString(mHistoryCur.states));
5036 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005037 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005038 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005039 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005040 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005041 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005042 }
5043
5044 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005045 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005046 }
5047 }
5048
5049 /**
5050 * Telephony stack updates the phone state.
5051 * @param state phone state from ServiceState.getState()
5052 */
5053 public void notePhoneStateLocked(int state, int simState) {
5054 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005055 }
5056
Wink Savillee9b06d72009-05-18 21:47:50 -07005057 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005058 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005059 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005060 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005061 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005062
Dianne Hackborn627bba72009-03-24 22:32:56 -07005063 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
5064 int bin = DATA_CONNECTION_NONE;
5065 if (hasData) {
5066 switch (dataType) {
5067 case TelephonyManager.NETWORK_TYPE_EDGE:
5068 bin = DATA_CONNECTION_EDGE;
5069 break;
5070 case TelephonyManager.NETWORK_TYPE_GPRS:
5071 bin = DATA_CONNECTION_GPRS;
5072 break;
5073 case TelephonyManager.NETWORK_TYPE_UMTS:
5074 bin = DATA_CONNECTION_UMTS;
5075 break;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005076 case TelephonyManager.NETWORK_TYPE_CDMA:
5077 bin = DATA_CONNECTION_CDMA;
5078 break;
5079 case TelephonyManager.NETWORK_TYPE_EVDO_0:
5080 bin = DATA_CONNECTION_EVDO_0;
5081 break;
5082 case TelephonyManager.NETWORK_TYPE_EVDO_A:
5083 bin = DATA_CONNECTION_EVDO_A;
5084 break;
5085 case TelephonyManager.NETWORK_TYPE_1xRTT:
5086 bin = DATA_CONNECTION_1xRTT;
5087 break;
5088 case TelephonyManager.NETWORK_TYPE_HSDPA:
5089 bin = DATA_CONNECTION_HSDPA;
5090 break;
5091 case TelephonyManager.NETWORK_TYPE_HSUPA:
5092 bin = DATA_CONNECTION_HSUPA;
5093 break;
5094 case TelephonyManager.NETWORK_TYPE_HSPA:
5095 bin = DATA_CONNECTION_HSPA;
5096 break;
5097 case TelephonyManager.NETWORK_TYPE_IDEN:
5098 bin = DATA_CONNECTION_IDEN;
5099 break;
5100 case TelephonyManager.NETWORK_TYPE_EVDO_B:
5101 bin = DATA_CONNECTION_EVDO_B;
5102 break;
Robert Greenwalt962a9902010-11-02 11:10:25 -07005103 case TelephonyManager.NETWORK_TYPE_LTE:
5104 bin = DATA_CONNECTION_LTE;
5105 break;
5106 case TelephonyManager.NETWORK_TYPE_EHRPD:
5107 bin = DATA_CONNECTION_EHRPD;
5108 break;
Patrick Tjinb71703c2013-11-06 09:27:03 -08005109 case TelephonyManager.NETWORK_TYPE_HSPAP:
5110 bin = DATA_CONNECTION_HSPAP;
5111 break;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005112 default:
5113 bin = DATA_CONNECTION_OTHER;
5114 break;
5115 }
5116 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005117 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005118 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005119 final long elapsedRealtime = mClocks.elapsedRealtime();
5120 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005121 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5122 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005123 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5124 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005125 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005126 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005127 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005128 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005129 }
5130 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005131 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005132 }
5133 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005134
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005135 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005136 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005137 final long elapsedRealtime = mClocks.elapsedRealtime();
5138 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005139 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005140 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5141 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005142 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005143 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005144 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005145 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005146 }
5147 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005148
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005149 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005150 final long elapsedRealtime = mClocks.elapsedRealtime();
5151 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005152 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005153 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005154 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5155 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005156 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005157 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005158 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005159 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005160 }
5161 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005162
5163 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005164 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005165 final long elapsedRealtime = mClocks.elapsedRealtime();
5166 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005167 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005168 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005169 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5170 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005171 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005172 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005173 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005174 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005175 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005176 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005177
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005178 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005179 if (mAudioOnNesting == 0) {
5180 return;
5181 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005182 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005183 final long elapsedRealtime = mClocks.elapsedRealtime();
5184 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005185 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005186 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005187 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5188 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005189 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005190 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005191 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005192 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005193 }
5194
5195 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005196 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005197 final long elapsedRealtime = mClocks.elapsedRealtime();
5198 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005199 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005200 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005201 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5202 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005203 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005204 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005205 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005206 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005207 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005208 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005209
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005210 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005211 if (mVideoOnNesting == 0) {
5212 return;
5213 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005214 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005215 final long elapsedRealtime = mClocks.elapsedRealtime();
5216 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005217 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005218 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005219 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5220 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005221 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005222 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005223 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005224 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005225 }
5226
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005227 public void noteResetAudioLocked() {
5228 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005229 final long elapsedRealtime = mClocks.elapsedRealtime();
5230 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005231 mAudioOnNesting = 0;
5232 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5233 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5234 + Integer.toHexString(mHistoryCur.states));
5235 addHistoryRecordLocked(elapsedRealtime, uptime);
5236 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5237 for (int i=0; i<mUidStats.size(); i++) {
5238 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5239 uid.noteResetAudioLocked(elapsedRealtime);
5240 }
5241 }
5242 }
5243
5244 public void noteResetVideoLocked() {
5245 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005246 final long elapsedRealtime = mClocks.elapsedRealtime();
5247 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005248 mAudioOnNesting = 0;
5249 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5250 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5251 + Integer.toHexString(mHistoryCur.states));
5252 addHistoryRecordLocked(elapsedRealtime, uptime);
5253 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5254 for (int i=0; i<mUidStats.size(); i++) {
5255 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5256 uid.noteResetVideoLocked(elapsedRealtime);
5257 }
5258 }
5259 }
5260
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005261 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005262 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005263 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005264 }
5265
5266 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005267 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005268 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005269 }
5270
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005271 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005272 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005273 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5274 }
5275
5276 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005277 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005278 getUidStatsLocked(uid).noteVibratorOffLocked();
5279 }
5280
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005281 public void noteFlashlightOnLocked(int uid) {
5282 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005283 final long elapsedRealtime = mClocks.elapsedRealtime();
5284 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005285 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005286 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5287 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005288 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005289 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005290 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5291 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005292 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5293 }
5294
5295 public void noteFlashlightOffLocked(int uid) {
5296 if (mFlashlightOnNesting == 0) {
5297 return;
5298 }
5299 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005300 final long elapsedRealtime = mClocks.elapsedRealtime();
5301 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005302 if (--mFlashlightOnNesting == 0) {
5303 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5304 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5305 + Integer.toHexString(mHistoryCur.states2));
5306 addHistoryRecordLocked(elapsedRealtime, uptime);
5307 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5308 }
5309 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5310 }
5311
5312 public void noteCameraOnLocked(int uid) {
5313 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005314 final long elapsedRealtime = mClocks.elapsedRealtime();
5315 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005316 if (mCameraOnNesting++ == 0) {
5317 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5318 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5319 + Integer.toHexString(mHistoryCur.states2));
5320 addHistoryRecordLocked(elapsedRealtime, uptime);
5321 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5322 }
5323 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5324 }
5325
5326 public void noteCameraOffLocked(int uid) {
5327 if (mCameraOnNesting == 0) {
5328 return;
5329 }
5330 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005331 final long elapsedRealtime = mClocks.elapsedRealtime();
5332 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005333 if (--mCameraOnNesting == 0) {
5334 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5335 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5336 + Integer.toHexString(mHistoryCur.states2));
5337 addHistoryRecordLocked(elapsedRealtime, uptime);
5338 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5339 }
5340 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5341 }
5342
5343 public void noteResetCameraLocked() {
5344 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005345 final long elapsedRealtime = mClocks.elapsedRealtime();
5346 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005347 mCameraOnNesting = 0;
5348 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5349 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5350 + Integer.toHexString(mHistoryCur.states2));
5351 addHistoryRecordLocked(elapsedRealtime, uptime);
5352 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5353 for (int i=0; i<mUidStats.size(); i++) {
5354 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5355 uid.noteResetCameraLocked(elapsedRealtime);
5356 }
5357 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005358 }
5359
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005360 public void noteResetFlashlightLocked() {
5361 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005362 final long elapsedRealtime = mClocks.elapsedRealtime();
5363 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005364 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005365 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5366 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005367 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005368 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005369 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5370 for (int i=0; i<mUidStats.size(); i++) {
5371 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5372 uid.noteResetFlashlightLocked(elapsedRealtime);
5373 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005374 }
5375 }
5376
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005377 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5378 boolean isUnoptimized) {
5379 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005380 final long elapsedRealtime = mClocks.elapsedRealtime();
5381 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005382 if (mBluetoothScanNesting == 0) {
5383 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5384 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5385 + Integer.toHexString(mHistoryCur.states2));
5386 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005387 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005388 }
5389 mBluetoothScanNesting++;
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005390
5391 // TODO(statsd): Log WorkChain here if it's non-null.
5392 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED, uid, 1);
5393 if (isUnoptimized) {
5394 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, 1);
5395 }
5396
Bookatzb1f04f32017-05-19 13:57:32 -07005397 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005398 if (workChain != null) {
5399 getUidStatsLocked(uid).addBluetoothWorkChain(workChain, isUnoptimized);
5400 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005401 }
5402
Bookatzb1f04f32017-05-19 13:57:32 -07005403 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005404 final int N = ws.size();
5405 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005406 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5407 }
5408
5409 final List<WorkChain> workChains = ws.getWorkChains();
5410 if (workChains != null) {
5411 for (int i = 0; i < workChains.size(); ++i) {
5412 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5413 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005414 }
5415 }
5416
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005417 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5418 boolean isUnoptimized) {
5419 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005420 final long elapsedRealtime = mClocks.elapsedRealtime();
5421 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005422 mBluetoothScanNesting--;
5423 if (mBluetoothScanNesting == 0) {
5424 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5425 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5426 + Integer.toHexString(mHistoryCur.states2));
5427 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005428 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005429 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005430
5431 // TODO(statsd): Log WorkChain here if it's non-null.
5432 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED, uid, 0);
5433 if (isUnoptimized) {
5434 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, 0);
5435 }
5436
Bookatz94c5a312017-07-11 16:49:17 -07005437 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005438 if (workChain != null) {
5439 getUidStatsLocked(uid).removeBluetoothWorkChain(workChain, isUnoptimized);
5440 }
5441 }
5442
5443 private int getAttributionUid(int uid, WorkChain workChain) {
5444 if (workChain != null) {
5445 return mapUid(workChain.getAttributionUid());
5446 }
5447
5448 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005449 }
5450
Bookatz94c5a312017-07-11 16:49:17 -07005451 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005452 final int N = ws.size();
5453 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005454 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5455 }
5456
5457 final List<WorkChain> workChains = ws.getWorkChains();
5458 if (workChains != null) {
5459 for (int i = 0; i < workChains.size(); ++i) {
5460 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5461 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005462 }
5463 }
5464
5465 public void noteResetBluetoothScanLocked() {
5466 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005467 final long elapsedRealtime = mClocks.elapsedRealtime();
5468 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005469 mBluetoothScanNesting = 0;
5470 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5471 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5472 + Integer.toHexString(mHistoryCur.states2));
5473 addHistoryRecordLocked(elapsedRealtime, uptime);
5474 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005475
5476
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005477 for (int i=0; i<mUidStats.size(); i++) {
5478 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5479 uid.noteResetBluetoothScanLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005480
5481 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED, uid.getUid(), 0);
5482
5483 List<WorkChain> allWorkChains = uid.getAllBluetoothWorkChains();
5484 if (allWorkChains != null) {
5485 for (int j = 0; j < allWorkChains.size(); ++j) {
5486 // TODO(statsd) : Log the entire workchain here.
5487 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
5488 allWorkChains.get(j).getAttributionUid(), 0);
5489 }
5490
5491 allWorkChains.clear();
5492 }
5493
5494 List<WorkChain> unoptimizedWorkChains = uid.getUnoptimizedBluetoothWorkChains();
5495 if (unoptimizedWorkChains != null) {
5496 for (int j = 0; j < unoptimizedWorkChains.size(); ++j) {
5497 // TODO(statsd) : Log the entire workchain here.
5498 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
5499 unoptimizedWorkChains.get(j).getAttributionUid(), 0);
5500 }
5501
5502 unoptimizedWorkChains.clear();
5503 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005504 }
5505 }
5506 }
5507
Bookatz4ebc0642017-05-11 12:21:19 -07005508 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005509 final int N = ws.size();
5510 for (int i = 0; i < N; i++) {
5511 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005512 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005513 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED, uid, numNewResults);
5514 }
5515
5516 final List<WorkChain> workChains = ws.getWorkChains();
5517 if (workChains != null) {
5518 for (int i = 0; i < workChains.size(); ++i) {
5519 final WorkChain wc = workChains.get(i);
5520 int uid = mapUid(wc.getAttributionUid());
5521 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
5522 // TODO(statsd): Log the entire WorkChain here.
5523 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED, uid, numNewResults);
5524 }
Bookatz956f36bf2017-04-28 09:48:17 -07005525 }
5526 }
5527
Adam Lesinski5f056f62016-07-14 16:56:08 -07005528 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5529 final long uptimeMillis, int uid) {
5530 uid = mapUid(uid);
5531 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5532 uid);
5533 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5534 }
5535
5536 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005537 final long elapsedRealtime = mClocks.elapsedRealtime();
5538 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005539 if (mWifiRadioPowerState != powerState) {
5540 final boolean active =
5541 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5542 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5543 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005544 if (uid > 0) {
5545 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5546 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005547 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
5548 } else {
5549 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
5550 }
5551 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5552 + Integer.toHexString(mHistoryCur.states));
5553 addHistoryRecordLocked(elapsedRealtime, uptime);
5554 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005555 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005556 }
5557 }
5558
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005559 public void noteWifiRunningLocked(WorkSource ws) {
5560 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005561 final long elapsedRealtime = mClocks.elapsedRealtime();
5562 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005563 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005564 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5565 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005566 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005567 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005568 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005569 int N = ws.size();
5570 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005571 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005572 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005573 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005574
5575 List<WorkChain> workChains = ws.getWorkChains();
5576 if (workChains != null) {
5577 for (int i = 0; i < workChains.size(); ++i) {
5578 int uid = mapUid(workChains.get(i).getAttributionUid());
5579 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5580 }
5581 }
5582
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005583 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005584 } else {
5585 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005586 }
5587 }
5588
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005589 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5590 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005591 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005592 int N = oldWs.size();
5593 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005594 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005595 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005596 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005597
5598 List<WorkChain> workChains = oldWs.getWorkChains();
5599 if (workChains != null) {
5600 for (int i = 0; i < workChains.size(); ++i) {
5601 int uid = mapUid(workChains.get(i).getAttributionUid());
5602 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5603 }
5604 }
5605
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005606 N = newWs.size();
5607 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005608 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005609 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005610 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005611
5612 workChains = newWs.getWorkChains();
5613 if (workChains != null) {
5614 for (int i = 0; i < workChains.size(); ++i) {
5615 int uid = mapUid(workChains.get(i).getAttributionUid());
5616 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5617 }
5618 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005619 } else {
5620 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5621 }
5622 }
5623
5624 public void noteWifiStoppedLocked(WorkSource ws) {
5625 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005626 final long elapsedRealtime = mClocks.elapsedRealtime();
5627 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005628 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005629 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5630 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005631 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005632 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005633 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005634 int N = ws.size();
5635 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005636 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005637 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005638 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005639
5640 List<WorkChain> workChains = ws.getWorkChains();
5641 if (workChains != null) {
5642 for (int i = 0; i < workChains.size(); ++i) {
5643 int uid = mapUid(workChains.get(i).getAttributionUid());
5644 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5645 }
5646 }
5647
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005648 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005649 } else {
5650 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005651 }
5652 }
5653
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005654 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5655 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5656 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005657 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005658 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005659 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005660 }
5661 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005662 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005663 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005664 }
5665 }
5666
Dianne Hackborn3251b902014-06-20 14:40:53 -07005667 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5668 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5669 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005670 final long elapsedRealtime = mClocks.elapsedRealtime();
5671 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005672 if (mWifiSupplState >= 0) {
5673 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5674 }
5675 mWifiSupplState = supplState;
5676 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5677 mHistoryCur.states2 =
5678 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5679 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5680 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5681 + Integer.toHexString(mHistoryCur.states2));
5682 addHistoryRecordLocked(elapsedRealtime, uptime);
5683 }
5684 }
5685
5686 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005687 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005688 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5689 if (i == except) {
5690 continue;
5691 }
5692 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5693 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5694 }
5695 }
5696 }
5697
5698 public void noteWifiRssiChangedLocked(int newRssi) {
5699 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5700 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5701 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005702 final long elapsedRealtime = mClocks.elapsedRealtime();
5703 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005704 if (mWifiSignalStrengthBin >= 0) {
5705 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5706 elapsedRealtime);
5707 }
5708 if (strengthBin >= 0) {
5709 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5710 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Bookatze5885242017-10-24 20:10:31 -07005711 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07005712 }
5713 mHistoryCur.states2 =
5714 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5715 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5716 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5717 + Integer.toHexString(mHistoryCur.states2));
5718 addHistoryRecordLocked(elapsedRealtime, uptime);
5719 } else {
5720 stopAllWifiSignalStrengthTimersLocked(-1);
5721 }
5722 mWifiSignalStrengthBin = strengthBin;
5723 }
5724 }
5725
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005726 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005727
The Android Open Source Project10592532009-03-18 17:39:46 -07005728 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005729 final long elapsedRealtime = mClocks.elapsedRealtime();
5730 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005731 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005732 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005733 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5734 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005735 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005736 }
5737 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005738 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005739 }
5740
5741 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005742 final long elapsedRealtime = mClocks.elapsedRealtime();
5743 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005744 mWifiFullLockNesting--;
5745 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005746 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005747 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
5748 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005749 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005750 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005751 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005752 }
5753
Nick Pelly6ccaa542012-06-15 15:22:47 -07005754 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005755
Nick Pelly6ccaa542012-06-15 15:22:47 -07005756 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005757 final long elapsedRealtime = mClocks.elapsedRealtime();
5758 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005759 if (mWifiScanNesting == 0) {
5760 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
5761 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005762 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005763 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005764 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07005765 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005766 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005767 }
5768
Nick Pelly6ccaa542012-06-15 15:22:47 -07005769 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005770 final long elapsedRealtime = mClocks.elapsedRealtime();
5771 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005772 mWifiScanNesting--;
5773 if (mWifiScanNesting == 0) {
5774 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
5775 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005776 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005777 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005778 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005779 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005780 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005781
Robert Greenwalta029ea12013-09-25 16:38:12 -07005782 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005783 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005784 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005785 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005786 }
5787
5788 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005789 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005790 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005791 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005792 }
5793
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005794 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005795
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005796 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005797 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005798 final long elapsedRealtime = mClocks.elapsedRealtime();
5799 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005800 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005801 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005802 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
5803 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005804 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08005805
5806 // Start Wifi Multicast overall timer
5807 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
5808 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
5809 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
5810 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005811 }
5812 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005813 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005814 }
5815
5816 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005817 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005818 final long elapsedRealtime = mClocks.elapsedRealtime();
5819 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005820 mWifiMulticastNesting--;
5821 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005822 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005823 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
5824 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005825 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08005826
5827 // Stop Wifi Multicast overall timer
5828 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
5829 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
5830 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
5831 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005832 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005833 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005834 }
5835
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005836 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
5837 int N = ws.size();
5838 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005839 final int uid = mapUid(ws.get(i));
5840 noteFullWifiLockAcquiredLocked(uid);
5841 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED, uid, 1);
5842 }
5843
5844 final List<WorkChain> workChains = ws.getWorkChains();
5845 if (workChains != null) {
5846 for (int i = 0; i < workChains.size(); ++i) {
5847 final WorkChain workChain = workChains.get(i);
5848 final int uid = mapUid(workChain.getAttributionUid());
5849 noteFullWifiLockAcquiredLocked(uid);
5850
5851 // TODO(statsd): Log workChain instead of uid here.
5852 if (DEBUG) {
5853 Slog.v(TAG, "noteFullWifiLockAcquiredFromSourceLocked: " + workChain);
5854 }
5855 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED, uid, 1);
5856 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005857 }
5858 }
5859
5860 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
5861 int N = ws.size();
5862 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005863 final int uid = mapUid(ws.get(i));
5864 noteFullWifiLockReleasedLocked(uid);
5865 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED, uid, 0);
5866 }
5867
5868 final List<WorkChain> workChains = ws.getWorkChains();
5869 if (workChains != null) {
5870 for (int i = 0; i < workChains.size(); ++i) {
5871 final WorkChain workChain = workChains.get(i);
5872 final int uid = mapUid(workChain.getAttributionUid());
5873 noteFullWifiLockReleasedLocked(uid);
5874
5875 // TODO(statsd): Log workChain instead of uid here.
5876 if (DEBUG) {
5877 Slog.v(TAG, "noteFullWifiLockReleasedFromSourceLocked: " + workChain);
5878 }
5879 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED, uid, 0);
5880 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005881 }
5882 }
5883
Nick Pelly6ccaa542012-06-15 15:22:47 -07005884 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005885 int N = ws.size();
5886 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005887 final int uid = mapUid(ws.get(i));
5888 noteWifiScanStartedLocked(uid);
5889 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, uid, 1);
5890 }
5891
5892 final List<WorkChain> workChains = ws.getWorkChains();
5893 if (workChains != null) {
5894 for (int i = 0; i < workChains.size(); ++i) {
5895 final WorkChain workChain = workChains.get(i);
5896 final int uid = mapUid(workChain.getAttributionUid());
5897 noteWifiScanStartedLocked(uid);
5898
5899 // TODO(statsd): Log workChain instead of uid here.
5900 if (DEBUG) {
5901 Slog.v(TAG, "noteWifiScanStartedFromSourceLocked: " + workChain);
5902 }
5903 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, uid, 1);
5904 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005905 }
5906 }
5907
Nick Pelly6ccaa542012-06-15 15:22:47 -07005908 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005909 int N = ws.size();
5910 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005911 final int uid = mapUid(ws.get(i));
5912 noteWifiScanStoppedLocked(uid);
5913 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, uid, 0);
5914 }
5915
5916 final List<WorkChain> workChains = ws.getWorkChains();
5917 if (workChains != null) {
5918 for (int i = 0; i < workChains.size(); ++i) {
5919 final WorkChain workChain = workChains.get(i);
5920 final int uid = mapUid(workChain.getAttributionUid());
5921 noteWifiScanStoppedLocked(uid);
5922
5923 if (DEBUG) {
5924 Slog.v(TAG, "noteWifiScanStoppedFromSourceLocked: " + workChain);
5925 }
5926 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, uid, 0);
5927 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005928 }
5929 }
5930
Robert Greenwalta029ea12013-09-25 16:38:12 -07005931 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
5932 int N = ws.size();
5933 for (int i=0; i<N; i++) {
5934 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
5935 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005936
5937 final List<WorkChain> workChains = ws.getWorkChains();
5938 if (workChains != null) {
5939 for (int i = 0; i < workChains.size(); ++i) {
5940 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
5941 }
5942 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07005943 }
5944
5945 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
5946 int N = ws.size();
5947 for (int i=0; i<N; i++) {
5948 noteWifiBatchedScanStoppedLocked(ws.get(i));
5949 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005950
5951 final List<WorkChain> workChains = ws.getWorkChains();
5952 if (workChains != null) {
5953 for (int i = 0; i < workChains.size(); ++i) {
5954 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
5955 }
5956 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07005957 }
5958
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005959 public void noteWifiMulticastEnabledFromSourceLocked(WorkSource ws) {
5960 int N = ws.size();
5961 for (int i=0; i<N; i++) {
5962 noteWifiMulticastEnabledLocked(ws.get(i));
5963 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005964
5965 final List<WorkChain> workChains = ws.getWorkChains();
5966 if (workChains != null) {
5967 for (int i = 0; i < workChains.size(); ++i) {
5968 noteWifiMulticastEnabledLocked(workChains.get(i).getAttributionUid());
5969 }
5970 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005971 }
5972
5973 public void noteWifiMulticastDisabledFromSourceLocked(WorkSource ws) {
5974 int N = ws.size();
5975 for (int i=0; i<N; i++) {
5976 noteWifiMulticastDisabledLocked(ws.get(i));
5977 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005978
5979 final List<WorkChain> workChains = ws.getWorkChains();
5980 if (workChains != null) {
5981 for (int i = 0; i < workChains.size(); ++i) {
5982 noteWifiMulticastDisabledLocked(workChains.get(i).getAttributionUid());
5983 }
5984 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005985 }
5986
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08005987 private static String[] includeInStringArray(String[] array, String str) {
5988 if (ArrayUtils.indexOf(array, str) >= 0) {
5989 return array;
5990 }
5991 String[] newArray = new String[array.length+1];
5992 System.arraycopy(array, 0, newArray, 0, array.length);
5993 newArray[array.length] = str;
5994 return newArray;
5995 }
5996
5997 private static String[] excludeFromStringArray(String[] array, String str) {
5998 int index = ArrayUtils.indexOf(array, str);
5999 if (index >= 0) {
6000 String[] newArray = new String[array.length-1];
6001 if (index > 0) {
6002 System.arraycopy(array, 0, newArray, 0, index);
6003 }
6004 if (index < array.length-1) {
6005 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6006 }
6007 return newArray;
6008 }
6009 return array;
6010 }
6011
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006012 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006013 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006014
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006015 synchronized (mModemNetworkLock) {
6016 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6017 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6018 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6019 } else {
6020 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6021 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6022 }
6023 }
6024
6025 synchronized (mWifiNetworkLock) {
6026 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6027 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6028 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6029 } else {
6030 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6031 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6032 }
6033 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006034 }
6035
David Chenc8a43242017-10-17 16:23:28 -07006036 public String[] getWifiIfaces() {
6037 synchronized (mWifiNetworkLock) {
6038 return mWifiIfaces;
6039 }
6040 }
6041
6042 public String[] getMobileIfaces() {
6043 synchronized (mModemNetworkLock) {
6044 return mModemIfaces;
6045 }
6046 }
6047
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006048 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6049 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006051
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006052 @Override public int getScreenOnCount(int which) {
6053 return mScreenOnTimer.getCountLocked(which);
6054 }
6055
Mike Mac2f518a2017-09-19 16:06:03 -07006056 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6057 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6058 }
6059
6060 @Override public int getScreenDozeCount(int which) {
6061 return mScreenDozeTimer.getCountLocked(which);
6062 }
6063
Dianne Hackborn617f8772009-03-31 15:04:46 -07006064 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006065 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006066 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006067 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006068 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006069
Kweku Adams87b19ec2017-10-09 12:40:03 -07006070 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6071 return mScreenBrightnessTimer[brightnessBin];
6072 }
6073
Jeff Browne95c3cd2014-05-02 16:59:26 -07006074 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6075 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006076 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006077
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006078 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6079 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006080 }
6081
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006082 @Override public int getPowerSaveModeEnabledCount(int which) {
6083 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6084 }
6085
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006086 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6087 int which) {
6088 switch (mode) {
6089 case DEVICE_IDLE_MODE_LIGHT:
6090 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006091 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006092 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6093 }
6094 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006095 }
6096
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006097 @Override public int getDeviceIdleModeCount(int mode, int which) {
6098 switch (mode) {
6099 case DEVICE_IDLE_MODE_LIGHT:
6100 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006101 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006102 return mDeviceIdleModeFullTimer.getCountLocked(which);
6103 }
6104 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006105 }
6106
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006107 @Override public long getLongestDeviceIdleModeTime(int mode) {
6108 switch (mode) {
6109 case DEVICE_IDLE_MODE_LIGHT:
6110 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006111 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006112 return mLongestFullIdleTime;
6113 }
6114 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006115 }
6116
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006117 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6118 switch (mode) {
6119 case DEVICE_IDLE_MODE_LIGHT:
6120 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006121 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006122 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6123 }
6124 return 0;
6125 }
6126
6127 @Override public int getDeviceIdlingCount(int mode, int which) {
6128 switch (mode) {
6129 case DEVICE_IDLE_MODE_LIGHT:
6130 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006131 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006132 return mDeviceIdlingTimer.getCountLocked(which);
6133 }
6134 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006135 }
6136
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006137 @Override public int getNumConnectivityChange(int which) {
6138 int val = mNumConnectivityChange;
6139 if (which == STATS_CURRENT) {
6140 val -= mLoadedNumConnectivityChange;
6141 } else if (which == STATS_SINCE_UNPLUGGED) {
6142 val -= mUnpluggedNumConnectivityChange;
6143 }
6144 return val;
6145 }
6146
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006147 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6148 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006150
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006151 @Override public int getPhoneOnCount(int which) {
6152 return mPhoneOnTimer.getCountLocked(which);
6153 }
6154
Dianne Hackborn627bba72009-03-24 22:32:56 -07006155 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006156 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006157 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006158 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006159 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006160
6161 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006162 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006163 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006164 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006165 }
6166
Kweku Adams87b19ec2017-10-09 12:40:03 -07006167 @Override public Timer getPhoneSignalScanningTimer() {
6168 return mPhoneSignalScanningTimer;
6169 }
6170
Catherine Liufb900812012-07-17 14:12:56 -05006171 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6172 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006173 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006174
Kweku Adams87b19ec2017-10-09 12:40:03 -07006175 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6176 return mPhoneSignalStrengthsTimer[strengthBin];
6177 }
6178
Dianne Hackborn627bba72009-03-24 22:32:56 -07006179 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006180 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006181 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006182 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006183 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006184
Dianne Hackborn617f8772009-03-31 15:04:46 -07006185 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006186 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006187 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006188
Kweku Adams87b19ec2017-10-09 12:40:03 -07006189 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6190 return mPhoneDataConnectionsTimer[dataType];
6191 }
6192
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006193 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6194 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006195 }
6196
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006197 @Override public int getMobileRadioActiveCount(int which) {
6198 return mMobileRadioActiveTimer.getCountLocked(which);
6199 }
6200
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006201 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6202 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6203 }
6204
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006205 @Override public long getMobileRadioActiveUnknownTime(int which) {
6206 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6207 }
6208
6209 @Override public int getMobileRadioActiveUnknownCount(int which) {
6210 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6211 }
6212
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006213 @Override public long getWifiMulticastWakelockTime(
6214 long elapsedRealtimeUs, int which) {
6215 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6216 elapsedRealtimeUs, which);
6217 }
6218
6219 @Override public int getWifiMulticastWakelockCount(int which) {
6220 return mWifiMulticastWakelockTimer.getCountLocked(which);
6221 }
6222
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006223 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6224 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006225 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006226
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006227 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6228 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006229 }
6230
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006231 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006232 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006233 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006234 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006235 }
6236
6237 @Override public int getWifiStateCount(int wifiState, int which) {
6238 return mWifiStateTimer[wifiState].getCountLocked(which);
6239 }
6240
Kweku Adams87b19ec2017-10-09 12:40:03 -07006241 @Override public Timer getWifiStateTimer(int wifiState) {
6242 return mWifiStateTimer[wifiState];
6243 }
6244
Dianne Hackborn3251b902014-06-20 14:40:53 -07006245 @Override public long getWifiSupplStateTime(int state,
6246 long elapsedRealtimeUs, int which) {
6247 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6248 elapsedRealtimeUs, which);
6249 }
6250
6251 @Override public int getWifiSupplStateCount(int state, int which) {
6252 return mWifiSupplStateTimer[state].getCountLocked(which);
6253 }
6254
Kweku Adams87b19ec2017-10-09 12:40:03 -07006255 @Override public Timer getWifiSupplStateTimer(int state) {
6256 return mWifiSupplStateTimer[state];
6257 }
6258
Dianne Hackborn3251b902014-06-20 14:40:53 -07006259 @Override public long getWifiSignalStrengthTime(int strengthBin,
6260 long elapsedRealtimeUs, int which) {
6261 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6262 elapsedRealtimeUs, which);
6263 }
6264
6265 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6266 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6267 }
6268
Kweku Adams87b19ec2017-10-09 12:40:03 -07006269 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6270 return mWifiSignalStrengthsTimer[strengthBin];
6271 }
6272
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006273 @Override
6274 public ControllerActivityCounter getBluetoothControllerActivity() {
6275 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006276 }
6277
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006278 @Override
6279 public ControllerActivityCounter getWifiControllerActivity() {
6280 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006281 }
6282
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006283 @Override
6284 public ControllerActivityCounter getModemControllerActivity() {
6285 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006286 }
6287
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006288 @Override
6289 public boolean hasBluetoothActivityReporting() {
6290 return mHasBluetoothReporting;
6291 }
6292
6293 @Override
6294 public boolean hasWifiActivityReporting() {
6295 return mHasWifiReporting;
6296 }
6297
6298 @Override
6299 public boolean hasModemActivityReporting() {
6300 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006301 }
6302
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006303 @Override
6304 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006305 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6306 }
6307
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006308 @Override
6309 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006310 return mFlashlightOnTimer.getCountLocked(which);
6311 }
6312
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006313 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006314 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6315 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6316 }
6317
6318 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006319 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6320 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6321 }
6322
6323 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006324 public long getNetworkActivityBytes(int type, int which) {
6325 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6326 return mNetworkByteActivityCounters[type].getCountLocked(which);
6327 } else {
6328 return 0;
6329 }
6330 }
6331
6332 @Override
6333 public long getNetworkActivityPackets(int type, int which) {
6334 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6335 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006336 } else {
6337 return 0;
6338 }
6339 }
6340
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006341 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006342 final long currentTime = System.currentTimeMillis();
6343 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006344 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6345 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006346 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006347 return mStartClockTime;
6348 }
6349
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006350 @Override public String getStartPlatformVersion() {
6351 return mStartPlatformVersion;
6352 }
6353
6354 @Override public String getEndPlatformVersion() {
6355 return mEndPlatformVersion;
6356 }
6357
6358 @Override public int getParcelVersion() {
6359 return VERSION;
6360 }
6361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 @Override public boolean getIsOnBattery() {
6363 return mOnBattery;
6364 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6367 return mUidStats;
6368 }
6369
Adam Lesinski5f056f62016-07-14 16:56:08 -07006370 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6371 if (timer != null) {
6372 timer.detach();
6373 }
6374 }
6375
6376 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6377 boolean detachIfReset) {
6378 if (timer != null) {
6379 return timer.reset(detachIfReset);
6380 }
6381 return true;
6382 }
6383
Bookatz867c0d72017-03-07 18:23:42 -08006384 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6385 if (timer != null) {
6386 return timer.reset(detachIfReset);
6387 }
6388 return true;
6389 }
6390
Adam Lesinski5f056f62016-07-14 16:56:08 -07006391 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6392 if (counter != null) {
6393 counter.detach();
6394 }
6395 }
6396
6397 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6398 boolean detachIfReset) {
6399 if (counter != null) {
6400 counter.reset(detachIfReset);
6401 }
6402 }
6403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 /**
6405 * The statistics associated with a particular uid.
6406 */
Joe Onoratoabded112016-02-08 16:49:39 -08006407 public static class Uid extends BatteryStats.Uid {
6408 /**
6409 * BatteryStatsImpl that we are associated with.
6410 */
6411 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006414
Bookatz867c0d72017-03-07 18:23:42 -08006415 /** TimeBase for when uid is in background and device is on battery. */
6416 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6417 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006418 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6419 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006420
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006421 boolean mWifiRunning;
6422 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006423
The Android Open Source Project10592532009-03-18 17:39:46 -07006424 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006425 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006426
Nick Pelly6ccaa542012-06-15 15:22:47 -07006427 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006428 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006429
Dianne Hackborn61659e52014-07-09 16:13:01 -07006430 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006431 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6432 StopwatchTimer[] mWifiBatchedScanTimer;
6433
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006434 boolean mWifiMulticastEnabled;
6435 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006436
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006437 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006438 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006439 StopwatchTimer mFlashlightTurnedOnTimer;
6440 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006441 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006442 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006443 /** Total time spent by the uid holding any partial wakelocks. */
6444 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006445 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006446 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006447 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006448 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006449
Dianne Hackborna8d10942015-11-19 17:55:19 -08006450 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006451 StopwatchTimer[] mProcessStateTimer;
6452
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006453 boolean mInForegroundService = false;
6454
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006455 BatchTimer mVibratorOnTimer;
6456
Dianne Hackborn617f8772009-03-31 15:04:46 -07006457 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006458
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006459 LongSamplingCounter[] mNetworkByteActivityCounters;
6460 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006461 LongSamplingCounter mMobileRadioActiveTime;
6462 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006465 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6466 */
6467 private LongSamplingCounter mMobileRadioApWakeupCount;
6468
6469 /**
6470 * How many times this UID woke up the Application Processor due to a Wifi packet.
6471 */
6472 private LongSamplingCounter mWifiRadioApWakeupCount;
6473
6474 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006475 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006476 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006477 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006478 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006479
6480 /**
6481 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006482 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006483 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006484 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6485
6486 /**
6487 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6488 * Can be null if the UID has had no such activity.
6489 */
6490 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006491
6492 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006493 * The CPU times we had at the last history details update.
6494 */
6495 long mLastStepUserTime;
6496 long mLastStepSystemTime;
6497 long mCurStepUserTime;
6498 long mCurStepSystemTime;
6499
Joe Onoratoabded112016-02-08 16:49:39 -08006500 LongSamplingCounter mUserCpuTime;
6501 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006502 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006503
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006504 LongSamplingCounterArray mCpuFreqTimeMs;
6505 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
6506
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006507 LongSamplingCounterArray[] mProcStateTimeMs;
6508 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6509
6510 IntArray mChildUids;
6511
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006512 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 * The statistics we have collected for this uid's wake locks.
6514 */
Joe Onoratoabded112016-02-08 16:49:39 -08006515 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516
6517 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006518 * The statistics we have collected for this uid's syncs.
6519 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006520 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006521
6522 /**
6523 * The statistics we have collected for this uid's jobs.
6524 */
Bookatzaa4594a2017-03-24 12:39:56 -07006525 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006526
6527 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006528 * Count of the jobs that have completed and the reasons why they completed.
6529 */
6530 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6531
6532 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 * The statistics we have collected for this uid's sensor activations.
6534 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006535 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536
6537 /**
6538 * The statistics we have collected for this uid's processes.
6539 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006540 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541
6542 /**
6543 * The statistics we have collected for this uid's processes.
6544 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006545 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006546
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006547 /**
6548 * The transient wake stats we have collected for this uid's pids.
6549 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006550 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006551
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00006552 /**
6553 * The list of WorkChains associated with active bluetooth scans.
6554 *
6555 * NOTE: This is a hack and it only needs to exist because there's a "reset" API that is
6556 * supposed to stop and log all WorkChains that were currently active.
6557 */
6558 ArrayList<WorkChain> mAllBluetoothChains = null;
6559 ArrayList<WorkChain> mUnoptimizedBluetoothChains = null;
6560
Joe Onoratoabded112016-02-08 16:49:39 -08006561 public Uid(BatteryStatsImpl bsi, int uid) {
6562 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006563 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006564
Bookatz867c0d72017-03-07 18:23:42 -08006565 mOnBatteryBackgroundTimeBase = new TimeBase();
6566 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6567 mBsi.mClocks.elapsedRealtime() * 1000);
6568
Bookatzc8c44962017-05-11 12:12:54 -07006569 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6570 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6571 mBsi.mClocks.elapsedRealtime() * 1000);
6572
Joe Onoratoabded112016-02-08 16:49:39 -08006573 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6574 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006575
Dianne Hackborn657153b2016-07-29 14:54:14 -07006576 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006577 @Override public Wakelock instantiateObject() {
6578 return new Wakelock(mBsi, Uid.this);
6579 }
6580 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006581 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6582 @Override public DualTimer instantiateObject() {
6583 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6584 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006585 }
6586 };
Bookatzaa4594a2017-03-24 12:39:56 -07006587 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6588 @Override public DualTimer instantiateObject() {
6589 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6590 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006591 }
6592 };
6593
6594 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6595 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6596 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6597 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006598 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6599 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006600 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006601 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6602 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006603 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 }
6605
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006606 @VisibleForTesting
6607 public void setProcessStateForTest(int procState) {
6608 mProcessState = procState;
6609 }
6610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006612 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006613 return nullIfAllZeros(mCpuFreqTimeMs, which);
6614 }
6615
6616 @Override
6617 public long[] getScreenOffCpuFreqTimes(int which) {
6618 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6619 }
6620
6621 @Override
6622 public long[] getCpuFreqTimes(int which, int procState) {
6623 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006624 return null;
6625 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006626 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006627 return null;
6628 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006629 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6630 mProcStateTimeMs = null;
6631 return null;
6632 }
6633 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6634 }
6635
6636 @Override
6637 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6638 if (which < 0 || which >= NUM_PROCESS_STATE) {
6639 return null;
6640 }
6641 if (mProcStateScreenOffTimeMs == null) {
6642 return null;
6643 }
6644 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6645 mProcStateScreenOffTimeMs = null;
6646 return null;
6647 }
6648 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6649 }
6650
6651 public void addIsolatedUid(int isolatedUid) {
6652 if (mChildUids == null) {
6653 mChildUids = new IntArray();
6654 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6655 return;
6656 }
6657 mChildUids.add(isolatedUid);
6658 }
6659
6660 public void removeIsolatedUid(int isolatedUid) {
6661 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6662 if (idx < 0) {
6663 return;
6664 }
6665 mChildUids.remove(idx);
6666 }
6667
6668 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6669 if (cpuTimesMs == null) {
6670 return null;
6671 }
6672 final long[] counts = cpuTimesMs.getCountsLocked(which);
6673 if (counts == null) {
6674 return null;
6675 }
6676 // Return counts only if at least one of the elements is non-zero.
6677 for (int i = counts.length - 1; i >= 0; --i) {
6678 if (counts[i] != 0) {
6679 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006680 }
6681 }
6682 return null;
6683 }
6684
Sudheer Shankae544d162017-12-28 17:06:20 -08006685 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006686 if (mProcStateTimeMs == null) {
6687 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006688 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006689 if (mProcStateTimeMs[procState] == null
6690 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
6691 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6692 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006693 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006694 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006695 }
6696
Sudheer Shankae544d162017-12-28 17:06:20 -08006697 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6698 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006699 if (mProcStateScreenOffTimeMs == null) {
6700 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006701 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006702 if (mProcStateScreenOffTimeMs[procState] == null
6703 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
6704 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
6705 mBsi.mOnBatteryScreenOffTimeBase);
6706 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006707 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006708 }
6709
6710 @Override
Bookatzc8c44962017-05-11 12:12:54 -07006711 public Timer getAggregatedPartialWakelockTimer() {
6712 return mAggregatedPartialWakelockTimer;
6713 }
6714
6715 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006716 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006717 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 }
6719
6720 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07006721 public Timer getMulticastWakelockStats() {
6722 return mWifiMulticastTimer;
6723 }
6724
6725 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006726 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006727 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006728 }
6729
6730 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006731 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006732 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006733 }
6734
6735 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006736 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
6737 return mJobCompletions;
6738 }
6739
6740 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07006741 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006742 return mSensorStats;
6743 }
6744
6745 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006746 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 return mProcessStats;
6748 }
6749
6750 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006751 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 return mPackageStats;
6753 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006754
6755 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006756 public int getUid() {
6757 return mUid;
6758 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006759
6760 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006761 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006762 if (!mWifiRunning) {
6763 mWifiRunning = true;
6764 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006765 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
6766 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006767 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006768 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006769 }
6770 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006771
Dianne Hackborn617f8772009-03-31 15:04:46 -07006772 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006773 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006774 if (mWifiRunning) {
6775 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006776 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006777 }
6778 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006779
Dianne Hackborn617f8772009-03-31 15:04:46 -07006780 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006781 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006782 if (!mFullWifiLockOut) {
6783 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006784 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006785 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
6786 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006787 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006788 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006789 }
6790 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006791
The Android Open Source Project10592532009-03-18 17:39:46 -07006792 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006793 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006794 if (mFullWifiLockOut) {
6795 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006796 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006797 }
6798 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006799
The Android Open Source Project10592532009-03-18 17:39:46 -07006800 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006801 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006802 if (!mWifiScanStarted) {
6803 mWifiScanStarted = true;
6804 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006805 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
6806 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
6807 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006808 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006809 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006810 }
6811 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006812
The Android Open Source Project10592532009-03-18 17:39:46 -07006813 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006814 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006815 if (mWifiScanStarted) {
6816 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006817 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006818 }
6819 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006820
6821 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006822 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006823 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07006824 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006825 csph = csph >> 3;
6826 bin++;
6827 }
6828
6829 if (mWifiBatchedScanBinStarted == bin) return;
6830
6831 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
6832 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006833 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006834 }
6835 mWifiBatchedScanBinStarted = bin;
6836 if (mWifiBatchedScanTimer[bin] == null) {
6837 makeWifiBatchedScanBin(bin, null);
6838 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006839 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006840 }
6841
6842 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006843 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006844 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
6845 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006846 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006847 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6848 }
6849 }
6850
6851 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006852 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006853 if (!mWifiMulticastEnabled) {
6854 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006855 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006856 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6857 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006858 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006859 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006860 }
6861 }
6862
6863 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006864 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006865 if (mWifiMulticastEnabled) {
6866 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006867 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006868 }
6869 }
6870
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006871 @Override
6872 public ControllerActivityCounter getWifiControllerActivity() {
6873 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006874 }
6875
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006876 @Override
6877 public ControllerActivityCounter getBluetoothControllerActivity() {
6878 return mBluetoothControllerActivity;
6879 }
6880
6881 @Override
6882 public ControllerActivityCounter getModemControllerActivity() {
6883 return mModemControllerActivity;
6884 }
6885
6886 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
6887 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006888 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006889 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08006890 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006891 return mWifiControllerActivity;
6892 }
6893
6894 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
6895 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006896 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006897 NUM_BT_TX_LEVELS);
6898 }
6899 return mBluetoothControllerActivity;
6900 }
6901
6902 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
6903 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006904 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006905 ModemActivityInfo.TX_POWER_LEVELS);
6906 }
6907 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08006908 }
6909
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006910 public StopwatchTimer createAudioTurnedOnTimerLocked() {
6911 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006912 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
6913 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006914 }
6915 return mAudioTurnedOnTimer;
6916 }
6917
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006918 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006919 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006920 // TODO(statsd): Possibly use a worksource instead of a uid.
6921 StatsLog.write(StatsLog.AUDIO_STATE_CHANGED, getUid(), 1);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006922 }
6923
6924 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
6925 if (mAudioTurnedOnTimer != null) {
6926 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006927 if (!mAudioTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
6928 // TODO(statsd): Possibly use a worksource instead of a uid.
6929 StatsLog.write(StatsLog.AUDIO_STATE_CHANGED, getUid(), 0);
6930 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006931 }
6932 }
6933
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006934 public void noteResetAudioLocked(long elapsedRealtimeMs) {
6935 if (mAudioTurnedOnTimer != null) {
6936 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006937 // TODO(statsd): Possibly use a worksource instead of a uid.
6938 StatsLog.write(StatsLog.AUDIO_STATE_CHANGED, getUid(), 0);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006939 }
6940 }
6941
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006942 public StopwatchTimer createVideoTurnedOnTimerLocked() {
6943 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006944 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
6945 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006946 }
6947 return mVideoTurnedOnTimer;
6948 }
6949
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006950 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006951 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006952 // TODO(statsd): Possibly use a worksource instead of a uid.
6953 StatsLog.write(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), 1);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006954 }
6955
6956 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
6957 if (mVideoTurnedOnTimer != null) {
6958 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006959 if (!mVideoTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
6960 // TODO(statsd): Possibly use a worksource instead of a uid.
6961 StatsLog.write(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), 0);
6962 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006963 }
6964 }
6965
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006966 public void noteResetVideoLocked(long elapsedRealtimeMs) {
6967 if (mVideoTurnedOnTimer != null) {
6968 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006969 // TODO(statsd): Possibly use a worksource instead of a uid.
6970 StatsLog.write(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), 0);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006971 }
6972 }
6973
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006974 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
6975 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006976 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6977 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006978 }
6979 return mFlashlightTurnedOnTimer;
6980 }
6981
6982 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
6983 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006984 // TODO(statsd): Possibly use a worksource instead of a uid.
6985 StatsLog.write(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), 1);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006986 }
6987
6988 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
6989 if (mFlashlightTurnedOnTimer != null) {
6990 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07006991 if (!mFlashlightTurnedOnTimer.isRunningLocked()) {
6992 // TODO(statsd): Possibly use a worksource instead of a uid.
6993 StatsLog.write(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), 0);
6994 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006995 }
6996 }
6997
6998 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
6999 if (mFlashlightTurnedOnTimer != null) {
7000 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007001 // TODO(statsd): Possibly use a worksource instead of a uid.
7002 StatsLog.write(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), 0);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007003 }
7004 }
7005
7006 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7007 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007008 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7009 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007010 }
7011 return mCameraTurnedOnTimer;
7012 }
7013
7014 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7015 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007016 // TODO(statsd): Possibly use a worksource instead of a uid.
7017 StatsLog.write(StatsLog.CAMERA_STATE_CHANGED, getUid(), 1);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007018 }
7019
7020 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7021 if (mCameraTurnedOnTimer != null) {
7022 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007023 if (!mCameraTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
7024 // TODO(statsd): Possibly use a worksource instead of a uid.
7025 StatsLog.write(StatsLog.CAMERA_STATE_CHANGED, getUid(), 0);
7026 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007027 }
7028 }
7029
7030 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7031 if (mCameraTurnedOnTimer != null) {
7032 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007033 // TODO(statsd): Possibly use a worksource instead of a uid.
7034 StatsLog.write(StatsLog.CAMERA_STATE_CHANGED, getUid(), 0);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007035 }
7036 }
7037
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007038 public StopwatchTimer createForegroundActivityTimerLocked() {
7039 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007040 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7041 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007042 }
7043 return mForegroundActivityTimer;
7044 }
7045
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007046 public StopwatchTimer createForegroundServiceTimerLocked() {
7047 if (mForegroundServiceTimer == null) {
7048 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7049 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7050 }
7051 return mForegroundServiceTimer;
7052 }
7053
Bookatzc8c44962017-05-11 12:12:54 -07007054 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7055 if (mAggregatedPartialWakelockTimer == null) {
7056 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7057 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7058 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7059 }
7060 return mAggregatedPartialWakelockTimer;
7061 }
7062
Bookatz867c0d72017-03-07 18:23:42 -08007063 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007064 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007065 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7066 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7067 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007068 }
7069 return mBluetoothScanTimer;
7070 }
7071
Bookatzb1f04f32017-05-19 13:57:32 -07007072 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7073 if (mBluetoothUnoptimizedScanTimer == null) {
7074 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7075 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7076 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7077 }
7078 return mBluetoothUnoptimizedScanTimer;
7079 }
7080
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007081 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7082 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007083 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007084 if (isUnoptimized) {
7085 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7086 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007087 }
7088
Bookatz94c5a312017-07-11 16:49:17 -07007089 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007090 if (mBluetoothScanTimer != null) {
7091 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7092 }
Bookatz94c5a312017-07-11 16:49:17 -07007093 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007094 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7095 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007096 }
7097
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007098 public void addBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7099 if (mAllBluetoothChains == null) {
7100 mAllBluetoothChains = new ArrayList<WorkChain>(4);
7101 }
7102
7103 if (isUnoptimized && mUnoptimizedBluetoothChains == null) {
7104 mUnoptimizedBluetoothChains = new ArrayList<WorkChain>(4);
7105 }
7106
7107 mAllBluetoothChains.add(workChain);
7108 if (isUnoptimized) {
7109 mUnoptimizedBluetoothChains.add(workChain);
7110 }
7111 }
7112
7113 public void removeBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7114 if (mAllBluetoothChains != null) {
7115 mAllBluetoothChains.remove(workChain);
7116 }
7117
7118 if (isUnoptimized && mUnoptimizedBluetoothChains != null) {
7119 mUnoptimizedBluetoothChains.remove(workChain);
7120 }
7121 }
7122
7123 public List<WorkChain> getAllBluetoothWorkChains() {
7124 return mAllBluetoothChains;
7125 }
7126
7127 public List<WorkChain> getUnoptimizedBluetoothWorkChains() {
7128 return mUnoptimizedBluetoothChains;
7129 }
7130
7131
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007132 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7133 if (mBluetoothScanTimer != null) {
7134 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7135 }
Bookatzb1f04f32017-05-19 13:57:32 -07007136 if (mBluetoothUnoptimizedScanTimer != null) {
7137 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7138 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007139 }
7140
Bookatz956f36bf2017-04-28 09:48:17 -07007141 public Counter createBluetoothScanResultCounterLocked() {
7142 if (mBluetoothScanResultCounter == null) {
7143 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7144 }
7145 return mBluetoothScanResultCounter;
7146 }
7147
Bookatzb1f04f32017-05-19 13:57:32 -07007148 public Counter createBluetoothScanResultBgCounterLocked() {
7149 if (mBluetoothScanResultBgCounter == null) {
7150 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7151 }
7152 return mBluetoothScanResultBgCounter;
7153 }
7154
Bookatz4ebc0642017-05-11 12:21:19 -07007155 public void noteBluetoothScanResultsLocked(int numNewResults) {
7156 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007157 // Uses background timebase, so the count will only be incremented if uid in background.
7158 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007159 }
7160
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007161 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007162 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007163 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007164 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007165 }
7166
7167 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007168 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007169 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007170 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007171 }
7172 }
7173
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007174 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7175 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7176 }
7177
7178 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7179 if (mForegroundServiceTimer != null) {
7180 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7181 }
7182 }
7183
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007184 public BatchTimer createVibratorOnTimerLocked() {
7185 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007186 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7187 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007188 }
7189 return mVibratorOnTimer;
7190 }
7191
7192 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007193 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007194 }
7195
7196 public void noteVibratorOffLocked() {
7197 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007198 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007199 }
7200 }
7201
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007202 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007203 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007204 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007205 return 0;
7206 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007207 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007208 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007209
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007210 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007211 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007212 if (mFullWifiLockTimer == null) {
7213 return 0;
7214 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007215 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007216 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007217
7218 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007219 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007220 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007221 return 0;
7222 }
Bookatzaa4594a2017-03-24 12:39:56 -07007223 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007224 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007225
7226 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007227 public int getWifiScanCount(int which) {
7228 if (mWifiScanTimer == null) {
7229 return 0;
7230 }
Bookatzaa4594a2017-03-24 12:39:56 -07007231 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007232 }
7233
7234 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007235 public Timer getWifiScanTimer() {
7236 return mWifiScanTimer;
7237 }
7238
7239 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007240 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007241 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007242 return 0;
7243 }
7244 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7245 }
7246
7247 @Override
7248 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7249 if (mWifiScanTimer == null) {
7250 return 0;
7251 }
7252 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007253 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007254 }
7255
7256 @Override
7257 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007258 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007259 return 0;
7260 }
7261 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7262 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007263 }
7264
7265 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007266 public Timer getWifiScanBackgroundTimer() {
7267 if (mWifiScanTimer == null) {
7268 return null;
7269 }
7270 return mWifiScanTimer.getSubTimer();
7271 }
7272
7273 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007274 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007275 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7276 if (mWifiBatchedScanTimer[csphBin] == null) {
7277 return 0;
7278 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007279 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007280 }
7281
7282 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007283 public int getWifiBatchedScanCount(int csphBin, int which) {
7284 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7285 if (mWifiBatchedScanTimer[csphBin] == null) {
7286 return 0;
7287 }
7288 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7289 }
7290
7291 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007292 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007293 if (mWifiMulticastTimer == null) {
7294 return 0;
7295 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007296 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007297 }
7298
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007299 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007300 public Timer getAudioTurnedOnTimer() {
7301 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007302 }
7303
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007304 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007305 public Timer getVideoTurnedOnTimer() {
7306 return mVideoTurnedOnTimer;
7307 }
7308
7309 @Override
7310 public Timer getFlashlightTurnedOnTimer() {
7311 return mFlashlightTurnedOnTimer;
7312 }
7313
7314 @Override
7315 public Timer getCameraTurnedOnTimer() {
7316 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007317 }
7318
Dianne Hackborn617f8772009-03-31 15:04:46 -07007319 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007320 public Timer getForegroundActivityTimer() {
7321 return mForegroundActivityTimer;
7322 }
7323
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007324 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007325 public Timer getForegroundServiceTimer() {
7326 return mForegroundServiceTimer;
7327 }
7328
7329 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007330 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007331 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007332 }
7333
7334 @Override
7335 public Timer getBluetoothScanBackgroundTimer() {
7336 if (mBluetoothScanTimer == null) {
7337 return null;
7338 }
7339 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007340 }
7341
Bookatz956f36bf2017-04-28 09:48:17 -07007342 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007343 public Timer getBluetoothUnoptimizedScanTimer() {
7344 return mBluetoothUnoptimizedScanTimer;
7345 }
7346
7347 @Override
7348 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7349 if (mBluetoothUnoptimizedScanTimer == null) {
7350 return null;
7351 }
7352 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7353 }
7354
7355 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007356 public Counter getBluetoothScanResultCounter() {
7357 return mBluetoothScanResultCounter;
7358 }
7359
Bookatzb1f04f32017-05-19 13:57:32 -07007360 @Override
7361 public Counter getBluetoothScanResultBgCounter() {
7362 return mBluetoothScanResultBgCounter;
7363 }
7364
Dianne Hackborn61659e52014-07-09 16:13:01 -07007365 void makeProcessState(int i, Parcel in) {
7366 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7367
7368 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007369 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7370 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007371 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007372 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7373 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007374 }
7375 }
7376
7377 @Override
7378 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7379 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7380 if (mProcessStateTimer[state] == null) {
7381 return 0;
7382 }
7383 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7384 }
7385
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007386 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007387 public Timer getProcessStateTimer(int state) {
7388 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7389 return mProcessStateTimer[state];
7390 }
7391
7392 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007393 public Timer getVibratorOnTimer() {
7394 return mVibratorOnTimer;
7395 }
7396
7397 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007398 public void noteUserActivityLocked(int type) {
7399 if (mUserActivityCounters == null) {
7400 initUserActivityLocked();
7401 }
Jeff Browndf693de2012-07-27 12:03:38 -07007402 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7403 mUserActivityCounters[type].stepAtomic();
7404 } else {
7405 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7406 new Throwable());
7407 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007408 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007409
Dianne Hackborn617f8772009-03-31 15:04:46 -07007410 @Override
7411 public boolean hasUserActivity() {
7412 return mUserActivityCounters != null;
7413 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007414
Dianne Hackborn617f8772009-03-31 15:04:46 -07007415 @Override
7416 public int getUserActivityCount(int type, int which) {
7417 if (mUserActivityCounters == null) {
7418 return 0;
7419 }
Evan Millarc64edde2009-04-18 12:26:32 -07007420 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007421 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007422
Robert Greenwalta029ea12013-09-25 16:38:12 -07007423 void makeWifiBatchedScanBin(int i, Parcel in) {
7424 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7425
Joe Onoratoabded112016-02-08 16:49:39 -08007426 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007427 if (collected == null) {
7428 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007429 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007430 }
7431 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007432 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7433 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007434 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007435 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7436 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007437 }
7438 }
7439
7440
Dianne Hackborn617f8772009-03-31 15:04:46 -07007441 void initUserActivityLocked() {
7442 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7443 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007444 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007445 }
7446 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007447
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007448 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7449 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007450 initNetworkActivityLocked();
7451 }
7452 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007453 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7454 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007455 } else {
7456 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7457 new Throwable());
7458 }
7459 }
7460
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007461 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7462 if (mNetworkByteActivityCounters == null) {
7463 initNetworkActivityLocked();
7464 }
7465 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7466 mMobileRadioActiveCount.addCountLocked(1);
7467 }
7468
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007469 @Override
7470 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007471 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007472 }
7473
7474 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007475 public long getNetworkActivityBytes(int type, int which) {
7476 if (mNetworkByteActivityCounters != null && type >= 0
7477 && type < mNetworkByteActivityCounters.length) {
7478 return mNetworkByteActivityCounters[type].getCountLocked(which);
7479 } else {
7480 return 0;
7481 }
7482 }
7483
7484 @Override
7485 public long getNetworkActivityPackets(int type, int which) {
7486 if (mNetworkPacketActivityCounters != null && type >= 0
7487 && type < mNetworkPacketActivityCounters.length) {
7488 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007489 } else {
7490 return 0;
7491 }
7492 }
7493
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007494 @Override
7495 public long getMobileRadioActiveTime(int which) {
7496 return mMobileRadioActiveTime != null
7497 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7498 }
7499
7500 @Override
7501 public int getMobileRadioActiveCount(int which) {
7502 return mMobileRadioActiveCount != null
7503 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7504 }
7505
Adam Lesinskie08af192015-03-25 16:42:59 -07007506 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007507 public long getUserCpuTimeUs(int which) {
7508 return mUserCpuTime.getCountLocked(which);
7509 }
7510
7511 @Override
7512 public long getSystemCpuTimeUs(int which) {
7513 return mSystemCpuTime.getCountLocked(which);
7514 }
7515
7516 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007517 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007518 if (mCpuClusterSpeedTimesUs != null) {
7519 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7520 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7521 if (cpuSpeedTimesUs != null) {
7522 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7523 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007524 if (c != null) {
7525 return c.getCountLocked(which);
7526 }
7527 }
7528 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007529 }
7530 }
7531 return 0;
7532 }
7533
Adam Lesinski5f056f62016-07-14 16:56:08 -07007534 public void noteMobileRadioApWakeupLocked() {
7535 if (mMobileRadioApWakeupCount == null) {
7536 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7537 }
7538 mMobileRadioApWakeupCount.addCountLocked(1);
7539 }
7540
7541 @Override
7542 public long getMobileRadioApWakeupCount(int which) {
7543 if (mMobileRadioApWakeupCount != null) {
7544 return mMobileRadioApWakeupCount.getCountLocked(which);
7545 }
7546 return 0;
7547 }
7548
7549 public void noteWifiRadioApWakeupLocked() {
7550 if (mWifiRadioApWakeupCount == null) {
7551 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7552 }
7553 mWifiRadioApWakeupCount.addCountLocked(1);
7554 }
7555
7556 @Override
7557 public long getWifiRadioApWakeupCount(int which) {
7558 if (mWifiRadioApWakeupCount != null) {
7559 return mWifiRadioApWakeupCount.getCountLocked(which);
7560 }
7561 return 0;
7562 }
7563
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007564 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007565 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7566 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007567 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007568 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7569 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007570 }
Joe Onoratoabded112016-02-08 16:49:39 -08007571 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7572 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007574
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007575 /**
7576 * Clear all stats for this uid. Returns true if the uid is completely
7577 * inactive so can be dropped.
7578 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007579 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007580 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007581 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007582
Bookatz993a0be2017-07-21 09:03:23 -07007583 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7584 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7585
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007586 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007587 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007588 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007589 }
7590 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007591 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007592 active |= mFullWifiLockOut;
7593 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007594 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007595 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007596 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007597 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007598 if (mWifiBatchedScanTimer != null) {
7599 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7600 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007601 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007602 }
7603 }
7604 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7605 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007606 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007607 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007608 active |= mWifiMulticastEnabled;
7609 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007610
7611 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7612 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7613 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7614 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7615 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007616 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007617 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007618 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007619 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007620 if (mBluetoothScanResultCounter != null) {
7621 mBluetoothScanResultCounter.reset(false);
7622 }
Bookatzb1f04f32017-05-19 13:57:32 -07007623 if (mBluetoothScanResultBgCounter != null) {
7624 mBluetoothScanResultBgCounter.reset(false);
7625 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007626
Dianne Hackborn61659e52014-07-09 16:13:01 -07007627 if (mProcessStateTimer != null) {
7628 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7629 if (mProcessStateTimer[i] != null) {
7630 active |= !mProcessStateTimer[i].reset(false);
7631 }
7632 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007633 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007634 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007635 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007636 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007637 mVibratorOnTimer.detach();
7638 mVibratorOnTimer = null;
7639 } else {
7640 active = true;
7641 }
7642 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007643
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007644 if (mUserActivityCounters != null) {
7645 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7646 mUserActivityCounters[i].reset(false);
7647 }
7648 }
7649
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007650 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007651 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007652 mNetworkByteActivityCounters[i].reset(false);
7653 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007654 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007655 mMobileRadioActiveTime.reset(false);
7656 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007657 }
7658
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007659 if (mWifiControllerActivity != null) {
7660 mWifiControllerActivity.reset(false);
7661 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007662
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007663 if (mBluetoothControllerActivity != null) {
7664 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007665 }
7666
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007667 if (mModemControllerActivity != null) {
7668 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007669 }
7670
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007671 mUserCpuTime.reset(false);
7672 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007673
Sudheer Shankaaf857412017-07-21 00:14:24 -07007674 if (mCpuClusterSpeedTimesUs != null) {
7675 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007676 if (speeds != null) {
7677 for (LongSamplingCounter speed : speeds) {
7678 if (speed != null) {
7679 speed.reset(false);
7680 }
7681 }
7682 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007683 }
7684 }
7685
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007686 if (mCpuFreqTimeMs != null) {
7687 mCpuFreqTimeMs.reset(false);
7688 }
7689 if (mScreenOffCpuFreqTimeMs != null) {
7690 mScreenOffCpuFreqTimeMs.reset(false);
7691 }
7692
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007693 if (mProcStateTimeMs != null) {
7694 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7695 if (counters != null) {
7696 counters.reset(false);
7697 }
7698 }
7699 }
7700 if (mProcStateScreenOffTimeMs != null) {
7701 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7702 if (counters != null) {
7703 counters.reset(false);
7704 }
7705 }
7706 }
7707
Adam Lesinski5f056f62016-07-14 16:56:08 -07007708 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
7709 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
7710
Dianne Hackbornd953c532014-08-16 18:17:38 -07007711 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7712 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
7713 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007714 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007715 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007716 } else {
7717 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007718 }
7719 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007720 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07007721 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007722 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07007723 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007724 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007725 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007726 timer.detach();
7727 } else {
7728 active = true;
7729 }
7730 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007731 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07007732 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007733 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07007734 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007735 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007736 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007737 timer.detach();
7738 } else {
7739 active = true;
7740 }
7741 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007742 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007743 mJobCompletions.clear();
Dianne Hackborn61659e52014-07-09 16:13:01 -07007744 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
7745 Sensor s = mSensorStats.valueAt(ise);
7746 if (s.reset()) {
7747 mSensorStats.removeAt(ise);
7748 } else {
7749 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007750 }
7751 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07007752 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
7753 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08007754 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007755 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007756 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007757 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007758 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007759 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007760 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007761 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007762 } else {
7763 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007764 }
7765 }
7766 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007767 if (mPackageStats.size() > 0) {
7768 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
7769 while (it.hasNext()) {
7770 Map.Entry<String, Pkg> pkgEntry = it.next();
7771 Pkg p = pkgEntry.getValue();
7772 p.detach();
7773 if (p.mServiceStats.size() > 0) {
7774 Iterator<Map.Entry<String, Pkg.Serv>> it2
7775 = p.mServiceStats.entrySet().iterator();
7776 while (it2.hasNext()) {
7777 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
7778 servEntry.getValue().detach();
7779 }
7780 }
7781 }
7782 mPackageStats.clear();
7783 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007784
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08007785 mLastStepUserTime = mLastStepSystemTime = 0;
7786 mCurStepUserTime = mCurStepSystemTime = 0;
7787
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007788 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007789 if (mWifiRunningTimer != null) {
7790 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007791 }
7792 if (mFullWifiLockTimer != null) {
7793 mFullWifiLockTimer.detach();
7794 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007795 if (mWifiScanTimer != null) {
7796 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007797 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007798 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7799 if (mWifiBatchedScanTimer[i] != null) {
7800 mWifiBatchedScanTimer[i].detach();
7801 }
7802 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007803 if (mWifiMulticastTimer != null) {
7804 mWifiMulticastTimer.detach();
7805 }
7806 if (mAudioTurnedOnTimer != null) {
7807 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007808 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007809 }
7810 if (mVideoTurnedOnTimer != null) {
7811 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007812 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007813 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007814 if (mFlashlightTurnedOnTimer != null) {
7815 mFlashlightTurnedOnTimer.detach();
7816 mFlashlightTurnedOnTimer = null;
7817 }
7818 if (mCameraTurnedOnTimer != null) {
7819 mCameraTurnedOnTimer.detach();
7820 mCameraTurnedOnTimer = null;
7821 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007822 if (mForegroundActivityTimer != null) {
7823 mForegroundActivityTimer.detach();
7824 mForegroundActivityTimer = null;
7825 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007826 if (mForegroundServiceTimer != null) {
7827 mForegroundServiceTimer.detach();
7828 mForegroundServiceTimer = null;
7829 }
Bookatzc8c44962017-05-11 12:12:54 -07007830 if (mAggregatedPartialWakelockTimer != null) {
7831 mAggregatedPartialWakelockTimer.detach();
7832 mAggregatedPartialWakelockTimer = null;
7833 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007834 if (mBluetoothScanTimer != null) {
7835 mBluetoothScanTimer.detach();
7836 mBluetoothScanTimer = null;
7837 }
Bookatzb1f04f32017-05-19 13:57:32 -07007838 if (mBluetoothUnoptimizedScanTimer != null) {
7839 mBluetoothUnoptimizedScanTimer.detach();
7840 mBluetoothUnoptimizedScanTimer = null;
7841 }
Bookatz956f36bf2017-04-28 09:48:17 -07007842 if (mBluetoothScanResultCounter != null) {
7843 mBluetoothScanResultCounter.detach();
7844 mBluetoothScanResultCounter = null;
7845 }
Bookatzb1f04f32017-05-19 13:57:32 -07007846 if (mBluetoothScanResultBgCounter != null) {
7847 mBluetoothScanResultBgCounter.detach();
7848 mBluetoothScanResultBgCounter = null;
7849 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007850 if (mUserActivityCounters != null) {
7851 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7852 mUserActivityCounters[i].detach();
7853 }
7854 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007855 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007856 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007857 mNetworkByteActivityCounters[i].detach();
7858 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007859 }
7860 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007861
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007862 if (mWifiControllerActivity != null) {
7863 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07007864 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007865
7866 if (mBluetoothControllerActivity != null) {
7867 mBluetoothControllerActivity.detach();
7868 }
7869
7870 if (mModemControllerActivity != null) {
7871 mModemControllerActivity.detach();
7872 }
7873
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007874 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007875
7876 mUserCpuTime.detach();
7877 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07007878
Sudheer Shankaaf857412017-07-21 00:14:24 -07007879 if (mCpuClusterSpeedTimesUs != null) {
7880 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007881 if (cpuSpeeds != null) {
7882 for (LongSamplingCounter c : cpuSpeeds) {
7883 if (c != null) {
7884 c.detach();
7885 }
7886 }
7887 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007888 }
7889 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007890
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007891 if (mCpuFreqTimeMs != null) {
7892 mCpuFreqTimeMs.detach();
7893 }
7894 if (mScreenOffCpuFreqTimeMs != null) {
7895 mScreenOffCpuFreqTimeMs.detach();
7896 }
7897
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007898 if (mProcStateTimeMs != null) {
7899 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7900 if (counters != null) {
7901 counters.detach();
7902 }
7903 }
7904 }
7905 if (mProcStateScreenOffTimeMs != null) {
7906 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7907 if (counters != null) {
7908 counters.detach();
7909 }
7910 }
7911 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007912 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
7913 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007914 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007915
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007916 return !active;
7917 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007918
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007919 void writeJobCompletionsToParcelLocked(Parcel out) {
7920 int NJC = mJobCompletions.size();
7921 out.writeInt(NJC);
7922 for (int ijc=0; ijc<NJC; ijc++) {
7923 out.writeString(mJobCompletions.keyAt(ijc));
7924 SparseIntArray types = mJobCompletions.valueAt(ijc);
7925 int NT = types.size();
7926 out.writeInt(NT);
7927 for (int it=0; it<NT; it++) {
7928 out.writeInt(types.keyAt(it));
7929 out.writeInt(types.valueAt(it));
7930 }
7931 }
7932 }
7933
Bookatz867c0d72017-03-07 18:23:42 -08007934 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
7935 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07007936 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08007937
Dianne Hackbornd953c532014-08-16 18:17:38 -07007938 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7939 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07007940 out.writeInt(NW);
7941 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007942 out.writeString(wakeStats.keyAt(iw));
7943 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007944 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007945 }
7946
Bookatz2bffb5b2017-04-13 11:59:33 -07007947 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007948 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007949 out.writeInt(NS);
7950 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007951 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07007952 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007953 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
7954 }
7955
Bookatzaa4594a2017-03-24 12:39:56 -07007956 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007957 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007958 out.writeInt(NJ);
7959 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007960 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07007961 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007962 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
7963 }
7964
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007965 writeJobCompletionsToParcelLocked(out);
7966
Dianne Hackborn61659e52014-07-09 16:13:01 -07007967 int NSE = mSensorStats.size();
7968 out.writeInt(NSE);
7969 for (int ise=0; ise<NSE; ise++) {
7970 out.writeInt(mSensorStats.keyAt(ise));
7971 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007972 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973 }
7974
Dianne Hackborn61659e52014-07-09 16:13:01 -07007975 int NP = mProcessStats.size();
7976 out.writeInt(NP);
7977 for (int ip=0; ip<NP; ip++) {
7978 out.writeString(mProcessStats.keyAt(ip));
7979 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 proc.writeToParcelLocked(out);
7981 }
7982
7983 out.writeInt(mPackageStats.size());
7984 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
7985 out.writeString(pkgEntry.getKey());
7986 Uid.Pkg pkg = pkgEntry.getValue();
7987 pkg.writeToParcelLocked(out);
7988 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007989
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007990 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007991 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007992 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007993 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007994 out.writeInt(0);
7995 }
7996 if (mFullWifiLockTimer != null) {
7997 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007998 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007999 } else {
8000 out.writeInt(0);
8001 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008002 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008003 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008004 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008005 } else {
8006 out.writeInt(0);
8007 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008008 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8009 if (mWifiBatchedScanTimer[i] != null) {
8010 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008011 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008012 } else {
8013 out.writeInt(0);
8014 }
8015 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008016 if (mWifiMulticastTimer != null) {
8017 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008018 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008019 } else {
8020 out.writeInt(0);
8021 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008022
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008023 if (mAudioTurnedOnTimer != null) {
8024 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008025 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008026 } else {
8027 out.writeInt(0);
8028 }
8029 if (mVideoTurnedOnTimer != null) {
8030 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008031 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008032 } else {
8033 out.writeInt(0);
8034 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008035 if (mFlashlightTurnedOnTimer != null) {
8036 out.writeInt(1);
8037 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8038 } else {
8039 out.writeInt(0);
8040 }
8041 if (mCameraTurnedOnTimer != null) {
8042 out.writeInt(1);
8043 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8044 } else {
8045 out.writeInt(0);
8046 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008047 if (mForegroundActivityTimer != null) {
8048 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008049 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008050 } else {
8051 out.writeInt(0);
8052 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008053 if (mForegroundServiceTimer != null) {
8054 out.writeInt(1);
8055 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8056 } else {
8057 out.writeInt(0);
8058 }
Bookatzc8c44962017-05-11 12:12:54 -07008059 if (mAggregatedPartialWakelockTimer != null) {
8060 out.writeInt(1);
8061 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8062 } else {
8063 out.writeInt(0);
8064 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008065 if (mBluetoothScanTimer != null) {
8066 out.writeInt(1);
8067 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8068 } else {
8069 out.writeInt(0);
8070 }
Bookatzb1f04f32017-05-19 13:57:32 -07008071 if (mBluetoothUnoptimizedScanTimer != null) {
8072 out.writeInt(1);
8073 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8074 } else {
8075 out.writeInt(0);
8076 }
Bookatz956f36bf2017-04-28 09:48:17 -07008077 if (mBluetoothScanResultCounter != null) {
8078 out.writeInt(1);
8079 mBluetoothScanResultCounter.writeToParcel(out);
8080 } else {
8081 out.writeInt(0);
8082 }
Bookatzb1f04f32017-05-19 13:57:32 -07008083 if (mBluetoothScanResultBgCounter != null) {
8084 out.writeInt(1);
8085 mBluetoothScanResultBgCounter.writeToParcel(out);
8086 } else {
8087 out.writeInt(0);
8088 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008089 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8090 if (mProcessStateTimer[i] != null) {
8091 out.writeInt(1);
8092 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8093 } else {
8094 out.writeInt(0);
8095 }
8096 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008097 if (mVibratorOnTimer != null) {
8098 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008099 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008100 } else {
8101 out.writeInt(0);
8102 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008103 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008104 out.writeInt(1);
8105 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8106 mUserActivityCounters[i].writeToParcel(out);
8107 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008108 } else {
8109 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008110 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008111 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008112 out.writeInt(1);
8113 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008114 mNetworkByteActivityCounters[i].writeToParcel(out);
8115 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008116 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008117 mMobileRadioActiveTime.writeToParcel(out);
8118 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008119 } else {
8120 out.writeInt(0);
8121 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008122
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008123 if (mWifiControllerActivity != null) {
8124 out.writeInt(1);
8125 mWifiControllerActivity.writeToParcel(out, 0);
8126 } else {
8127 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008128 }
8129
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008130 if (mBluetoothControllerActivity != null) {
8131 out.writeInt(1);
8132 mBluetoothControllerActivity.writeToParcel(out, 0);
8133 } else {
8134 out.writeInt(0);
8135 }
8136
8137 if (mModemControllerActivity != null) {
8138 out.writeInt(1);
8139 mModemControllerActivity.writeToParcel(out, 0);
8140 } else {
8141 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008142 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008143
8144 mUserCpuTime.writeToParcel(out);
8145 mSystemCpuTime.writeToParcel(out);
8146
Sudheer Shankaaf857412017-07-21 00:14:24 -07008147 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008148 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008149 out.writeInt(mCpuClusterSpeedTimesUs.length);
8150 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008151 if (cpuSpeeds != null) {
8152 out.writeInt(1);
8153 out.writeInt(cpuSpeeds.length);
8154 for (LongSamplingCounter c : cpuSpeeds) {
8155 if (c != null) {
8156 out.writeInt(1);
8157 c.writeToParcel(out);
8158 } else {
8159 out.writeInt(0);
8160 }
8161 }
8162 } else {
8163 out.writeInt(0);
8164 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008165 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008166 } else {
8167 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008168 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008169
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008170 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8171 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008172 if (mProcStateTimeMs != null) {
8173 out.writeInt(mProcStateTimeMs.length);
8174 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8175 LongSamplingCounterArray.writeToParcel(out, counters);
8176 }
8177 } else {
8178 out.writeInt(0);
8179 }
8180 if (mProcStateScreenOffTimeMs != null) {
8181 out.writeInt(mProcStateScreenOffTimeMs.length);
8182 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8183 LongSamplingCounterArray.writeToParcel(out, counters);
8184 }
8185 } else {
8186 out.writeInt(0);
8187 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008188
Adam Lesinski5f056f62016-07-14 16:56:08 -07008189 if (mMobileRadioApWakeupCount != null) {
8190 out.writeInt(1);
8191 mMobileRadioApWakeupCount.writeToParcel(out);
8192 } else {
8193 out.writeInt(0);
8194 }
8195
8196 if (mWifiRadioApWakeupCount != null) {
8197 out.writeInt(1);
8198 mWifiRadioApWakeupCount.writeToParcel(out);
8199 } else {
8200 out.writeInt(0);
8201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008202 }
8203
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008204 void readJobCompletionsFromParcelLocked(Parcel in) {
8205 int numJobCompletions = in.readInt();
8206 mJobCompletions.clear();
8207 for (int j = 0; j < numJobCompletions; j++) {
8208 String jobName = in.readString();
8209 int numTypes = in.readInt();
8210 if (numTypes > 0) {
8211 SparseIntArray types = new SparseIntArray();
8212 for (int k = 0; k < numTypes; k++) {
8213 int type = in.readInt();
8214 int count = in.readInt();
8215 types.put(type, count);
8216 }
8217 mJobCompletions.put(jobName, types);
8218 }
8219 }
8220 }
8221
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008222 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008223 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008224 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008226 int numWakelocks = in.readInt();
8227 mWakelockStats.clear();
8228 for (int j = 0; j < numWakelocks; j++) {
8229 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008230 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008231 wakelock.readFromParcelLocked(
8232 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008233 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008234 }
8235
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008236 int numSyncs = in.readInt();
8237 mSyncStats.clear();
8238 for (int j = 0; j < numSyncs; j++) {
8239 String syncName = in.readString();
8240 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008241 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8242 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008243 }
8244 }
8245
8246 int numJobs = in.readInt();
8247 mJobStats.clear();
8248 for (int j = 0; j < numJobs; j++) {
8249 String jobName = in.readString();
8250 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008251 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8252 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008253 }
8254 }
8255
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008256 readJobCompletionsFromParcelLocked(in);
8257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008258 int numSensors = in.readInt();
8259 mSensorStats.clear();
8260 for (int k = 0; k < numSensors; k++) {
8261 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008262 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008263 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8264 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008265 mSensorStats.put(sensorNumber, sensor);
8266 }
8267
8268 int numProcs = in.readInt();
8269 mProcessStats.clear();
8270 for (int k = 0; k < numProcs; k++) {
8271 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008272 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008273 proc.readFromParcelLocked(in);
8274 mProcessStats.put(processName, proc);
8275 }
8276
8277 int numPkgs = in.readInt();
8278 mPackageStats.clear();
8279 for (int l = 0; l < numPkgs; l++) {
8280 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008281 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 pkg.readFromParcelLocked(in);
8283 mPackageStats.put(packageName, pkg);
8284 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008285
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008286 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008287 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008288 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8289 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008290 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008291 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008292 }
8293 mFullWifiLockOut = false;
8294 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008295 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8296 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008297 } else {
8298 mFullWifiLockTimer = null;
8299 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008300 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008301 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008302 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8303 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8304 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008305 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008306 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008307 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008308 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8309 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8310 if (in.readInt() != 0) {
8311 makeWifiBatchedScanBin(i, in);
8312 } else {
8313 mWifiBatchedScanTimer[i] = null;
8314 }
8315 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008316 mWifiMulticastEnabled = false;
8317 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008318 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8319 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008320 } else {
8321 mWifiMulticastTimer = null;
8322 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008323 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008324 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8325 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008326 } else {
8327 mAudioTurnedOnTimer = null;
8328 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008329 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008330 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8331 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008332 } else {
8333 mVideoTurnedOnTimer = null;
8334 }
8335 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008336 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8337 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008338 } else {
8339 mFlashlightTurnedOnTimer = null;
8340 }
8341 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008342 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8343 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008344 } else {
8345 mCameraTurnedOnTimer = null;
8346 }
8347 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008348 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8349 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008350 } else {
8351 mForegroundActivityTimer = null;
8352 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008353 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008354 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8355 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8356 } else {
8357 mForegroundServiceTimer = null;
8358 }
8359 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008360 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8361 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8362 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8363 in);
8364 } else {
8365 mAggregatedPartialWakelockTimer = null;
8366 }
8367 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008368 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8369 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8370 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008371 } else {
8372 mBluetoothScanTimer = null;
8373 }
Bookatz956f36bf2017-04-28 09:48:17 -07008374 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008375 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8376 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8377 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8378 } else {
8379 mBluetoothUnoptimizedScanTimer = null;
8380 }
8381 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008382 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8383 } else {
8384 mBluetoothScanResultCounter = null;
8385 }
Bookatzb1f04f32017-05-19 13:57:32 -07008386 if (in.readInt() != 0) {
8387 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8388 } else {
8389 mBluetoothScanResultBgCounter = null;
8390 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008391 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008392 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8393 if (in.readInt() != 0) {
8394 makeProcessState(i, in);
8395 } else {
8396 mProcessStateTimer[i] = null;
8397 }
8398 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008399 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008400 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8401 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008402 } else {
8403 mVibratorOnTimer = null;
8404 }
8405 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008406 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8407 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008408 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008409 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008410 } else {
8411 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008412 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008413 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008414 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8415 mNetworkPacketActivityCounters
8416 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008417 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008418 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008419 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008420 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008421 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008422 }
Joe Onoratoabded112016-02-08 16:49:39 -08008423 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8424 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008425 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008426 mNetworkByteActivityCounters = null;
8427 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008428 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008429
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008430 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008431 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008432 NUM_WIFI_TX_LEVELS, in);
8433 } else {
8434 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008435 }
8436
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008437 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008438 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008439 NUM_BT_TX_LEVELS, in);
8440 } else {
8441 mBluetoothControllerActivity = null;
8442 }
8443
8444 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008445 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008446 ModemActivityInfo.TX_POWER_LEVELS, in);
8447 } else {
8448 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008449 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008450
Joe Onoratoabded112016-02-08 16:49:39 -08008451 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8452 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008453
Adam Lesinski6832f392015-09-05 18:05:40 -07008454 if (in.readInt() != 0) {
8455 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008456 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008457 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008458 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008459
Sudheer Shankaaf857412017-07-21 00:14:24 -07008460 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008461 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8462 if (in.readInt() != 0) {
8463 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008464 if (mBsi.mPowerProfile != null &&
8465 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008466 throw new ParcelFormatException("Incompatible number of cpu speeds");
8467 }
8468
8469 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008470 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008471 for (int speed = 0; speed < numSpeeds; speed++) {
8472 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008473 cpuSpeeds[speed] = new LongSamplingCounter(
8474 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008475 }
8476 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008477 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008478 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008479 }
8480 }
8481 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008482 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008483 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008484
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008485 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8486 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8487 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008488
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008489 int length = in.readInt();
8490 if (length == NUM_PROCESS_STATE) {
8491 mProcStateTimeMs = new LongSamplingCounterArray[length];
8492 for (int procState = 0; procState < length; ++procState) {
8493 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8494 in, mBsi.mOnBatteryTimeBase);
8495 }
8496 } else {
8497 mProcStateTimeMs = null;
8498 }
8499 length = in.readInt();
8500 if (length == NUM_PROCESS_STATE) {
8501 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8502 for (int procState = 0; procState < length; ++procState) {
8503 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8504 in, mBsi.mOnBatteryScreenOffTimeBase);
8505 }
8506 } else {
8507 mProcStateScreenOffTimeMs = null;
8508 }
8509
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008510 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008511 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8512 } else {
8513 mMobileRadioApWakeupCount = null;
8514 }
8515
8516 if (in.readInt() != 0) {
8517 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8518 } else {
8519 mWifiRadioApWakeupCount = null;
8520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008521 }
8522
8523 /**
8524 * The statistics associated with a particular wake lock.
8525 */
Joe Onoratoabded112016-02-08 16:49:39 -08008526 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8527 /**
8528 * BatteryStatsImpl that we are associated with.
8529 */
8530 protected BatteryStatsImpl mBsi;
8531
8532 /**
8533 * BatteryStatsImpl that we are associated with.
8534 */
8535 protected Uid mUid;
8536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008537 /**
8538 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008539 * 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 -08008540 */
Bookatz5b5ec322017-05-26 09:40:38 -07008541 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008542
8543 /**
8544 * How long (in ms) this uid has been keeping the device fully awake.
8545 */
Evan Millarc64edde2009-04-18 12:26:32 -07008546 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547
8548 /**
8549 * How long (in ms) this uid has had a window keeping the device awake.
8550 */
Evan Millarc64edde2009-04-18 12:26:32 -07008551 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552
8553 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008554 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008555 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008556 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008557
Joe Onoratoabded112016-02-08 16:49:39 -08008558 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8559 mBsi = bsi;
8560 mUid = uid;
8561 }
8562
Adam Lesinski9425fe22015-06-19 12:02:13 -07008563 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008564 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8565 * proper timer pool from the given BatteryStatsImpl object.
8566 *
8567 * @param in the Parcel to be read from.
8568 * return a new Timer, or null.
8569 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008570 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8571 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008572 if (in.readInt() == 0) {
8573 return null;
8574 }
8575
Joe Onoratoabded112016-02-08 16:49:39 -08008576 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 }
8578
Joe Onorato92fd23f2016-07-25 11:18:42 -07008579 /**
8580 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8581 * proper timer pool from the given BatteryStatsImpl object.
8582 *
8583 * @param in the Parcel to be read from.
8584 * return a new Timer, or null.
8585 */
Bookatz5b5ec322017-05-26 09:40:38 -07008586 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8587 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008588 if (in.readInt() == 0) {
8589 return null;
8590 }
8591
Bookatz5b5ec322017-05-26 09:40:38 -07008592 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008593 }
8594
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008595 boolean reset() {
8596 boolean wlactive = false;
8597 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008598 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008599 }
8600 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008601 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008602 }
8603 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008604 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008605 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008606 if (mTimerDraw != null) {
8607 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008608 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008609 if (!wlactive) {
8610 if (mTimerFull != null) {
8611 mTimerFull.detach();
8612 mTimerFull = null;
8613 }
8614 if (mTimerPartial != null) {
8615 mTimerPartial.detach();
8616 mTimerPartial = null;
8617 }
8618 if (mTimerWindow != null) {
8619 mTimerWindow.detach();
8620 mTimerWindow = null;
8621 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008622 if (mTimerDraw != null) {
8623 mTimerDraw.detach();
8624 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008625 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008626 }
8627 return !wlactive;
8628 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008629
Bookatz5b5ec322017-05-26 09:40:38 -07008630 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
8631 TimeBase screenOffBgTimeBase, Parcel in) {
8632 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
8633 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008634 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
8635 mBsi.mFullTimers, timeBase, in);
8636 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
8637 mBsi.mWindowTimers, timeBase, in);
8638 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
8639 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 }
8641
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008642 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
8643 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
8644 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
8645 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008646 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008647 }
8648
8649 @Override
8650 public Timer getWakeTime(int type) {
8651 switch (type) {
8652 case WAKE_TYPE_FULL: return mTimerFull;
8653 case WAKE_TYPE_PARTIAL: return mTimerPartial;
8654 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008655 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 default: throw new IllegalArgumentException("type = " + type);
8657 }
8658 }
8659 }
8660
Joe Onoratoabded112016-02-08 16:49:39 -08008661 public static class Sensor extends BatteryStats.Uid.Sensor {
8662 /**
8663 * BatteryStatsImpl that we are associated with.
8664 */
8665 protected BatteryStatsImpl mBsi;
8666
8667 /**
Bookatz867c0d72017-03-07 18:23:42 -08008668 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08008669 */
8670 protected Uid mUid;
8671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008672 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08008673 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008674
Joe Onoratoabded112016-02-08 16:49:39 -08008675 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
8676 mBsi = bsi;
8677 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 mHandle = handle;
8679 }
8680
Bookatz867c0d72017-03-07 18:23:42 -08008681 private DualTimer readTimersFromParcel(
8682 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008683 if (in.readInt() == 0) {
8684 return null;
8685 }
8686
Joe Onoratoabded112016-02-08 16:49:39 -08008687 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07008689 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08008690 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008691 }
Bookatz867c0d72017-03-07 18:23:42 -08008692 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008693 }
8694
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008695 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008696 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008697 mTimer = null;
8698 return true;
8699 }
8700 return false;
8701 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008702
Bookatz867c0d72017-03-07 18:23:42 -08008703 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
8704 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008705 }
8706
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008707 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07008708 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 }
8710
8711 @Override
8712 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07008713 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008715
8716 @Override
Bookatz867c0d72017-03-07 18:23:42 -08008717 public Timer getSensorBackgroundTime() {
8718 if (mTimer == null) {
8719 return null;
8720 }
8721 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008722 }
8723
8724 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008725 public int getHandle() {
8726 return mHandle;
8727 }
8728 }
8729
8730 /**
8731 * The statistics associated with a particular process.
8732 */
Joe Onoratoabded112016-02-08 16:49:39 -08008733 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
8734 /**
8735 * BatteryStatsImpl that we are associated with.
8736 */
8737 protected BatteryStatsImpl mBsi;
8738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008740 * The name of this process.
8741 */
8742 final String mName;
8743
8744 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08008745 * Remains true until removed from the stats.
8746 */
8747 boolean mActive = true;
8748
8749 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008750 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008751 */
8752 long mUserTime;
8753
8754 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008755 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008756 */
8757 long mSystemTime;
8758
8759 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008760 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008761 */
8762 long mForegroundTime;
8763
8764 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008765 * Number of times the process has been started.
8766 */
8767 int mStarts;
8768
8769 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008770 * Number of times the process has crashed.
8771 */
8772 int mNumCrashes;
8773
8774 /**
8775 * Number of times the process has had an ANR.
8776 */
8777 int mNumAnrs;
8778
8779 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008780 * The amount of user time loaded from a previous save.
8781 */
8782 long mLoadedUserTime;
8783
8784 /**
8785 * The amount of system time loaded from a previous save.
8786 */
8787 long mLoadedSystemTime;
8788
8789 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008790 * The amount of foreground time loaded from a previous save.
8791 */
8792 long mLoadedForegroundTime;
8793
8794 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008795 * The number of times the process has started from a previous save.
8796 */
8797 int mLoadedStarts;
8798
8799 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008800 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008801 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008802 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008803
8804 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008805 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008806 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008807 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008808
8809 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008810 * The amount of user time when last unplugged.
8811 */
8812 long mUnpluggedUserTime;
8813
8814 /**
8815 * The amount of system time when last unplugged.
8816 */
8817 long mUnpluggedSystemTime;
8818
8819 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008820 * The amount of foreground time since unplugged.
8821 */
8822 long mUnpluggedForegroundTime;
8823
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008824 /**
8825 * The number of times the process has started before unplugged.
8826 */
8827 int mUnpluggedStarts;
8828
Dianne Hackborn61659e52014-07-09 16:13:01 -07008829 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008830 * Number of times the process has crashed before unplugged.
8831 */
8832 int mUnpluggedNumCrashes;
8833
8834 /**
8835 * Number of times the process has had an ANR before unplugged.
8836 */
8837 int mUnpluggedNumAnrs;
8838
Dianne Hackborn287952c2010-09-22 22:34:31 -07008839 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008840
Joe Onoratoabded112016-02-08 16:49:39 -08008841 public Proc(BatteryStatsImpl bsi, String name) {
8842 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008843 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08008844 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07008846
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008847 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008848 mUnpluggedUserTime = mUserTime;
8849 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008850 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008851 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008852 mUnpluggedNumCrashes = mNumCrashes;
8853 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008854 }
8855
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008856 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008857 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008858
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008859 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08008860 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08008861 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008862 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008863
Dianne Hackborn287952c2010-09-22 22:34:31 -07008864 public int countExcessivePowers() {
8865 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008866 }
8867
Dianne Hackborn287952c2010-09-22 22:34:31 -07008868 public ExcessivePower getExcessivePower(int i) {
8869 if (mExcessivePower != null) {
8870 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008871 }
8872 return null;
8873 }
8874
Dianne Hackborn287952c2010-09-22 22:34:31 -07008875 public void addExcessiveCpu(long overTime, long usedTime) {
8876 if (mExcessivePower == null) {
8877 mExcessivePower = new ArrayList<ExcessivePower>();
8878 }
8879 ExcessivePower ew = new ExcessivePower();
8880 ew.type = ExcessivePower.TYPE_CPU;
8881 ew.overTime = overTime;
8882 ew.usedTime = usedTime;
8883 mExcessivePower.add(ew);
8884 }
8885
8886 void writeExcessivePowerToParcelLocked(Parcel out) {
8887 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008888 out.writeInt(0);
8889 return;
8890 }
8891
Dianne Hackborn287952c2010-09-22 22:34:31 -07008892 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008893 out.writeInt(N);
8894 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008895 ExcessivePower ew = mExcessivePower.get(i);
8896 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008897 out.writeLong(ew.overTime);
8898 out.writeLong(ew.usedTime);
8899 }
8900 }
8901
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07008902 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008903 final int N = in.readInt();
8904 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008905 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07008906 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008907 }
8908
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08008909 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07008910 throw new ParcelFormatException(
8911 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08008912 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07008913
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07008914 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008915 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008916 ExcessivePower ew = new ExcessivePower();
8917 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008918 ew.overTime = in.readLong();
8919 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008920 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008921 }
8922 }
8923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008924 void writeToParcelLocked(Parcel out) {
8925 out.writeLong(mUserTime);
8926 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008927 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008929 out.writeInt(mNumCrashes);
8930 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008931 out.writeLong(mLoadedUserTime);
8932 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008933 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008935 out.writeInt(mLoadedNumCrashes);
8936 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008937 out.writeLong(mUnpluggedUserTime);
8938 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008939 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008940 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008941 out.writeInt(mUnpluggedNumCrashes);
8942 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008943 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 }
8945
8946 void readFromParcelLocked(Parcel in) {
8947 mUserTime = in.readLong();
8948 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008949 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008950 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008951 mNumCrashes = in.readInt();
8952 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008953 mLoadedUserTime = in.readLong();
8954 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008955 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008956 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008957 mLoadedNumCrashes = in.readInt();
8958 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008959 mUnpluggedUserTime = in.readLong();
8960 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008961 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008962 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008963 mUnpluggedNumCrashes = in.readInt();
8964 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008965 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008966 }
8967
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008968 public void addCpuTimeLocked(int utime, int stime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008969 mUserTime += utime;
8970 mSystemTime += stime;
8971 }
8972
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008973 public void addForegroundTimeLocked(long ttime) {
8974 mForegroundTime += ttime;
8975 }
8976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008977 public void incStartsLocked() {
8978 mStarts++;
8979 }
8980
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008981 public void incNumCrashesLocked() {
8982 mNumCrashes++;
8983 }
8984
8985 public void incNumAnrsLocked() {
8986 mNumAnrs++;
8987 }
8988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08008990 public boolean isActive() {
8991 return mActive;
8992 }
8993
8994 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008995 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008996 long val = mUserTime;
8997 if (which == STATS_CURRENT) {
8998 val -= mLoadedUserTime;
8999 } else if (which == STATS_SINCE_UNPLUGGED) {
9000 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001 }
9002 return val;
9003 }
9004
9005 @Override
9006 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009007 long val = mSystemTime;
9008 if (which == STATS_CURRENT) {
9009 val -= mLoadedSystemTime;
9010 } else if (which == STATS_SINCE_UNPLUGGED) {
9011 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009012 }
9013 return val;
9014 }
9015
9016 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009017 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009018 long val = mForegroundTime;
9019 if (which == STATS_CURRENT) {
9020 val -= mLoadedForegroundTime;
9021 } else if (which == STATS_SINCE_UNPLUGGED) {
9022 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009023 }
9024 return val;
9025 }
9026
9027 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009029 int val = mStarts;
9030 if (which == STATS_CURRENT) {
9031 val -= mLoadedStarts;
9032 } else if (which == STATS_SINCE_UNPLUGGED) {
9033 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009034 }
9035 return val;
9036 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009037
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009038 @Override
9039 public int getNumCrashes(int which) {
9040 int val = mNumCrashes;
9041 if (which == STATS_CURRENT) {
9042 val -= mLoadedNumCrashes;
9043 } else if (which == STATS_SINCE_UNPLUGGED) {
9044 val -= mUnpluggedNumCrashes;
9045 }
9046 return val;
9047 }
9048
9049 @Override
9050 public int getNumAnrs(int which) {
9051 int val = mNumAnrs;
9052 if (which == STATS_CURRENT) {
9053 val -= mLoadedNumAnrs;
9054 } else if (which == STATS_SINCE_UNPLUGGED) {
9055 val -= mUnpluggedNumAnrs;
9056 }
9057 return val;
9058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009059 }
9060
9061 /**
9062 * The statistics associated with a particular package.
9063 */
Joe Onoratoabded112016-02-08 16:49:39 -08009064 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9065 /**
9066 * BatteryStatsImpl that we are associated with.
9067 */
9068 protected BatteryStatsImpl mBsi;
9069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009070 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009071 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009072 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009073 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009074 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009075
9076 /**
9077 * The statics we have collected for this package's services.
9078 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009079 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009080
Joe Onoratoabded112016-02-08 16:49:39 -08009081 public Pkg(BatteryStatsImpl bsi) {
9082 mBsi = bsi;
9083 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009085
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009086 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009087 }
9088
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009089 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009090 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009091
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009092 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009093 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009094 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009097 int numWA = in.readInt();
9098 mWakeupAlarms.clear();
9099 for (int i=0; i<numWA; i++) {
9100 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009101 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009103
9104 int numServs = in.readInt();
9105 mServiceStats.clear();
9106 for (int m = 0; m < numServs; m++) {
9107 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009108 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 mServiceStats.put(serviceName, serv);
9110
9111 serv.readFromParcelLocked(in);
9112 }
9113 }
9114
9115 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009116 int numWA = mWakeupAlarms.size();
9117 out.writeInt(numWA);
9118 for (int i=0; i<numWA; i++) {
9119 out.writeString(mWakeupAlarms.keyAt(i));
9120 mWakeupAlarms.valueAt(i).writeToParcel(out);
9121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009122
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009123 final int NS = mServiceStats.size();
9124 out.writeInt(NS);
9125 for (int i=0; i<NS; i++) {
9126 out.writeString(mServiceStats.keyAt(i));
9127 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009128 serv.writeToParcelLocked(out);
9129 }
9130 }
9131
9132 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009133 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9134 return mWakeupAlarms;
9135 }
9136
9137 public void noteWakeupAlarmLocked(String tag) {
9138 Counter c = mWakeupAlarms.get(tag);
9139 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009140 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009141 mWakeupAlarms.put(tag, c);
9142 }
9143 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009144 }
9145
9146 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009147 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9148 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 }
9150
9151 /**
9152 * The statistics associated with a particular service.
9153 */
Joe Onoratoabded112016-02-08 16:49:39 -08009154 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9155 /**
9156 * BatteryStatsImpl that we are associated with.
9157 */
9158 protected BatteryStatsImpl mBsi;
9159
9160 /**
9161 * The android package in which this service resides.
9162 */
9163 protected Pkg mPkg;
9164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009165 /**
9166 * Total time (ms in battery uptime) the service has been left started.
9167 */
Joe Onoratoabded112016-02-08 16:49:39 -08009168 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169
9170 /**
9171 * If service has been started and not yet stopped, this is
9172 * when it was started.
9173 */
Joe Onoratoabded112016-02-08 16:49:39 -08009174 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009175
9176 /**
9177 * True if we are currently running.
9178 */
Joe Onoratoabded112016-02-08 16:49:39 -08009179 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009180
9181 /**
9182 * Total number of times startService() has been called.
9183 */
Joe Onoratoabded112016-02-08 16:49:39 -08009184 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009185
9186 /**
9187 * Total time (ms in battery uptime) the service has been left launched.
9188 */
Joe Onoratoabded112016-02-08 16:49:39 -08009189 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009190
9191 /**
9192 * If service has been launched and not yet exited, this is
9193 * when it was launched (ms in battery uptime).
9194 */
Joe Onoratoabded112016-02-08 16:49:39 -08009195 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009196
9197 /**
9198 * True if we are currently launched.
9199 */
Joe Onoratoabded112016-02-08 16:49:39 -08009200 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009201
9202 /**
9203 * Total number times the service has been launched.
9204 */
Joe Onoratoabded112016-02-08 16:49:39 -08009205 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009206
9207 /**
9208 * The amount of time spent started loaded from a previous save
9209 * (ms in battery uptime).
9210 */
Joe Onoratoabded112016-02-08 16:49:39 -08009211 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009212
9213 /**
9214 * The number of starts loaded from a previous save.
9215 */
Joe Onoratoabded112016-02-08 16:49:39 -08009216 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009217
9218 /**
9219 * The number of launches loaded from a previous save.
9220 */
Joe Onoratoabded112016-02-08 16:49:39 -08009221 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009222
9223 /**
9224 * The amount of time spent started as of the last run (ms
9225 * in battery uptime).
9226 */
Joe Onoratoabded112016-02-08 16:49:39 -08009227 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009228
9229 /**
9230 * The number of starts as of the last run.
9231 */
Joe Onoratoabded112016-02-08 16:49:39 -08009232 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009233
9234 /**
9235 * The number of launches as of the last run.
9236 */
Joe Onoratoabded112016-02-08 16:49:39 -08009237 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009238
9239 /**
9240 * The amount of time spent started when last unplugged (ms
9241 * in battery uptime).
9242 */
Joe Onoratoabded112016-02-08 16:49:39 -08009243 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009244
9245 /**
9246 * The number of starts when last unplugged.
9247 */
Joe Onoratoabded112016-02-08 16:49:39 -08009248 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009249
9250 /**
9251 * The number of launches when last unplugged.
9252 */
Joe Onoratoabded112016-02-08 16:49:39 -08009253 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009254
Joe Onoratoabded112016-02-08 16:49:39 -08009255 /**
9256 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9257 */
9258 public Serv(BatteryStatsImpl bsi) {
9259 mBsi = bsi;
9260 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009261 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009262
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009263 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9264 long baseRealtime) {
9265 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266 mUnpluggedStarts = mStarts;
9267 mUnpluggedLaunches = mLaunches;
9268 }
9269
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009270 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9271 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009272 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009273
Joe Onoratoabded112016-02-08 16:49:39 -08009274 /**
9275 * Remove this Serv as a listener from the time base.
9276 */
9277 public void detach() {
9278 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009279 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009280
Joe Onoratoabded112016-02-08 16:49:39 -08009281 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009282 mStartTime = in.readLong();
9283 mRunningSince = in.readLong();
9284 mRunning = in.readInt() != 0;
9285 mStarts = in.readInt();
9286 mLaunchedTime = in.readLong();
9287 mLaunchedSince = in.readLong();
9288 mLaunched = in.readInt() != 0;
9289 mLaunches = in.readInt();
9290 mLoadedStartTime = in.readLong();
9291 mLoadedStarts = in.readInt();
9292 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009293 mLastStartTime = 0;
9294 mLastStarts = 0;
9295 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009296 mUnpluggedStartTime = in.readLong();
9297 mUnpluggedStarts = in.readInt();
9298 mUnpluggedLaunches = in.readInt();
9299 }
9300
Joe Onoratoabded112016-02-08 16:49:39 -08009301 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009302 out.writeLong(mStartTime);
9303 out.writeLong(mRunningSince);
9304 out.writeInt(mRunning ? 1 : 0);
9305 out.writeInt(mStarts);
9306 out.writeLong(mLaunchedTime);
9307 out.writeLong(mLaunchedSince);
9308 out.writeInt(mLaunched ? 1 : 0);
9309 out.writeInt(mLaunches);
9310 out.writeLong(mLoadedStartTime);
9311 out.writeInt(mLoadedStarts);
9312 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009313 out.writeLong(mUnpluggedStartTime);
9314 out.writeInt(mUnpluggedStarts);
9315 out.writeInt(mUnpluggedLaunches);
9316 }
9317
Joe Onoratoabded112016-02-08 16:49:39 -08009318 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009319 if (!mLaunched) return mLaunchedTime;
9320 return mLaunchedTime + batteryUptime - mLaunchedSince;
9321 }
9322
Joe Onoratoabded112016-02-08 16:49:39 -08009323 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009324 if (!mRunning) return mStartTime;
9325 return mStartTime + batteryUptime - mRunningSince;
9326 }
9327
9328 public void startLaunchedLocked() {
9329 if (!mLaunched) {
9330 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009331 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009332 mLaunched = true;
9333 }
9334 }
9335
9336 public void stopLaunchedLocked() {
9337 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009338 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009339 if (time > 0) {
9340 mLaunchedTime += time;
9341 } else {
9342 mLaunches--;
9343 }
9344 mLaunched = false;
9345 }
9346 }
9347
9348 public void startRunningLocked() {
9349 if (!mRunning) {
9350 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009351 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 mRunning = true;
9353 }
9354 }
9355
9356 public void stopRunningLocked() {
9357 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009358 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009359 if (time > 0) {
9360 mStartTime += time;
9361 } else {
9362 mStarts--;
9363 }
9364 mRunning = false;
9365 }
9366 }
9367
9368 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009369 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009370 }
9371
9372 @Override
9373 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009374 int val = mLaunches;
9375 if (which == STATS_CURRENT) {
9376 val -= mLoadedLaunches;
9377 } else if (which == STATS_SINCE_UNPLUGGED) {
9378 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009380 return val;
9381 }
9382
9383 @Override
9384 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009385 long val = getStartTimeToNowLocked(now);
9386 if (which == STATS_CURRENT) {
9387 val -= mLoadedStartTime;
9388 } else if (which == STATS_SINCE_UNPLUGGED) {
9389 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009391 return val;
9392 }
9393
9394 @Override
9395 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009396 int val = mStarts;
9397 if (which == STATS_CURRENT) {
9398 val -= mLoadedStarts;
9399 } else if (which == STATS_SINCE_UNPLUGGED) {
9400 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 }
9402
9403 return val;
9404 }
9405 }
9406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009407 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009408 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009409 }
9410 }
9411
9412 /**
9413 * Retrieve the statistics object for a particular process, creating
9414 * if needed.
9415 */
9416 public Proc getProcessStatsLocked(String name) {
9417 Proc ps = mProcessStats.get(name);
9418 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009419 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009420 mProcessStats.put(name, ps);
9421 }
9422
9423 return ps;
9424 }
9425
Dianne Hackborna8d10942015-11-19 17:55:19 -08009426 public void updateUidProcessStateLocked(int procState) {
9427 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009428 // Make special note of Foreground Services
9429 final boolean userAwareService =
9430 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009431 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009432
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009433 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9434 return;
9435 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009436
Bookatz867c0d72017-03-07 18:23:42 -08009437 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009438 if (mProcessState != uidRunningState) {
9439 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009440
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009441 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9442 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009443
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009444 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009445 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009446 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9447 mBsi.mOnBatteryTimeBase.isRunning(),
9448 mBsi.mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009449 }
9450 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9451 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9452 mBsi.mPendingUids.put(mUid, mProcessState);
9453 }
9454 } else {
9455 mBsi.mPendingUids.clear();
9456 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009457 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009458 mProcessState = uidRunningState;
9459 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9460 if (mProcessStateTimer[uidRunningState] == null) {
9461 makeProcessState(uidRunningState, null);
9462 }
9463 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9464 }
9465
9466 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9467 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009468 }
Bookatz867c0d72017-03-07 18:23:42 -08009469
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009470 if (userAwareService != mInForegroundService) {
9471 if (userAwareService) {
9472 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9473 } else {
9474 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9475 }
9476 mInForegroundService = userAwareService;
9477 }
Bookatz867c0d72017-03-07 18:23:42 -08009478 }
9479
Bookatzc8c44962017-05-11 12:12:54 -07009480 /** Whether to consider Uid to be in the background for background timebase purposes. */
9481 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009482 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9483 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009484 return mProcessState >= PROCESS_STATE_BACKGROUND;
9485 }
9486
9487 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9488 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9489 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9490 }
9491
9492 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9493 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9494 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009495 }
9496
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009497 public SparseArray<? extends Pid> getPidStats() {
9498 return mPids;
9499 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009500
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009501 public Pid getPidStatsLocked(int pid) {
9502 Pid p = mPids.get(pid);
9503 if (p == null) {
9504 p = new Pid();
9505 mPids.put(pid, p);
9506 }
9507 return p;
9508 }
9509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009510 /**
9511 * Retrieve the statistics object for a particular service, creating
9512 * if needed.
9513 */
9514 public Pkg getPackageStatsLocked(String name) {
9515 Pkg ps = mPackageStats.get(name);
9516 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009517 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009518 mPackageStats.put(name, ps);
9519 }
9520
9521 return ps;
9522 }
9523
9524 /**
9525 * Retrieve the statistics object for a particular service, creating
9526 * if needed.
9527 */
9528 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9529 Pkg ps = getPackageStatsLocked(pkg);
9530 Pkg.Serv ss = ps.mServiceStats.get(serv);
9531 if (ss == null) {
9532 ss = ps.newServiceStatsLocked();
9533 ps.mServiceStats.put(serv, ss);
9534 }
9535
9536 return ss;
9537 }
9538
Dianne Hackbornd953c532014-08-16 18:17:38 -07009539 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009540 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009541 timer.readSummaryFromParcelLocked(in);
9542 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009543 }
9544
Dianne Hackbornd953c532014-08-16 18:17:38 -07009545 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009546 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009547 timer.readSummaryFromParcelLocked(in);
9548 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009549 }
9550
Dianne Hackbornd953c532014-08-16 18:17:38 -07009551 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009552 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009553 mWakelockStats.add(wlName, wl);
9554 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009555 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009556 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009557 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009558 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009559 }
9560 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009561 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009562 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009563 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009564 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009566 }
9567
Bookatz867c0d72017-03-07 18:23:42 -08009568 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569 Sensor se = mSensorStats.get(sensor);
9570 if (se == null) {
9571 if (!create) {
9572 return null;
9573 }
Joe Onoratoabded112016-02-08 16:49:39 -08009574 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009575 mSensorStats.put(sensor, se);
9576 }
Bookatz867c0d72017-03-07 18:23:42 -08009577 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009578 if (t != null) {
9579 return t;
9580 }
Joe Onoratoabded112016-02-08 16:49:39 -08009581 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009582 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009583 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009584 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009585 }
Bookatz867c0d72017-03-07 18:23:42 -08009586 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9587 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009588 se.mTimer = t;
9589 return t;
9590 }
9591
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009592 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009593 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009594 if (t != null) {
9595 t.startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009596 // TODO(statsd): Possibly use a worksource instead of a uid.
9597 StatsLog.write(StatsLog.SYNC_STATE_CHANGED, getUid(), name, 1);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009598 }
9599 }
9600
9601 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009602 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009603 if (t != null) {
9604 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009605 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
9606 // TODO(statsd): Possibly use a worksource instead of a uid.
9607 StatsLog.write(StatsLog.SYNC_STATE_CHANGED, getUid(), name, 0);
9608 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009609 }
9610 }
9611
9612 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009613 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009614 if (t != null) {
9615 t.startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009616 // TODO(statsd): Possibly use a worksource instead of a uid.
9617 StatsLog.write(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), name, 1);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009618 }
9619 }
9620
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009621 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07009622 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009623 if (t != null) {
9624 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009625 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
9626 // TODO(statsd): Possibly use a worksource instead of a uid.
9627 StatsLog.write(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), name, 0);
9628 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009629 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009630 if (mBsi.mOnBatteryTimeBase.isRunning()) {
9631 SparseIntArray types = mJobCompletions.get(name);
9632 if (types == null) {
9633 types = new SparseIntArray();
9634 mJobCompletions.put(name, types);
9635 }
9636 int last = types.get(stopReason, 0);
9637 types.put(stopReason, last + 1);
9638 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009639 }
9640
Bookatz5b5ec322017-05-26 09:40:38 -07009641 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
9642 if (wl == null) {
9643 return null;
9644 }
9645 switch (type) {
9646 case WAKE_TYPE_PARTIAL: {
9647 DualTimer t = wl.mTimerPartial;
9648 if (t == null) {
9649 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
9650 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
9651 mOnBatteryScreenOffBackgroundTimeBase);
9652 wl.mTimerPartial = t;
9653 }
9654 return t;
9655 }
9656 case WAKE_TYPE_FULL: {
9657 StopwatchTimer t = wl.mTimerFull;
9658 if (t == null) {
9659 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
9660 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
9661 wl.mTimerFull = t;
9662 }
9663 return t;
9664 }
9665 case WAKE_TYPE_WINDOW: {
9666 StopwatchTimer t = wl.mTimerWindow;
9667 if (t == null) {
9668 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
9669 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
9670 wl.mTimerWindow = t;
9671 }
9672 return t;
9673 }
9674 case WAKE_TYPE_DRAW: {
9675 StopwatchTimer t = wl.mTimerDraw;
9676 if (t == null) {
9677 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
9678 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
9679 wl.mTimerDraw = t;
9680 }
9681 return t;
9682 }
9683 default:
9684 throw new IllegalArgumentException("type=" + type);
9685 }
9686 }
9687
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009688 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009689 Wakelock wl = mWakelockStats.startObject(name);
9690 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07009691 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009692 }
Bookatzc8c44962017-05-11 12:12:54 -07009693 if (type == WAKE_TYPE_PARTIAL) {
9694 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
9695 if (pid >= 0) {
9696 Pid p = getPidStatsLocked(pid);
9697 if (p.mWakeNesting++ == 0) {
9698 p.mWakeStartMs = elapsedRealtimeMs;
9699 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -07009700 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009702 }
9703
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009704 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009705 Wakelock wl = mWakelockStats.stopObject(name);
9706 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -07009707 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
9708 wlt.stopRunningLocked(elapsedRealtimeMs);
9709 if (!wlt.isRunningLocked()) { // only tell statsd if truly stopped
Bookatzd6746242017-10-24 18:39:35 -07009710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009711 }
Bookatzc8c44962017-05-11 12:12:54 -07009712 if (type == WAKE_TYPE_PARTIAL) {
9713 if (mAggregatedPartialWakelockTimer != null) {
9714 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
9715 }
9716 if (pid >= 0) {
9717 Pid p = mPids.get(pid);
9718 if (p != null && p.mWakeNesting > 0) {
9719 if (p.mWakeNesting-- == 1) {
9720 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
9721 p.mWakeStartMs = 0;
9722 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08009723 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009724 }
9725 }
9726 }
9727
Dianne Hackborn287952c2010-09-22 22:34:31 -07009728 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
9729 Proc p = getProcessStatsLocked(proc);
9730 if (p != null) {
9731 p.addExcessiveCpu(overTime, usedTime);
9732 }
9733 }
9734
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009735 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009736 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -08009737 t.startRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009738 // TODO(statsd): Possibly use a worksource instead of a uid.
9739 if (sensor == Sensor.GPS) {
9740 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, getUid(), 1);
9741 } else {
9742 StatsLog.write(StatsLog.SENSOR_STATE_CHANGED, getUid(), sensor, 1);
9743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009744 }
9745
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009746 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009747 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -08009748 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009749 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009750 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009751 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
9752 // TODO(statsd): Possibly use a worksource instead of a uid.
9753 if (sensor == Sensor.GPS) {
9754 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, getUid(), 0);
9755 } else {
9756 StatsLog.write(StatsLog.SENSOR_STATE_CHANGED, getUid(), sensor, 0);
9757 }
9758 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009760 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009761
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009762 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009763 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009764 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009765
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009766 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009767 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009768 }
9769
9770 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009771 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009772 }
9773 }
9774
Sudheer Shanka9b735c52017-05-09 18:26:18 -07009775 public long[] getCpuFreqs() {
9776 return mCpuFreqs;
9777 }
9778
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009779 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
9780 UserInfoProvider userInfoProvider) {
9781 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009782 }
9783
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009784 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
9785 PlatformIdleStateCallback cb,
9786 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -08009787 init(clocks);
9788
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009789 if (systemDir != null) {
9790 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
9791 new File(systemDir, "batterystats.bin.tmp"));
9792 } else {
9793 mFile = null;
9794 }
9795 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009796 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -08009797 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009798 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009799 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -08009800 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -07009801 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07009802 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009803 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009804 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009805 }
Joe Onoratoabded112016-02-08 16:49:39 -08009806 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
9807 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
9808 mOnBatteryTimeBase);
9809 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
9810 mOnBatteryTimeBase);
9811 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
9812 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
9813 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
9814 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
9815 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
9816 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
9817 mOnBatteryTimeBase);
9818 }
9819 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
9820 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009821 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009822 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009823 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009824 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009825 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009826 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
9827 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009828 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009829 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
9830 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
9831 NUM_BT_TX_LEVELS);
9832 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
9833 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -08009834 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
9835 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
9836 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009837 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009838 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
9839 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08009840 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
9841 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08009842 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
9843 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08009844 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009845 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -07009846 mOnBatteryTimeBase);
9847 }
Joe Onoratoabded112016-02-08 16:49:39 -08009848 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9849 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
9850 mOnBatteryTimeBase);
9851 }
9852 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9853 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
9854 mOnBatteryTimeBase);
9855 }
9856 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
9857 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
9858 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
9859 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
9860 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009861 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -07009862 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -08009863 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
9864 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009865 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009866 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009867 long uptime = mClocks.uptimeMillis() * 1000;
9868 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009869 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -07009870 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -07009871 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009872 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009873 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -07009874 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009875 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009876 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009877 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009878 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009879 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009880 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009881 }
9882
9883 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -08009884 this(new SystemClocks(), p);
9885 }
9886
9887 public BatteryStatsImpl(Clocks clocks, Parcel p) {
9888 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07009889 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009890 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009891 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07009892 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009893 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009894 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009895 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009896 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009897 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009898 }
9899
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009900 public void setPowerProfileLocked(PowerProfile profile) {
9901 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -07009902
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009903 // We need to initialize the KernelCpuSpeedReaders to read from
9904 // the first cpu of each core. Once we have the PowerProfile, we have access to this
9905 // information.
9906 final int numClusters = mPowerProfile.getNumCpuClusters();
9907 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
9908 int firstCpuOfCluster = 0;
9909 for (int i = 0; i < numClusters; i++) {
9910 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
9911 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
9912 numSpeedSteps);
9913 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
9914 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -07009915
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009916 if (mEstimatedBatteryCapacity == -1) {
9917 // Initialize the estimated battery capacity to a known preset one.
9918 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -07009919 }
9920 }
9921
Dianne Hackborn0d903a82010-09-07 23:51:03 -07009922 public void setCallback(BatteryCallback cb) {
9923 mCallback = cb;
9924 }
9925
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009926 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07009927 if (mPhoneSignalScanningTimer != null) {
9928 mPhoneSignalScanningTimer.setTimeout(timeout);
9929 }
9930 }
9931
Adam Lesinskib3a1bad2017-05-26 11:50:40 -07009932 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
9933 mExternalSync = sync;
9934 }
9935
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009936 public void updateDailyDeadlineLocked() {
9937 // Get the current time.
9938 long currentTime = mDailyStartTime = System.currentTimeMillis();
9939 Calendar calDeadline = Calendar.getInstance();
9940 calDeadline.setTimeInMillis(currentTime);
9941
9942 // Move time up to the next day, ranging from 1am to 3pm.
9943 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
9944 calDeadline.set(Calendar.MILLISECOND, 0);
9945 calDeadline.set(Calendar.SECOND, 0);
9946 calDeadline.set(Calendar.MINUTE, 0);
9947 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
9948 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
9949 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
9950 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
9951 }
9952
9953 public void recordDailyStatsIfNeededLocked(boolean settled) {
9954 long currentTime = System.currentTimeMillis();
9955 if (currentTime >= mNextMaxDailyDeadline) {
9956 recordDailyStatsLocked();
9957 } else if (settled && currentTime >= mNextMinDailyDeadline) {
9958 recordDailyStatsLocked();
9959 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
9960 recordDailyStatsLocked();
9961 }
9962 }
9963
9964 public void recordDailyStatsLocked() {
9965 DailyItem item = new DailyItem();
9966 item.mStartTime = mDailyStartTime;
9967 item.mEndTime = System.currentTimeMillis();
9968 boolean hasData = false;
9969 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
9970 hasData = true;
9971 item.mDischargeSteps = new LevelStepTracker(
9972 mDailyDischargeStepTracker.mNumStepDurations,
9973 mDailyDischargeStepTracker.mStepDurations);
9974 }
9975 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
9976 hasData = true;
9977 item.mChargeSteps = new LevelStepTracker(
9978 mDailyChargeStepTracker.mNumStepDurations,
9979 mDailyChargeStepTracker.mStepDurations);
9980 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07009981 if (mDailyPackageChanges != null) {
9982 hasData = true;
9983 item.mPackageChanges = mDailyPackageChanges;
9984 mDailyPackageChanges = null;
9985 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009986 mDailyDischargeStepTracker.init();
9987 mDailyChargeStepTracker.init();
9988 updateDailyDeadlineLocked();
9989
9990 if (hasData) {
9991 mDailyItems.add(item);
9992 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
9993 mDailyItems.remove(0);
9994 }
9995 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
9996 try {
9997 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01009998 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009999 writeDailyItemsLocked(out);
10000 BackgroundThread.getHandler().post(new Runnable() {
10001 @Override
10002 public void run() {
10003 synchronized (mCheckinFile) {
10004 FileOutputStream stream = null;
10005 try {
10006 stream = mDailyFile.startWrite();
10007 memStream.writeTo(stream);
10008 stream.flush();
10009 FileUtils.sync(stream);
10010 stream.close();
10011 mDailyFile.finishWrite(stream);
10012 } catch (IOException e) {
10013 Slog.w("BatteryStats",
10014 "Error writing battery daily items", e);
10015 mDailyFile.failWrite(stream);
10016 }
10017 }
10018 }
10019 });
10020 } catch (IOException e) {
10021 }
10022 }
10023 }
10024
10025 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10026 StringBuilder sb = new StringBuilder(64);
10027 out.startDocument(null, true);
10028 out.startTag(null, "daily-items");
10029 for (int i=0; i<mDailyItems.size(); i++) {
10030 final DailyItem dit = mDailyItems.get(i);
10031 out.startTag(null, "item");
10032 out.attribute(null, "start", Long.toString(dit.mStartTime));
10033 out.attribute(null, "end", Long.toString(dit.mEndTime));
10034 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10035 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010036 if (dit.mPackageChanges != null) {
10037 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10038 PackageChange pc = dit.mPackageChanges.get(j);
10039 if (pc.mUpdate) {
10040 out.startTag(null, "upd");
10041 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010042 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010043 out.endTag(null, "upd");
10044 } else {
10045 out.startTag(null, "rem");
10046 out.attribute(null, "pkg", pc.mPackageName);
10047 out.endTag(null, "rem");
10048 }
10049 }
10050 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010051 out.endTag(null, "item");
10052 }
10053 out.endTag(null, "daily-items");
10054 out.endDocument();
10055 }
10056
10057 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10058 StringBuilder tmpBuilder) throws IOException {
10059 if (steps != null) {
10060 out.startTag(null, tag);
10061 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10062 for (int i=0; i<steps.mNumStepDurations; i++) {
10063 out.startTag(null, "s");
10064 tmpBuilder.setLength(0);
10065 steps.encodeEntryAt(i, tmpBuilder);
10066 out.attribute(null, "v", tmpBuilder.toString());
10067 out.endTag(null, "s");
10068 }
10069 out.endTag(null, tag);
10070 }
10071 }
10072
10073 public void readDailyStatsLocked() {
10074 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10075 mDailyItems.clear();
10076 FileInputStream stream;
10077 try {
10078 stream = mDailyFile.openRead();
10079 } catch (FileNotFoundException e) {
10080 return;
10081 }
10082 try {
10083 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010084 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010085 readDailyItemsLocked(parser);
10086 } catch (XmlPullParserException e) {
10087 } finally {
10088 try {
10089 stream.close();
10090 } catch (IOException e) {
10091 }
10092 }
10093 }
10094
10095 private void readDailyItemsLocked(XmlPullParser parser) {
10096 try {
10097 int type;
10098 while ((type = parser.next()) != XmlPullParser.START_TAG
10099 && type != XmlPullParser.END_DOCUMENT) {
10100 ;
10101 }
10102
10103 if (type != XmlPullParser.START_TAG) {
10104 throw new IllegalStateException("no start tag found");
10105 }
10106
10107 int outerDepth = parser.getDepth();
10108 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10109 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10110 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10111 continue;
10112 }
10113
10114 String tagName = parser.getName();
10115 if (tagName.equals("item")) {
10116 readDailyItemTagLocked(parser);
10117 } else {
10118 Slog.w(TAG, "Unknown element under <daily-items>: "
10119 + parser.getName());
10120 XmlUtils.skipCurrentTag(parser);
10121 }
10122 }
10123
10124 } catch (IllegalStateException e) {
10125 Slog.w(TAG, "Failed parsing daily " + e);
10126 } catch (NullPointerException e) {
10127 Slog.w(TAG, "Failed parsing daily " + e);
10128 } catch (NumberFormatException e) {
10129 Slog.w(TAG, "Failed parsing daily " + e);
10130 } catch (XmlPullParserException e) {
10131 Slog.w(TAG, "Failed parsing daily " + e);
10132 } catch (IOException e) {
10133 Slog.w(TAG, "Failed parsing daily " + e);
10134 } catch (IndexOutOfBoundsException e) {
10135 Slog.w(TAG, "Failed parsing daily " + e);
10136 }
10137 }
10138
10139 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10140 XmlPullParserException, IOException {
10141 DailyItem dit = new DailyItem();
10142 String attr = parser.getAttributeValue(null, "start");
10143 if (attr != null) {
10144 dit.mStartTime = Long.parseLong(attr);
10145 }
10146 attr = parser.getAttributeValue(null, "end");
10147 if (attr != null) {
10148 dit.mEndTime = Long.parseLong(attr);
10149 }
10150 int outerDepth = parser.getDepth();
10151 int type;
10152 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10153 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10154 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10155 continue;
10156 }
10157
10158 String tagName = parser.getName();
10159 if (tagName.equals("dis")) {
10160 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10161 } else if (tagName.equals("chg")) {
10162 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010163 } else if (tagName.equals("upd")) {
10164 if (dit.mPackageChanges == null) {
10165 dit.mPackageChanges = new ArrayList<>();
10166 }
10167 PackageChange pc = new PackageChange();
10168 pc.mUpdate = true;
10169 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10170 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010171 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010172 dit.mPackageChanges.add(pc);
10173 XmlUtils.skipCurrentTag(parser);
10174 } else if (tagName.equals("rem")) {
10175 if (dit.mPackageChanges == null) {
10176 dit.mPackageChanges = new ArrayList<>();
10177 }
10178 PackageChange pc = new PackageChange();
10179 pc.mUpdate = false;
10180 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10181 dit.mPackageChanges.add(pc);
10182 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010183 } else {
10184 Slog.w(TAG, "Unknown element under <item>: "
10185 + parser.getName());
10186 XmlUtils.skipCurrentTag(parser);
10187 }
10188 }
10189 mDailyItems.add(dit);
10190 }
10191
10192 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10193 String tag)
10194 throws NumberFormatException, XmlPullParserException, IOException {
10195 final String numAttr = parser.getAttributeValue(null, "n");
10196 if (numAttr == null) {
10197 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10198 XmlUtils.skipCurrentTag(parser);
10199 return;
10200 }
10201 final int num = Integer.parseInt(numAttr);
10202 LevelStepTracker steps = new LevelStepTracker(num);
10203 if (isCharge) {
10204 dit.mChargeSteps = steps;
10205 } else {
10206 dit.mDischargeSteps = steps;
10207 }
10208 int i = 0;
10209 int outerDepth = parser.getDepth();
10210 int type;
10211 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10212 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10213 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10214 continue;
10215 }
10216
10217 String tagName = parser.getName();
10218 if ("s".equals(tagName)) {
10219 if (i < num) {
10220 String valueAttr = parser.getAttributeValue(null, "v");
10221 if (valueAttr != null) {
10222 steps.decodeEntryAt(i, valueAttr);
10223 i++;
10224 }
10225 }
10226 } else {
10227 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10228 + parser.getName());
10229 XmlUtils.skipCurrentTag(parser);
10230 }
10231 }
10232 steps.mNumStepDurations = i;
10233 }
10234
10235 @Override
10236 public DailyItem getDailyItemLocked(int daysAgo) {
10237 int index = mDailyItems.size()-1-daysAgo;
10238 return index >= 0 ? mDailyItems.get(index) : null;
10239 }
10240
10241 @Override
10242 public long getCurrentDailyStartTime() {
10243 return mDailyStartTime;
10244 }
10245
10246 @Override
10247 public long getNextMinDailyDeadline() {
10248 return mNextMinDailyDeadline;
10249 }
10250
10251 @Override
10252 public long getNextMaxDailyDeadline() {
10253 return mNextMaxDailyDeadline;
10254 }
10255
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010256 @Override
10257 public boolean startIteratingOldHistoryLocked() {
10258 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10259 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010260 if ((mHistoryIterator = mHistory) == null) {
10261 return false;
10262 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010263 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010264 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010265 mReadOverflow = false;
10266 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010267 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010268 }
10269
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010270 @Override
10271 public boolean getNextOldHistoryLocked(HistoryItem out) {
10272 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10273 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010274 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010275 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010276 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010277 HistoryItem cur = mHistoryIterator;
10278 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010279 if (!mReadOverflow && !end) {
10280 Slog.w(TAG, "Old history ends before new history!");
10281 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010282 return false;
10283 }
10284 out.setTo(cur);
10285 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010286 if (!mReadOverflow) {
10287 if (end) {
10288 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010289 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010290 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010291 pw.println("Histories differ!");
10292 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010293 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010294 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010295 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10296 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010297 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010298 }
10299 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010300 return true;
10301 }
10302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010303 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010304 public void finishIteratingOldHistoryLocked() {
10305 mIteratingHistory = false;
10306 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010307 mHistoryIterator = null;
10308 }
10309
10310 public int getHistoryTotalSize() {
10311 return MAX_HISTORY_BUFFER;
10312 }
10313
10314 public int getHistoryUsedSize() {
10315 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010316 }
10317
10318 @Override
10319 public boolean startIteratingHistoryLocked() {
10320 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10321 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010322 if (mHistoryBuffer.dataSize() <= 0) {
10323 return false;
10324 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010325 mHistoryBuffer.setDataPosition(0);
10326 mReadOverflow = false;
10327 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010328 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10329 mReadHistoryUids = new int[mHistoryTagPool.size()];
10330 mReadHistoryChars = 0;
10331 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10332 final HistoryTag tag = ent.getKey();
10333 final int idx = ent.getValue();
10334 mReadHistoryStrings[idx] = tag.string;
10335 mReadHistoryUids[idx] = tag.uid;
10336 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010337 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010338 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010339 }
10340
10341 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010342 public int getHistoryStringPoolSize() {
10343 return mReadHistoryStrings.length;
10344 }
10345
10346 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010347 public int getHistoryStringPoolBytes() {
10348 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10349 // Each string character is 2 bytes.
10350 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10351 }
10352
10353 @Override
10354 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010355 return mReadHistoryStrings[index];
10356 }
10357
10358 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010359 public int getHistoryTagPoolUid(int index) {
10360 return mReadHistoryUids[index];
10361 }
10362
10363 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010364 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010365 final int pos = mHistoryBuffer.dataPosition();
10366 if (pos == 0) {
10367 out.clear();
10368 }
10369 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010370 if (end) {
10371 return false;
10372 }
10373
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010374 final long lastRealtime = out.time;
10375 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010376 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010377 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10378 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010379 out.currentTime = lastWalltime + (out.time - lastRealtime);
10380 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010381 return true;
10382 }
10383
10384 @Override
10385 public void finishIteratingHistoryLocked() {
10386 mIteratingHistory = false;
10387 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010388 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010389 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010390
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010391 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010392 public long getHistoryBaseTime() {
10393 return mHistoryBaseTime;
10394 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010395
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010396 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010397 public int getStartCount() {
10398 return mStartCount;
10399 }
10400
10401 public boolean isOnBattery() {
10402 return mOnBattery;
10403 }
10404
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010405 public boolean isCharging() {
10406 return mCharging;
10407 }
10408
Mike Mac2f518a2017-09-19 16:06:03 -070010409 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010410 return state == Display.STATE_ON || state == Display.STATE_VR
10411 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010412 }
10413
10414 public boolean isScreenOff(int state) {
10415 return state == Display.STATE_OFF;
10416 }
10417
10418 public boolean isScreenDoze(int state) {
10419 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010420 }
10421
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010422 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010423 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010424 mOnBatteryTimeBase.init(uptime, realtime);
10425 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010426 mRealtime = 0;
10427 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010428 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010429 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010430 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010431
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010432 void initDischarge() {
10433 mLowDischargeAmountSinceCharge = 0;
10434 mHighDischargeAmountSinceCharge = 0;
10435 mDischargeAmountScreenOn = 0;
10436 mDischargeAmountScreenOnSinceCharge = 0;
10437 mDischargeAmountScreenOff = 0;
10438 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010439 mDischargeAmountScreenDoze = 0;
10440 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010441 mDischargeStepTracker.init();
10442 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010443 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010444 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010445 mDischargeLightDozeCounter.reset(false);
10446 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010447 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010448 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010449
10450 public void resetAllStatsCmdLocked() {
10451 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010452 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010453 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010454 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010455 long realtime = mSecRealtime * 1000;
10456 mDischargeStartLevel = mHistoryCur.batteryLevel;
10457 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010458 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010459 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10460 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010461 mOnBatteryTimeBase.reset(uptime, realtime);
10462 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10463 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010464 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010465 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010466 mDischargeScreenDozeUnplugLevel = 0;
10467 mDischargeScreenOffUnplugLevel = 0;
10468 } else if (isScreenDoze(mScreenState)) {
10469 mDischargeScreenOnUnplugLevel = 0;
10470 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010471 mDischargeScreenOffUnplugLevel = 0;
10472 } else {
10473 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010474 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010475 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10476 }
10477 mDischargeAmountScreenOn = 0;
10478 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010479 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010480 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010481 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010482 }
10483
10484 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010485 final long uptimeMillis = mClocks.uptimeMillis();
10486 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010487 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010488 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010489 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010490 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010491 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010492 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010493 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010494
10495 if (mPowerProfile != null) {
10496 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10497 } else {
10498 mEstimatedBatteryCapacity = -1;
10499 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010500 mMinLearnedBatteryCapacity = -1;
10501 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010502 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010503 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010504 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010505 mLongestLightIdleTime = 0;
10506 mLongestFullIdleTime = 0;
10507 mDeviceIdleModeLightTimer.reset(false);
10508 mDeviceIdleModeFullTimer.reset(false);
10509 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010510 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010511 mPhoneOnTimer.reset(false);
10512 mAudioOnTimer.reset(false);
10513 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010514 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010515 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010516 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010517 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010518 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010519 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010520 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010521 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010522 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010523 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010524 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010525 mNetworkByteActivityCounters[i].reset(false);
10526 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010527 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010528 mMobileRadioActiveTimer.reset(false);
10529 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010530 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010531 mMobileRadioActiveUnknownTime.reset(false);
10532 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010533 mWifiOnTimer.reset(false);
10534 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010535 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010536 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010537 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010538 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10539 mWifiSupplStateTimer[i].reset(false);
10540 }
10541 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10542 mWifiSignalStrengthsTimer[i].reset(false);
10543 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010544 mWifiMulticastWakelockTimer.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010545 mWifiActivity.reset(false);
10546 mBluetoothActivity.reset(false);
10547 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010548 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010549
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010550 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010551 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010552 mUidStats.remove(mUidStats.keyAt(i));
10553 i--;
10554 }
10555 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010556
Bookatz50df7112017-08-04 14:53:26 -070010557 if (mRpmStats.size() > 0) {
10558 for (SamplingTimer timer : mRpmStats.values()) {
10559 mOnBatteryTimeBase.remove(timer);
10560 }
10561 mRpmStats.clear();
10562 }
10563 if (mScreenOffRpmStats.size() > 0) {
10564 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10565 mOnBatteryScreenOffTimeBase.remove(timer);
10566 }
10567 mScreenOffRpmStats.clear();
10568 }
10569
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010570 if (mKernelWakelockStats.size() > 0) {
10571 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010572 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010573 }
10574 mKernelWakelockStats.clear();
10575 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010576
James Carr3a226052016-07-01 14:49:52 -070010577 if (mKernelMemoryStats.size() > 0) {
10578 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10579 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10580 }
10581 mKernelMemoryStats.clear();
10582 }
10583
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010584 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010585 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10586 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010587 }
10588 mWakeupReasonStats.clear();
10589 }
10590
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010591 mLastHistoryStepDetails = null;
10592 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10593 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10594 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10595 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10596 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10597 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10598 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
10599 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
10600 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
10601 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
10602
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010603 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010604
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010605 clearHistoryLocked();
10606 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010607
Dianne Hackborn40c87252014-03-19 16:55:40 -070010608 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010609 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010610 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
10611 // Not recording process starts/stops.
10612 continue;
10613 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010614 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010615 if (active == null) {
10616 continue;
10617 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010618 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
10619 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010620 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070010621 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
10622 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010623 }
10624 }
10625 }
10626 }
10627
Mike Mac2f518a2017-09-19 16:06:03 -070010628 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
10629 updateOldDischargeScreenLevelLocked(oldState);
10630 updateNewDischargeScreenLevelLocked(newState);
10631 }
10632
10633 private void updateOldDischargeScreenLevelLocked(int state) {
10634 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010635 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
10636 if (diff > 0) {
10637 mDischargeAmountScreenOn += diff;
10638 mDischargeAmountScreenOnSinceCharge += diff;
10639 }
Mike Mac2f518a2017-09-19 16:06:03 -070010640 } else if (isScreenDoze(state)) {
10641 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
10642 if (diff > 0) {
10643 mDischargeAmountScreenDoze += diff;
10644 mDischargeAmountScreenDozeSinceCharge += diff;
10645 }
10646 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010647 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
10648 if (diff > 0) {
10649 mDischargeAmountScreenOff += diff;
10650 mDischargeAmountScreenOffSinceCharge += diff;
10651 }
10652 }
Mike Mac2f518a2017-09-19 16:06:03 -070010653 }
10654
10655 private void updateNewDischargeScreenLevelLocked(int state) {
10656 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010657 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
10658 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010659 mDischargeScreenDozeUnplugLevel = 0;
10660 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010661 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010662 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
10663 mDischargeScreenOffUnplugLevel = 0;
10664 } else if (isScreenOff(state)) {
10665 mDischargeScreenOnUnplugLevel = 0;
10666 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010667 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
10668 }
10669 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010670
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010671 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010672 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070010673 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010674 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010675 }
10676
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010677 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
10678 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
10679
10680 private final Object mWifiNetworkLock = new Object();
10681
10682 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010683 private String[] mWifiIfaces = EmptyArray.STRING;
10684
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010685 @GuardedBy("mWifiNetworkLock")
10686 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010687
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010688 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010689
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010690 @GuardedBy("mModemNetworkLock")
10691 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010692
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010693 @GuardedBy("mModemNetworkLock")
10694 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
10695
10696 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
10697 try {
10698 if (!ArrayUtils.isEmpty(ifaces)) {
10699 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
10700 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
10701 }
10702 } catch (IOException e) {
10703 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010704 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010705 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010706 }
10707
10708 /**
10709 * Distribute WiFi energy info and network traffic to apps.
10710 * @param info The energy information from the WiFi controller.
10711 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010712 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010713 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010714 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010715 }
10716
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010717 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070010718 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010719 synchronized (mWifiNetworkLock) {
10720 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
10721 if (latestStats != null) {
10722 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
10723 mNetworkStatsPool.acquire());
10724 mNetworkStatsPool.release(mLastWifiNetworkStats);
10725 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070010726 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010727 }
10728
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010729 synchronized (this) {
10730 if (!mOnBatteryInternal) {
10731 if (delta != null) {
10732 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010733 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010734 return;
10735 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010736
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010737 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
10738 SparseLongArray rxPackets = new SparseLongArray();
10739 SparseLongArray txPackets = new SparseLongArray();
10740 long totalTxPackets = 0;
10741 long totalRxPackets = 0;
10742 if (delta != null) {
10743 NetworkStats.Entry entry = new NetworkStats.Entry();
10744 final int size = delta.size();
10745 for (int i = 0; i < size; i++) {
10746 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010747
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010748 if (DEBUG_ENERGY) {
10749 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
10750 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
10751 + " txPackets=" + entry.txPackets);
10752 }
10753
10754 if (entry.rxBytes == 0 && entry.txBytes == 0) {
10755 // Skip the lookup below since there is no work to do.
10756 continue;
10757 }
10758
10759 final Uid u = getUidStatsLocked(mapUid(entry.uid));
10760 if (entry.rxBytes != 0) {
10761 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080010762 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010763 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10764 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
10765 entry.rxPackets);
10766 }
10767 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
10768 entry.rxBytes);
10769 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
10770 entry.rxPackets);
10771
10772 rxPackets.put(u.getUid(), entry.rxPackets);
10773
10774 // Sum the total number of packets so that the Rx Power can
10775 // be evenly distributed amongst the apps.
10776 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080010777 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010778
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010779 if (entry.txBytes != 0) {
10780 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080010781 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010782 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10783 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
10784 entry.txPackets);
10785 }
10786 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
10787 entry.txBytes);
10788 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
10789 entry.txPackets);
10790
10791 txPackets.put(u.getUid(), entry.txPackets);
10792
10793 // Sum the total number of packets so that the Tx Power can
10794 // be evenly distributed amongst the apps.
10795 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080010796 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080010797 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010798 mNetworkStatsPool.release(delta);
10799 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070010800 }
10801
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010802 if (info != null) {
10803 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070010804
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010805 // Measured in mAms
10806 final long txTimeMs = info.getControllerTxTimeMillis();
10807 final long rxTimeMs = info.getControllerRxTimeMillis();
10808 final long idleTimeMs = info.getControllerIdleTimeMillis();
10809 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070010810
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010811 long leftOverRxTimeMs = rxTimeMs;
10812 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070010813
Adam Lesinskie08af192015-03-25 16:42:59 -070010814 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010815 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
10816 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
10817 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
10818 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
10819 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070010820 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010821
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010822 long totalWifiLockTimeMs = 0;
10823 long totalScanTimeMs = 0;
10824
10825 // On the first pass, collect some totals so that we can normalize power
10826 // calculations if we need to.
10827 final int uidStatsSize = mUidStats.size();
10828 for (int i = 0; i < uidStatsSize; i++) {
10829 final Uid uid = mUidStats.valueAt(i);
10830
10831 // Sum the total scan power for all apps.
10832 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
10833 elapsedRealtimeMs * 1000) / 1000;
10834
10835 // Sum the total time holding wifi lock for all apps.
10836 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
10837 elapsedRealtimeMs * 1000) / 1000;
10838 }
10839
10840 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
10841 Slog.d(TAG,
10842 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
10843 + rxTimeMs + " ms). Normalizing scan time.");
10844 }
10845 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
10846 Slog.d(TAG,
10847 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
10848 + txTimeMs + " ms). Normalizing scan time.");
10849 }
10850
10851 // Actually assign and distribute power usage to apps.
10852 for (int i = 0; i < uidStatsSize; i++) {
10853 final Uid uid = mUidStats.valueAt(i);
10854
10855 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
10856 elapsedRealtimeMs * 1000) / 1000;
10857 if (scanTimeSinceMarkMs > 0) {
10858 // Set the new mark so that next time we get new data since this point.
10859 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
10860
10861 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
10862 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
10863
10864 // Our total scan time is more than the reported Tx/Rx time.
10865 // This is possible because the cost of a scan is approximate.
10866 // Let's normalize the result so that we evenly blame each app
10867 // scanning.
10868 //
10869 // This means that we may have apps that transmitted/received packets not be
10870 // blamed for this, but this is fine as scans are relatively more expensive.
10871 if (totalScanTimeMs > rxTimeMs) {
10872 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
10873 totalScanTimeMs;
10874 }
10875 if (totalScanTimeMs > txTimeMs) {
10876 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
10877 totalScanTimeMs;
10878 }
10879
10880 if (DEBUG_ENERGY) {
10881 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
10882 + scanRxTimeSinceMarkMs + " ms Tx:"
10883 + scanTxTimeSinceMarkMs + " ms)");
10884 }
10885
10886 ControllerActivityCounterImpl activityCounter =
10887 uid.getOrCreateWifiControllerActivityLocked();
10888 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
10889 activityCounter.getTxTimeCounters()[0].addCountLocked(
10890 scanTxTimeSinceMarkMs);
10891 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
10892 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
10893 }
10894
10895 // Distribute evenly the power consumed while Idle to each app holding a WiFi
10896 // lock.
10897 final long wifiLockTimeSinceMarkMs =
10898 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
10899 elapsedRealtimeMs * 1000) / 1000;
10900 if (wifiLockTimeSinceMarkMs > 0) {
10901 // Set the new mark so that next time we get new data since this point.
10902 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
10903
10904 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
10905 / totalWifiLockTimeMs;
10906 if (DEBUG_ENERGY) {
10907 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
10908 + myIdleTimeMs + " ms");
10909 }
10910 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
10911 .addCountLocked(myIdleTimeMs);
10912 }
10913 }
10914
Adam Lesinskie08af192015-03-25 16:42:59 -070010915 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010916 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
10917 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070010918 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010919
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010920 // Distribute the remaining Tx power appropriately between all apps that transmitted
10921 // packets.
10922 for (int i = 0; i < txPackets.size(); i++) {
10923 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
10924 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
10925 / totalTxPackets;
10926 if (DEBUG_ENERGY) {
10927 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
10928 }
10929 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
10930 .addCountLocked(myTxTimeMs);
10931 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010932
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010933 // Distribute the remaining Rx power appropriately between all apps that received
10934 // packets.
10935 for (int i = 0; i < rxPackets.size(); i++) {
10936 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
10937 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
10938 / totalRxPackets;
10939 if (DEBUG_ENERGY) {
10940 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
10941 }
10942 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
10943 .addCountLocked(myRxTimeMs);
10944 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010945
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010946 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
10947
10948
10949 // Update WiFi controller stats.
10950 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
10951 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
10952 info.getControllerTxTimeMillis());
10953 mWifiActivity.getIdleTimeCounter().addCountLocked(
10954 info.getControllerIdleTimeMillis());
10955
10956 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
10957 final double opVolt = mPowerProfile.getAveragePower(
10958 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
10959 if (opVolt != 0) {
10960 // We store the power drain as mAms.
10961 mWifiActivity.getPowerCounter().addCountLocked(
10962 (long) (info.getControllerEnergyUsed() / opVolt));
10963 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010964 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010965 }
10966 }
10967
10968 /**
10969 * Distribute Cell radio energy info and network traffic to apps.
10970 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010971 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010972 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010973 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010974 }
10975
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010976 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070010977 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010978 synchronized (mModemNetworkLock) {
10979 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
10980 if (latestStats != null) {
10981 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
10982 mNetworkStatsPool.acquire());
10983 mNetworkStatsPool.release(mLastModemNetworkStats);
10984 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070010985 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010986 }
10987
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010988 synchronized (this) {
10989 if (!mOnBatteryInternal) {
10990 if (delta != null) {
10991 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010992 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010993 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070010994 }
10995
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010996 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010997 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
10998 elapsedRealtimeMs * 1000);
10999 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11000
11001 long totalRxPackets = 0;
11002 long totalTxPackets = 0;
11003 if (delta != null) {
11004 NetworkStats.Entry entry = new NetworkStats.Entry();
11005 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011006 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011007 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011008 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11009 continue;
11010 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011011
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011012 if (DEBUG_ENERGY) {
11013 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11014 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11015 + " txPackets=" + entry.txPackets);
11016 }
11017
11018 totalRxPackets += entry.rxPackets;
11019 totalTxPackets += entry.txPackets;
11020
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011021 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011022 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11023 entry.rxPackets);
11024 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11025 entry.txPackets);
11026 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11027 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11028 entry.rxBytes, entry.rxPackets);
11029 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11030 entry.txBytes, entry.txPackets);
11031 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011032
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011033 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11034 entry.rxBytes);
11035 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11036 entry.txBytes);
11037 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11038 entry.rxPackets);
11039 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11040 entry.txPackets);
11041 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011042
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011043 // Now distribute proportional blame to the apps that did networking.
11044 long totalPackets = totalRxPackets + totalTxPackets;
11045 if (totalPackets > 0) {
11046 for (int i = 0; i < size; i++) {
11047 entry = delta.getValues(i, entry);
11048 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11049 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011050 }
11051
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011052 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11053
11054 // Distribute total radio active time in to this app.
11055 final long appPackets = entry.rxPackets + entry.txPackets;
11056 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11057 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11058
11059 // Remove this app from the totals, so that we don't lose any time
11060 // due to rounding.
11061 radioTime -= appRadioTime;
11062 totalPackets -= appPackets;
11063
11064 if (activityInfo != null) {
11065 ControllerActivityCounterImpl activityCounter =
11066 u.getOrCreateModemControllerActivityLocked();
11067 if (totalRxPackets > 0 && entry.rxPackets > 0) {
11068 final long rxMs = (entry.rxPackets * activityInfo.getRxTimeMillis())
11069 / totalRxPackets;
11070 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11071 }
11072
11073 if (totalTxPackets > 0 && entry.txPackets > 0) {
11074 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11075 long txMs =
11076 entry.txPackets * activityInfo.getTxTimeMillis()[lvl];
11077 txMs /= totalTxPackets;
11078 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11079 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011080 }
11081 }
11082 }
11083 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011084
11085 if (radioTime > 0) {
11086 // Whoops, there is some radio time we can't blame on an app!
11087 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11088 mMobileRadioActiveUnknownCount.addCountLocked(1);
11089 }
11090
11091 mNetworkStatsPool.release(delta);
11092 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011093 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011094
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011095 if (activityInfo != null) {
11096 mHasModemReporting = true;
11097 mModemActivity.getIdleTimeCounter().addCountLocked(
11098 activityInfo.getIdleTimeMillis());
11099 mModemActivity.getRxTimeCounter().addCountLocked(activityInfo.getRxTimeMillis());
11100 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11101 mModemActivity.getTxTimeCounters()[lvl]
11102 .addCountLocked(activityInfo.getTxTimeMillis()[lvl]);
11103 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011104
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011105 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11106 final double opVolt = mPowerProfile.getAveragePower(
11107 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11108 if (opVolt != 0) {
11109 // We store the power drain as mAms.
11110 mModemActivity.getPowerCounter().addCountLocked(
11111 (long) (activityInfo.getEnergyUsed() / opVolt));
11112 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011113 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011114 }
11115 }
11116
11117 /**
11118 * Distribute Bluetooth energy info and network traffic to apps.
11119 * @param info The energy information from the bluetooth controller.
11120 */
11121 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011122 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011123 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011124 }
11125
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011126 if (info == null || !mOnBatteryInternal) {
11127 return;
11128 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011129
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011130 mHasBluetoothReporting = true;
11131
Bookatz867c0d72017-03-07 18:23:42 -080011132 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011133 final long rxTimeMs = info.getControllerRxTimeMillis();
11134 final long txTimeMs = info.getControllerTxTimeMillis();
11135
11136 if (DEBUG_ENERGY) {
11137 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11138 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11139 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11140 Slog.d(TAG, " Idle Time: " + info.getControllerIdleTimeMillis() + " ms");
11141 }
11142
11143 long totalScanTimeMs = 0;
11144
11145 final int uidCount = mUidStats.size();
11146 for (int i = 0; i < uidCount; i++) {
11147 final Uid u = mUidStats.valueAt(i);
11148 if (u.mBluetoothScanTimer == null) {
11149 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011150 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011151
Bookatzaa4594a2017-03-24 12:39:56 -070011152 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011153 elapsedRealtimeMs * 1000) / 1000;
11154 }
11155
11156 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11157 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11158
11159 if (DEBUG_ENERGY) {
11160 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11161 + " TX=" + normalizeScanTxTime);
11162 }
11163
11164 long leftOverRxTimeMs = rxTimeMs;
11165 long leftOverTxTimeMs = txTimeMs;
11166
11167 for (int i = 0; i < uidCount; i++) {
11168 final Uid u = mUidStats.valueAt(i);
11169 if (u.mBluetoothScanTimer == null) {
11170 continue;
11171 }
11172
Bookatzaa4594a2017-03-24 12:39:56 -070011173 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011174 elapsedRealtimeMs * 1000) / 1000;
11175 if (scanTimeSinceMarkMs > 0) {
11176 // Set the new mark so that next time we get new data since this point.
11177 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11178
11179 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11180 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11181
11182 if (normalizeScanRxTime) {
11183 // Scan time is longer than the total rx time in the controller,
11184 // so distribute the scan time proportionately. This means regular traffic
11185 // will not blamed, but scans are more expensive anyways.
11186 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11187 }
11188
11189 if (normalizeScanTxTime) {
11190 // Scan time is longer than the total tx time in the controller,
11191 // so distribute the scan time proportionately. This means regular traffic
11192 // will not blamed, but scans are more expensive anyways.
11193 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11194 }
11195
11196 final ControllerActivityCounterImpl counter =
11197 u.getOrCreateBluetoothControllerActivityLocked();
11198 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11199 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11200
11201 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11202 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11203 }
11204 }
11205
11206 if (DEBUG_ENERGY) {
11207 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs
11208 + " TX=" + leftOverTxTimeMs);
11209 }
11210
11211 //
11212 // Now distribute blame to apps that did bluetooth traffic.
11213 //
11214
11215 long totalTxBytes = 0;
11216 long totalRxBytes = 0;
11217
11218 final UidTraffic[] uidTraffic = info.getUidTraffic();
11219 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11220 for (int i = 0; i < numUids; i++) {
11221 final UidTraffic traffic = uidTraffic[i];
11222
11223 // Add to the global counters.
11224 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(
11225 traffic.getRxBytes());
11226 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(
11227 traffic.getTxBytes());
11228
11229 // Add to the UID counters.
11230 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
11231 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, traffic.getRxBytes(), 0);
11232 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, traffic.getTxBytes(), 0);
11233
11234 // Calculate the total traffic.
11235 totalTxBytes += traffic.getTxBytes();
11236 totalRxBytes += traffic.getRxBytes();
11237 }
11238
11239 if ((totalTxBytes != 0 || totalRxBytes != 0) &&
11240 (leftOverRxTimeMs != 0 || leftOverTxTimeMs != 0)) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011241 for (int i = 0; i < numUids; i++) {
11242 final UidTraffic traffic = uidTraffic[i];
11243
Adam Lesinski50e47602015-12-04 17:04:54 -080011244 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011245 final ControllerActivityCounterImpl counter =
11246 u.getOrCreateBluetoothControllerActivityLocked();
11247
11248 if (totalRxBytes > 0 && traffic.getRxBytes() > 0) {
11249 final long timeRxMs = (leftOverRxTimeMs * traffic.getRxBytes()) / totalRxBytes;
11250
11251 if (DEBUG_ENERGY) {
11252 Slog.d(TAG, "UID=" + traffic.getUid() + " rx_bytes=" + traffic.getRxBytes()
11253 + " rx_time=" + timeRxMs);
11254 }
11255 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11256 leftOverRxTimeMs -= timeRxMs;
11257 }
11258
11259 if (totalTxBytes > 0 && traffic.getTxBytes() > 0) {
11260 final long timeTxMs = (leftOverTxTimeMs * traffic.getTxBytes()) / totalTxBytes;
11261
11262 if (DEBUG_ENERGY) {
11263 Slog.d(TAG, "UID=" + traffic.getUid() + " tx_bytes=" + traffic.getTxBytes()
11264 + " tx_time=" + timeTxMs);
11265 }
11266
11267 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11268 leftOverTxTimeMs -= timeTxMs;
11269 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011270 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011271 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011272
11273 mBluetoothActivity.getRxTimeCounter().addCountLocked(
11274 info.getControllerRxTimeMillis());
11275 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(
11276 info.getControllerTxTimeMillis());
11277 mBluetoothActivity.getIdleTimeCounter().addCountLocked(
11278 info.getControllerIdleTimeMillis());
11279
11280 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11281 final double opVolt = mPowerProfile.getAveragePower(
11282 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11283 if (opVolt != 0) {
11284 // We store the power drain as mAms.
11285 mBluetoothActivity.getPowerCounter().addCountLocked(
11286 (long) (info.getControllerEnergyUsed() / opVolt));
11287 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011288 }
11289
11290 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011291 * Read and record Resource Power Manager (RPM) state and voter times.
11292 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11293 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011294 */
11295 public void updateRpmStatsLocked() {
11296 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011297 long now = SystemClock.elapsedRealtime();
11298 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11299 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11300 mLastRpmStatsUpdateTimeMs = now;
11301 }
Bookatz50df7112017-08-04 14:53:26 -070011302
11303 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11304 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11305
11306 // Update values for this platform state.
11307 final String pName = pstate.getKey();
11308 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11309 final int pCount = pstate.getValue().mCount;
11310 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011311 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11312 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11313 }
Bookatz50df7112017-08-04 14:53:26 -070011314
11315 // Update values for each voter of this platform state.
11316 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11317 : pstate.getValue().mVoters.entrySet()) {
11318 final String vName = pName + "." + voter.getKey();
11319 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11320 final int vCount = voter.getValue().mCount;
11321 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011322 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11323 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11324 }
Bookatz50df7112017-08-04 14:53:26 -070011325 }
11326 }
11327
11328 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11329 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11330
11331 final String subsysName = subsys.getKey();
11332 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11333 : subsys.getValue().mStates.entrySet()) {
11334 final String name = subsysName + "." + sstate.getKey();
11335 final long timeUs = sstate.getValue().mTimeMs * 1000;
11336 final int count = sstate.getValue().mCount;
11337 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011338 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11339 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11340 }
Bookatz50df7112017-08-04 14:53:26 -070011341 }
11342 }
11343 }
11344
11345 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011346 * Read and distribute kernel wake lock use across apps.
11347 */
11348 public void updateKernelWakelocksLocked() {
11349 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11350 mTmpWakelockStats);
11351 if (wakelockStats == null) {
11352 // Not crashing might make board bringup easier.
11353 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11354 return;
11355 }
11356
11357 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11358 String name = ent.getKey();
11359 KernelWakelockStats.Entry kws = ent.getValue();
11360
11361 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11362 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011363 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011364 mKernelWakelockStats.put(name, kwlt);
11365 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011366
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011367 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011368 kwlt.setUpdateVersion(kws.mVersion);
11369 }
11370
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011371 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011372 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11373 // this time.
11374 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11375 SamplingTimer st = ent.getValue();
11376 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11377 st.endSample();
11378 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011379 }
11380 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011381
Adam Lesinskid84ad302016-05-17 18:31:02 -070011382 // Record whether we've seen a non-zero time (for debugging b/22716723).
11383 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011384 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11385 }
11386
11387 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11388 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11389 wakelockStats.kernelWakelockVersion);
11390 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011391 }
11392
Adam Lesinski72478f02015-06-17 15:39:43 -070011393 // We use an anonymous class to access these variables,
11394 // so they can't live on the stack or they'd have to be
11395 // final MutableLong objects (more allocations).
11396 // Used in updateCpuTimeLocked().
11397 long mTempTotalCpuUserTimeUs;
11398 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011399 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011400
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011401 /**
James Carr3a226052016-07-01 14:49:52 -070011402 * Reads the newest memory stats from the kernel.
11403 */
11404 public void updateKernelMemoryBandwidthLocked() {
11405 mKernelMemoryBandwidthStats.updateStats();
11406 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11407 final int bandwidthEntryCount = bandwidthEntries.size();
11408 int index;
11409 for (int i = 0; i < bandwidthEntryCount; i++) {
11410 SamplingTimer timer;
11411 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11412 timer = mKernelMemoryStats.valueAt(index);
11413 } else {
11414 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11415 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11416 }
11417 timer.update(bandwidthEntries.valueAt(i), 1);
11418 if (DEBUG_MEMORY) {
11419 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11420 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11421 mKernelMemoryStats.get(
11422 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11423 mKernelMemoryStats.size()));
11424 }
11425 }
11426 }
11427
11428 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011429 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11430 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11431 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011432 */
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011433 public void updateCpuTimeLocked() {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011434 if (mPowerProfile == null) {
11435 return;
11436 }
11437
Adam Lesinski72478f02015-06-17 15:39:43 -070011438 if (DEBUG_ENERGY_CPU) {
11439 Slog.d(TAG, "!Cpu updating!");
11440 }
11441
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011442 if (mCpuFreqs == null) {
11443 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11444 }
11445
Sudheer Shanka38383232017-07-25 09:55:03 -070011446 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11447 // usually holding the wakelock on behalf of an app.
11448 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11449 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Adam Lesinski72478f02015-06-17 15:39:43 -070011450 if (mOnBatteryScreenOffTimeBase.isRunning()) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011451 partialTimersToConsider = new ArrayList<>();
11452 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011453 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011454 // Since the collection and blaming of wakelocks can be scheduled to run after
11455 // some delay, the mPartialTimers list may have new entries. We can't blame
11456 // the newly added timer for past cpu time, so we only consider timers that
11457 // were present for one round of collection. Once a timer has gone through
11458 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011459 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011460 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011461 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011462 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011463 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011464 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011465
Sudheer Shanka38383232017-07-25 09:55:03 -070011466 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11467 // need to take the snapshots.
11468 if (!mOnBatteryInternal) {
11469 mKernelUidCpuTimeReader.readDelta(null);
11470 mKernelUidCpuFreqTimeReader.readDelta(null);
11471 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
11472 mKernelCpuSpeedReaders[cluster].readDelta();
11473 }
11474 return;
11475 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011476
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011477 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011478 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
11479 ? null : new SparseLongArray();
Sudheer Shanka38383232017-07-25 09:55:03 -070011480 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011481 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
11482 // freqs, so no need to approximate these values.
11483 if (updatedUids != null) {
11484 updateClusterSpeedTimes(updatedUids);
Sudheer Shanka671985f2017-05-19 11:33:42 -070011485 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011486 readKernelUidCpuFreqTimesLocked(partialTimersToConsider);
Sudheer Shanka38383232017-07-25 09:55:03 -070011487 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011488
Sudheer Shanka38383232017-07-25 09:55:03 -070011489 /**
11490 * Mark the current partial timers as gone through a collection so that they will be
11491 * considered in the next cpu times distribution to wakelock holders.
11492 */
11493 @VisibleForTesting
11494 public void markPartialTimersAsEligible() {
11495 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
11496 // No difference, so each timer is now considered for the next collection.
11497 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
11498 mPartialTimers.get(i).mInList = true;
11499 }
11500 } else {
11501 // The lists are different, meaning we added (or removed a timer) since the last
11502 // collection.
11503 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
11504 mLastPartialTimers.get(i).mInList = false;
11505 }
11506 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070011507
Sudheer Shanka38383232017-07-25 09:55:03 -070011508 // Mark the current timers as gone through a collection.
11509 final int numPartialTimers = mPartialTimers.size();
11510 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011511 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011512 timer.mInList = true;
11513 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070011514 }
11515 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011516 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011517
Sudheer Shanka38383232017-07-25 09:55:03 -070011518 /**
11519 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
11520 * calculate cpu times spent by each uid at different frequencies.
11521 *
11522 * @param updatedUids The uids for which times spent at different frequencies are calculated.
11523 */
11524 @VisibleForTesting
11525 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011526 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011527 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070011528 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011529 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011530 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
11531 if (clusterSpeedTimesMs[cluster] != null) {
11532 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
11533 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011534 }
11535 }
11536 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011537 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011538 // We have cpu times per freq aggregated over all uids but we need the times per uid.
11539 // So, we distribute total time spent by an uid to different cpu freqs based on the
11540 // amount of time cpu was running at that freq.
11541 final int updatedUidsCount = updatedUids.size();
11542 for (int i = 0; i < updatedUidsCount; ++i) {
11543 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070011544 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011545 // Add the cpu speeds to this UID.
11546 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070011547 if (u.mCpuClusterSpeedTimesUs == null ||
11548 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011549 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011550 }
11551
Sudheer Shankaaf857412017-07-21 00:14:24 -070011552 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
11553 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
11554 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
11555 u.mCpuClusterSpeedTimesUs[cluster].length) {
11556 u.mCpuClusterSpeedTimesUs[cluster]
11557 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011558 }
11559
Sudheer Shankaaf857412017-07-21 00:14:24 -070011560 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011561 for (int speed = 0; speed < speedsInCluster; speed++) {
11562 if (cpuSpeeds[speed] == null) {
11563 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11564 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011565 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
11566 * clusterSpeedTimesMs[cluster][speed]
11567 / totalCpuClustersTimeMs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011568 }
11569 }
11570 }
11571 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011572 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011573
Sudheer Shanka38383232017-07-25 09:55:03 -070011574 /**
11575 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
11576 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
11577 * wakelock holders.
11578 *
11579 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
11580 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
11581 */
11582 @VisibleForTesting
11583 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
11584 @Nullable SparseLongArray updatedUids) {
11585 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
11586 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11587 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070011588
Sudheer Shanka38383232017-07-25 09:55:03 -070011589 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
11590 uid = mapUid(uid);
11591 if (Process.isIsolated(uid)) {
11592 // This could happen if the isolated uid mapping was removed before that process
11593 // was actually killed.
11594 mKernelUidCpuTimeReader.removeUid(uid);
11595 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
11596 return;
11597 }
11598 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11599 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
11600 mKernelUidCpuTimeReader.removeUid(uid);
11601 return;
11602 }
11603 final Uid u = getUidStatsLocked(uid);
11604
11605 // Accumulate the total system and user time.
11606 mTempTotalCpuUserTimeUs += userTimeUs;
11607 mTempTotalCpuSystemTimeUs += systemTimeUs;
11608
11609 StringBuilder sb = null;
11610 if (DEBUG_ENERGY_CPU) {
11611 sb = new StringBuilder();
11612 sb.append(" got time for uid=").append(u.mUid).append(": u=");
11613 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11614 sb.append(" s=");
11615 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11616 sb.append("\n");
11617 }
11618
11619 if (numWakelocks > 0) {
11620 // We have wakelocks being held, so only give a portion of the
11621 // time to the process. The rest will be distributed among wakelock
11622 // holders.
11623 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
11624 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
11625 }
11626
11627 if (sb != null) {
11628 sb.append(" adding to uid=").append(u.mUid).append(": u=");
11629 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11630 sb.append(" s=");
11631 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11632 Slog.d(TAG, sb.toString());
11633 }
11634
11635 u.mUserCpuTime.addCountLocked(userTimeUs);
11636 u.mSystemCpuTime.addCountLocked(systemTimeUs);
11637 if (updatedUids != null) {
11638 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
11639 }
11640 });
11641
11642 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11643 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11644 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
11645 }
11646
11647 if (numWakelocks > 0) {
11648 // Distribute a portion of the total cpu time to wakelock holders.
11649 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11650 mTempTotalCpuSystemTimeUs =
11651 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11652
11653 for (int i = 0; i < numWakelocks; ++i) {
11654 final StopwatchTimer timer = partialTimers.get(i);
11655 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
11656 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
11657
11658 if (DEBUG_ENERGY_CPU) {
11659 final StringBuilder sb = new StringBuilder();
11660 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
11661 .append(": u=");
11662 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11663 sb.append(" s=");
11664 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11665 Slog.d(TAG, sb.toString());
11666 }
11667
11668 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs);
11669 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs);
11670 if (updatedUids != null) {
11671 final int uid = timer.mUid.getUid();
11672 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
11673 }
11674
11675 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
11676 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000);
11677
11678 mTempTotalCpuUserTimeUs -= userTimeUs;
11679 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011680 }
11681 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011682 }
11683
Sudheer Shanka38383232017-07-25 09:55:03 -070011684 /**
11685 * Take a snapshot of the cpu times spent by each uid in each freq and update the
11686 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011687 *
11688 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070011689 */
11690 @VisibleForTesting
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011691 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers) {
11692 final boolean perClusterTimesAvailable =
11693 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
11694 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11695 final int numClusters = mPowerProfile.getNumCpuClusters();
11696 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080011697 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011698 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
11699 uid = mapUid(uid);
11700 if (Process.isIsolated(uid)) {
11701 mKernelUidCpuFreqTimeReader.removeUid(uid);
11702 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
11703 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070011704 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011705 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11706 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
11707 mKernelUidCpuFreqTimeReader.removeUid(uid);
11708 return;
11709 }
11710 final Uid u = getUidStatsLocked(uid);
11711 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
11712 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
11713 }
11714 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
11715 if (u.mScreenOffCpuFreqTimeMs == null ||
11716 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
11717 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
11718 mOnBatteryScreenOffTimeBase);
11719 }
11720 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011721
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011722 if (perClusterTimesAvailable) {
11723 if (u.mCpuClusterSpeedTimesUs == null ||
11724 u.mCpuClusterSpeedTimesUs.length != numClusters) {
11725 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070011726 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011727 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
11728 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070011729 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011730
11731 int freqIndex = 0;
11732 for (int cluster = 0; cluster < numClusters; ++cluster) {
11733 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
11734 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
11735 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
11736 u.mCpuClusterSpeedTimesUs[cluster]
11737 = new LongSamplingCounter[speedsInCluster];
11738 }
11739 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
11740 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
11741 }
11742 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
11743 for (int speed = 0; speed < speedsInCluster; ++speed) {
11744 if (cpuTimesUs[speed] == null) {
11745 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11746 }
11747 final long appAllocationUs;
11748 if (mWakeLockAllocationsUs != null) {
11749 appAllocationUs =
11750 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
11751 mWakeLockAllocationsUs[cluster][speed] +=
11752 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
11753 } else {
11754 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
11755 }
11756 cpuTimesUs[speed].addCountLocked(appAllocationUs);
11757 freqIndex++;
11758 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011759 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011760 }
11761 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011762
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080011763 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11764 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11765 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
11766 }
11767
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011768 if (mWakeLockAllocationsUs != null) {
11769 for (int i = 0; i < numWakelocks; ++i) {
11770 final Uid u = partialTimers.get(i).mUid;
11771 if (u.mCpuClusterSpeedTimesUs == null ||
11772 u.mCpuClusterSpeedTimesUs.length != numClusters) {
11773 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
11774 }
11775
11776 for (int cluster = 0; cluster < numClusters; ++cluster) {
11777 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
11778 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
11779 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
11780 u.mCpuClusterSpeedTimesUs[cluster]
11781 = new LongSamplingCounter[speedsInCluster];
11782 }
11783 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
11784 for (int speed = 0; speed < speedsInCluster; ++speed) {
11785 if (cpuTimeUs[speed] == null) {
11786 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11787 }
11788 final long allocationUs =
11789 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
11790 cpuTimeUs[speed].addCountLocked(allocationUs);
11791 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
11792 }
11793 }
11794 }
11795 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011796 }
11797
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011798 boolean setChargingLocked(boolean charging) {
11799 if (mCharging != charging) {
11800 mCharging = charging;
11801 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070011802 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011803 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070011804 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011805 }
11806 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
11807 return true;
11808 }
11809 return false;
11810 }
11811
Mike Mac2f518a2017-09-19 16:06:03 -070011812 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
11813 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011814 boolean doWrite = false;
11815 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
11816 m.arg1 = onBattery ? 1 : 0;
11817 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011818
Dianne Hackborn40c87252014-03-19 16:55:40 -070011819 final long uptime = mSecUptime * 1000;
11820 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070011821 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011822 if (onBattery) {
11823 // We will reset our status if we are unplugging after the
11824 // battery was last full, or the level is at 100, or
11825 // we have gone through a significant charge (from a very low
11826 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011827 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070011828 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011829 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070011830 || (mDischargeCurrentLevel < 20 && level >= 80)
11831 || (getHighDischargeAmountSinceCharge() >= 200
11832 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070011833 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070011834 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070011835 + " lowAmount=" + getLowDischargeAmountSinceCharge()
11836 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011837 // Before we write, collect a snapshot of the final aggregated
11838 // stats to be reported in the next checkin. Only do this if we have
11839 // a sufficient amount of data to make it interesting.
11840 if (getLowDischargeAmountSinceCharge() >= 20) {
11841 final Parcel parcel = Parcel.obtain();
11842 writeSummaryToParcel(parcel, true);
11843 BackgroundThread.getHandler().post(new Runnable() {
11844 @Override public void run() {
11845 synchronized (mCheckinFile) {
11846 FileOutputStream stream = null;
11847 try {
11848 stream = mCheckinFile.startWrite();
11849 stream.write(parcel.marshall());
11850 stream.flush();
11851 FileUtils.sync(stream);
11852 stream.close();
11853 mCheckinFile.finishWrite(stream);
11854 } catch (IOException e) {
11855 Slog.w("BatteryStats",
11856 "Error writing checkin battery statistics", e);
11857 mCheckinFile.failWrite(stream);
11858 } finally {
11859 parcel.recycle();
11860 }
11861 }
11862 }
11863 });
11864 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011865 doWrite = true;
11866 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080011867 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070011868 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080011869 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070011870 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011871 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080011872 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011873 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011874 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011875 if (mCharging) {
11876 setChargingLocked(false);
11877 }
11878 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080011879 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011880 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070011881 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011882 mDischargeStepTracker.clearTime();
11883 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011884 mInitStepMode = mCurStepMode;
11885 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011886 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011887 mHistoryCur.batteryLevel = (byte)level;
11888 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
11889 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
11890 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011891 if (reset) {
11892 mRecordingHistory = true;
11893 startRecordingHistory(mSecRealtime, mSecUptime, reset);
11894 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070011895 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011896 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070011897 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011898 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070011899 mDischargeScreenDozeUnplugLevel = 0;
11900 mDischargeScreenOffUnplugLevel = 0;
11901 } else if (isScreenDoze(screenState)) {
11902 mDischargeScreenOnUnplugLevel = 0;
11903 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011904 mDischargeScreenOffUnplugLevel = 0;
11905 } else {
11906 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011907 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011908 mDischargeScreenOffUnplugLevel = level;
11909 }
11910 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011911 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011912 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070011913 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011914 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070011915 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080011916 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080011917 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011918 mHistoryCur.batteryLevel = (byte)level;
11919 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
11920 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
11921 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070011922 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011923 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011924 if (level < mDischargeUnplugLevel) {
11925 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
11926 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
11927 }
Mike Mac2f518a2017-09-19 16:06:03 -070011928 updateDischargeScreenLevelsLocked(screenState, screenState);
11929 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011930 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070011931 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070011932 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011933 mInitStepMode = mCurStepMode;
11934 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080011935 }
11936 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
11937 if (mFile != null) {
11938 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011939 }
11940 }
11941 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011942
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011943 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
11944 boolean reset) {
11945 mRecordingHistory = true;
11946 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn37de0982014-05-09 09:32:18 -070011947 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs,
11948 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011949 mHistoryCur);
11950 mHistoryCur.currentTime = 0;
11951 if (reset) {
11952 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
11953 }
11954 }
11955
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070011956 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
11957 final long uptimeMs) {
11958 if (mRecordingHistory) {
11959 mHistoryCur.currentTime = currentTime;
11960 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_CURRENT_TIME,
11961 mHistoryCur);
11962 mHistoryCur.currentTime = 0;
11963 }
11964 }
11965
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080011966 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
11967 if (mRecordingHistory) {
11968 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080011969 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_SHUTDOWN,
11970 mHistoryCur);
11971 mHistoryCur.currentTime = 0;
11972 }
11973 }
11974
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011975 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011976 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011977 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011978 }
11979 }
11980
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011981 // This should probably be exposed in the API, though it's not critical
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011982 public static final int BATTERY_PLUGGED_NONE = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011983
Bookatz8c6571b2017-10-24 15:04:41 -070011984 public void setBatteryStateLocked(final int status, final int health, final int plugType,
11985 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
11986 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070011987 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
11988 temp = Math.max(0, temp);
11989
Bookatz8c6571b2017-10-24 15:04:41 -070011990 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
11991 status, plugType, level, temp);
11992
Todd Poynor1acf06a2017-12-07 19:19:35 -080011993 final boolean onBattery =
11994 plugType == BATTERY_PLUGGED_NONE &&
11995 status != BatteryManager.BATTERY_STATUS_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080011996 final long uptime = mClocks.uptimeMillis();
11997 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011998 if (!mHaveBatteryLevel) {
11999 mHaveBatteryLevel = true;
12000 // We start out assuming that the device is plugged in (not
12001 // on battery). If our first report is now that we are indeed
12002 // plugged in, then twiddle our state to correctly reflect that
12003 // since we won't be going through the full setOnBattery().
12004 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012005 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012006 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012007 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012008 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012009 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012010 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012011 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012012 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012013 mHistoryCur.batteryStatus = (byte)status;
12014 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012015 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012016 mMaxChargeStepLevel = mMinDischargeStepLevel =
12017 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012018 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012019 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12020 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12021 }
12022 int oldStatus = mHistoryCur.batteryStatus;
12023 if (onBattery) {
12024 mDischargeCurrentLevel = level;
12025 if (!mRecordingHistory) {
12026 mRecordingHistory = true;
12027 startRecordingHistory(elapsedRealtime, uptime, true);
12028 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012029 } else if (level < 96 &&
12030 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012031 if (!mRecordingHistory) {
12032 mRecordingHistory = true;
12033 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012034 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012035 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012036 mCurrentBatteryLevel = level;
12037 if (mDischargePlugLevel < 0) {
12038 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012039 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012040
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012041 if (onBattery != mOnBattery) {
12042 mHistoryCur.batteryLevel = (byte)level;
12043 mHistoryCur.batteryStatus = (byte)status;
12044 mHistoryCur.batteryHealth = (byte)health;
12045 mHistoryCur.batteryPlugType = (byte)plugType;
12046 mHistoryCur.batteryTemperature = (short)temp;
12047 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012048 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12049 // Only record discharges
12050 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12051 mDischargeCounter.addCountLocked(chargeDiff);
12052 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012053 if (isScreenDoze(mScreenState)) {
12054 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12055 }
Mike Ma15313c92017-11-15 17:58:21 -080012056 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12057 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12058 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12059 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12060 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012061 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012062 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012063 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012064 } else {
12065 boolean changed = false;
12066 if (mHistoryCur.batteryLevel != level) {
12067 mHistoryCur.batteryLevel = (byte)level;
12068 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012069
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012070 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12071 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012072 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070012073 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012074 if (mHistoryCur.batteryStatus != status) {
12075 mHistoryCur.batteryStatus = (byte)status;
12076 changed = true;
12077 }
12078 if (mHistoryCur.batteryHealth != health) {
12079 mHistoryCur.batteryHealth = (byte)health;
12080 changed = true;
12081 }
12082 if (mHistoryCur.batteryPlugType != plugType) {
12083 mHistoryCur.batteryPlugType = (byte)plugType;
12084 changed = true;
12085 }
12086 if (temp >= (mHistoryCur.batteryTemperature+10)
12087 || temp <= (mHistoryCur.batteryTemperature-10)) {
12088 mHistoryCur.batteryTemperature = (short)temp;
12089 changed = true;
12090 }
12091 if (volt > (mHistoryCur.batteryVoltage+20)
12092 || volt < (mHistoryCur.batteryVoltage-20)) {
12093 mHistoryCur.batteryVoltage = (char)volt;
12094 changed = true;
12095 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012096 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12097 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012098 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12099 // Only record discharges
12100 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12101 mDischargeCounter.addCountLocked(chargeDiff);
12102 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012103 if (isScreenDoze(mScreenState)) {
12104 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12105 }
Mike Ma15313c92017-11-15 17:58:21 -080012106 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12107 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12108 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12109 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12110 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012111 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012112 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012113 changed = true;
12114 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012115 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12116 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12117 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12118 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012119 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012120 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12121 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12122 modeBits, elapsedRealtime);
12123 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12124 modeBits, elapsedRealtime);
12125 mLastDischargeStepLevel = level;
12126 mMinDischargeStepLevel = level;
12127 mInitStepMode = mCurStepMode;
12128 mModStepMode = 0;
12129 }
12130 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012131 if (level >= 90) {
12132 // If the battery level is at least 90%, always consider the device to be
12133 // charging even if it happens to go down a level.
12134 changed |= setChargingLocked(true);
12135 mLastChargeStepLevel = level;
12136 } if (!mCharging) {
12137 if (mLastChargeStepLevel < level) {
12138 // We have not reporting that we are charging, but the level has now
12139 // gone up, so consider the state to be charging.
12140 changed |= setChargingLocked(true);
12141 mLastChargeStepLevel = level;
12142 }
12143 } else {
12144 if (mLastChargeStepLevel > level) {
12145 // We had reported that the device was charging, but here we are with
12146 // power connected and the level going down. Looks like the current
12147 // power supplied isn't enough, so consider the device to now be
12148 // discharging.
12149 changed |= setChargingLocked(false);
12150 mLastChargeStepLevel = level;
12151 }
12152 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012153 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12154 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12155 modeBits, elapsedRealtime);
12156 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12157 modeBits, elapsedRealtime);
12158 mLastChargeStepLevel = level;
12159 mMaxChargeStepLevel = level;
12160 mInitStepMode = mCurStepMode;
12161 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012162 }
12163 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012164 if (changed) {
12165 addHistoryRecordLocked(elapsedRealtime, uptime);
12166 }
Evan Millarc64edde2009-04-18 12:26:32 -070012167 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012168 if (!onBattery &&
12169 (status == BatteryManager.BATTERY_STATUS_FULL ||
12170 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12171 // We don't record history while we are plugged in and fully charged
12172 // (or when battery is not present). The next time we are
12173 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012174 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012175 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012176
Jocelyn Dangc627d102017-04-14 13:15:14 -070012177 if (mMinLearnedBatteryCapacity == -1) {
12178 mMinLearnedBatteryCapacity = chargeFullUAh;
12179 } else {
12180 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012181 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012182 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012183 }
12184
Bookatz8c6571b2017-10-24 15:04:41 -070012185 // Inform StatsLog of setBatteryState changes.
12186 // If this is the first reporting, pass in recentPast == null.
12187 private void reportChangesToStatsLog(HistoryItem recentPast,
12188 final int status, final int plugType, final int level, final int temp) {
12189
12190 if (recentPast == null || recentPast.batteryStatus != status) {
12191 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12192 }
12193 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12194 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12195 }
12196 if (recentPast == null || recentPast.batteryLevel != level) {
12197 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12198 }
12199 // Let's just always print the temperature, regardless of whether it changed.
12200 StatsLog.write(StatsLog.DEVICE_TEMPERATURE_REPORTED, temp);
12201 }
12202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012203 public long getAwakeTimeBattery() {
12204 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12205 }
12206
12207 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012208 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012209 }
12210
12211 @Override
12212 public long computeUptime(long curTime, int which) {
12213 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012214 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012215 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012216 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012217 }
12218 return 0;
12219 }
12220
12221 @Override
12222 public long computeRealtime(long curTime, int which) {
12223 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012224 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012225 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012226 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012227 }
12228 return 0;
12229 }
12230
12231 @Override
12232 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012233 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012234 }
12235
12236 @Override
12237 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012238 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012239 }
12240
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012241 @Override
12242 public long computeBatteryScreenOffUptime(long curTime, int which) {
12243 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12244 }
12245
12246 @Override
12247 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12248 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012249 }
12250
Dianne Hackborn260c5022014-04-29 11:23:16 -070012251 private long computeTimePerLevel(long[] steps, int numSteps) {
12252 // For now we'll do a simple average across all steps.
12253 if (numSteps <= 0) {
12254 return -1;
12255 }
12256 long total = 0;
12257 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012258 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012259 }
12260 return total / numSteps;
12261 /*
12262 long[] buckets = new long[numSteps];
12263 int numBuckets = 0;
12264 int numToAverage = 4;
12265 int i = 0;
12266 while (i < numSteps) {
12267 long totalTime = 0;
12268 int num = 0;
12269 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012270 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012271 num++;
12272 }
12273 buckets[numBuckets] = totalTime / num;
12274 numBuckets++;
12275 numToAverage *= 2;
12276 i += num;
12277 }
12278 if (numBuckets < 1) {
12279 return -1;
12280 }
12281 long averageTime = buckets[numBuckets-1];
12282 for (i=numBuckets-2; i>=0; i--) {
12283 averageTime = (averageTime + buckets[i]) / 2;
12284 }
12285 return averageTime;
12286 */
12287 }
12288
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012289 @Override
12290 public long computeBatteryTimeRemaining(long curTime) {
12291 if (!mOnBattery) {
12292 return -1;
12293 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012294 /* Simple implementation just looks at the average discharge per level across the
12295 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012296 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12297 if (discharge < 2) {
12298 return -1;
12299 }
12300 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12301 if (duration < 1000*1000) {
12302 return -1;
12303 }
12304 long usPerLevel = duration/discharge;
12305 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012306 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012307 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012308 return -1;
12309 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012310 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012311 if (msPerLevel <= 0) {
12312 return -1;
12313 }
12314 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012315 }
12316
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012317 @Override
12318 public LevelStepTracker getDischargeLevelStepTracker() {
12319 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012320 }
12321
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012322 @Override
12323 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12324 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012325 }
12326
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012327 @Override
12328 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012329 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012330 // Not yet working.
12331 return -1;
12332 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012333 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012334 int curLevel = mCurrentBatteryLevel;
12335 int plugLevel = mDischargePlugLevel;
12336 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12337 return -1;
12338 }
12339 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12340 if (duration < 1000*1000) {
12341 return -1;
12342 }
12343 long usPerLevel = duration/(curLevel-plugLevel);
12344 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012345 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012346 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012347 return -1;
12348 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012349 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012350 if (msPerLevel <= 0) {
12351 return -1;
12352 }
12353 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012354 }
12355
Siddharth Raya1fd0572017-11-13 14:20:47 -080012356 /*@hide */
12357 public CellularBatteryStats getCellularBatteryStats() {
12358 CellularBatteryStats s = new CellularBatteryStats();
12359 final int which = STATS_SINCE_CHARGED;
12360 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12361 final ControllerActivityCounter counter = getModemControllerActivity();
12362 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12363 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12364 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12365 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12366 for (int i = 0; i < timeInRatMs.length; i++) {
12367 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12368 }
12369 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12370 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12371 timeInRxSignalStrengthLevelMs[i]
12372 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12373 }
12374 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12375 counter.getTxTimeCounters().length)];
12376 long totalTxTimeMs = 0;
12377 for (int i = 0; i < txTimeMs.length; i++) {
12378 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12379 totalTxTimeMs += txTimeMs[i];
12380 }
12381 final long totalControllerActivityTimeMs
12382 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12383 final long sleepTimeMs
12384 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + totalTxTimeMs);
12385 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12386 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12387 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12388 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12389 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12390 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
12391 s.setSleepTimeMs(sleepTimeMs);
12392 s.setIdleTimeMs(idleTimeMs);
12393 s.setRxTimeMs(rxTimeMs);
12394 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12395 s.setTimeInRatMs(timeInRatMs);
12396 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
12397 s.setTxTimeMs(txTimeMs);
12398 return s;
12399 }
12400
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012401 @Override
12402 public LevelStepTracker getChargeLevelStepTracker() {
12403 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012404 }
12405
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012406 @Override
12407 public LevelStepTracker getDailyChargeLevelStepTracker() {
12408 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012409 }
12410
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012411 @Override
12412 public ArrayList<PackageChange> getDailyPackageChanges() {
12413 return mDailyPackageChanges;
12414 }
12415
Joe Onoratoe1acd632016-02-23 13:25:10 -080012416 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012417 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012418 }
12419
12420 @Override
12421 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012422 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012423 }
12424
12425 @Override
12426 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012427 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012428 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070012429
The Android Open Source Project10592532009-03-18 17:39:46 -070012430 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012431 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012432 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012433 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012434 }
12435 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012436
Evan Millar633a1742009-04-02 16:36:33 -070012437 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012438 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012439 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012440
The Android Open Source Project10592532009-03-18 17:39:46 -070012441 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012442 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012443 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012444 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012445 }
12446 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012447
Evan Millar633a1742009-04-02 16:36:33 -070012448 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012449 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012451
Amith Yamasanie43530a2009-08-21 13:11:37 -070012452 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012453 public int getLowDischargeAmountSinceCharge() {
12454 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012455 int val = mLowDischargeAmountSinceCharge;
12456 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12457 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
12458 }
12459 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012460 }
12461 }
12462
12463 @Override
12464 public int getHighDischargeAmountSinceCharge() {
12465 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012466 int val = mHighDischargeAmountSinceCharge;
12467 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12468 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
12469 }
12470 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012471 }
12472 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012473
12474 @Override
12475 public int getDischargeAmount(int which) {
12476 int dischargeAmount = which == STATS_SINCE_CHARGED
12477 ? getHighDischargeAmountSinceCharge()
12478 : (getDischargeStartLevel() - getDischargeCurrentLevel());
12479 if (dischargeAmount < 0) {
12480 dischargeAmount = 0;
12481 }
12482 return dischargeAmount;
12483 }
12484
Mike Mac2f518a2017-09-19 16:06:03 -070012485 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012486 public int getDischargeAmountScreenOn() {
12487 synchronized(this) {
12488 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070012489 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012490 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12491 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12492 }
12493 return val;
12494 }
12495 }
12496
Mike Mac2f518a2017-09-19 16:06:03 -070012497 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012498 public int getDischargeAmountScreenOnSinceCharge() {
12499 synchronized(this) {
12500 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070012501 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012502 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12503 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12504 }
12505 return val;
12506 }
12507 }
12508
Mike Mac2f518a2017-09-19 16:06:03 -070012509 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012510 public int getDischargeAmountScreenOff() {
12511 synchronized(this) {
12512 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070012513 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012514 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12515 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12516 }
Mike Mac2f518a2017-09-19 16:06:03 -070012517 // For backward compatibility, doze discharge is counted into screen off.
12518 return val + getDischargeAmountScreenDoze();
12519 }
12520 }
12521
12522 @Override
12523 public int getDischargeAmountScreenOffSinceCharge() {
12524 synchronized(this) {
12525 int val = mDischargeAmountScreenOffSinceCharge;
12526 if (mOnBattery && isScreenOff(mScreenState)
12527 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12528 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12529 }
12530 // For backward compatibility, doze discharge is counted into screen off.
12531 return val + getDischargeAmountScreenDozeSinceCharge();
12532 }
12533 }
12534
12535 @Override
12536 public int getDischargeAmountScreenDoze() {
12537 synchronized(this) {
12538 int val = mDischargeAmountScreenDoze;
12539 if (mOnBattery && isScreenDoze(mScreenState)
12540 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
12541 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
12542 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012543 return val;
12544 }
12545 }
12546
Mike Mac2f518a2017-09-19 16:06:03 -070012547 @Override
12548 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012549 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070012550 int val = mDischargeAmountScreenDozeSinceCharge;
12551 if (mOnBattery && isScreenDoze(mScreenState)
12552 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
12553 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012554 }
12555 return val;
12556 }
12557 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012559 /**
12560 * Retrieve the statistics object for a particular uid, creating if needed.
12561 */
12562 public Uid getUidStatsLocked(int uid) {
12563 Uid u = mUidStats.get(uid);
12564 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080012565 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012566 mUidStats.put(uid, u);
12567 }
12568 return u;
12569 }
12570
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012571 /**
12572 * Retrieve the statistics object for a particular uid. Returns null if the object is not
12573 * available.
12574 */
12575 public Uid getAvailableUidStatsLocked(int uid) {
12576 Uid u = mUidStats.get(uid);
12577 return u;
12578 }
12579
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012580 public void onCleanupUserLocked(int userId) {
12581 final int firstUidForUser = UserHandle.getUid(userId, 0);
12582 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
12583 mKernelUidCpuFreqTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
12584 mKernelUidCpuTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012585 if (mKernelSingleUidTimeReader != null) {
12586 mKernelSingleUidTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
12587 }
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012588 }
12589
12590 public void onUserRemovedLocked(int userId) {
12591 final int firstUidForUser = UserHandle.getUid(userId, 0);
12592 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
12593 mUidStats.put(firstUidForUser, null);
12594 mUidStats.put(lastUidForUser, null);
12595 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
12596 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
12597 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
12598 }
12599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012600 /**
12601 * Remove the statistics object for a particular uid.
12602 */
12603 public void removeUidStatsLocked(int uid) {
Adam Lesinskib83ffee2015-05-12 14:43:47 -070012604 mKernelUidCpuTimeReader.removeUid(uid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -070012605 mKernelUidCpuFreqTimeReader.removeUid(uid);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012606 if (mKernelSingleUidTimeReader != null) {
12607 mKernelSingleUidTimeReader.removeUid(uid);
12608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012609 mUidStats.remove(uid);
12610 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070012611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012612 /**
12613 * Retrieve the statistics object for a particular process, creating
12614 * if needed.
12615 */
12616 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012617 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012618 Uid u = getUidStatsLocked(uid);
12619 return u.getProcessStatsLocked(name);
12620 }
12621
12622 /**
12623 * Retrieve the statistics object for a particular process, creating
12624 * if needed.
12625 */
12626 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012627 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012628 Uid u = getUidStatsLocked(uid);
12629 return u.getPackageStatsLocked(pkg);
12630 }
12631
12632 /**
12633 * Retrieve the statistics object for a particular service, creating
12634 * if needed.
12635 */
12636 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012637 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012638 Uid u = getUidStatsLocked(uid);
12639 return u.getServiceStatsLocked(pkg, name);
12640 }
12641
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012642 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012643 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012644 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012645 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012646 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012647
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012648 public boolean trackPerProcStateCpuTimes() {
12649 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
12650 }
12651
12652 public void systemServicesReady(Context context) {
12653 mConstants.startObserving(context.getContentResolver());
12654 }
12655
12656 @VisibleForTesting
12657 public final class Constants extends ContentObserver {
12658 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
12659 = "track_cpu_times_by_proc_state";
12660
12661 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
12662
12663 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
12664
12665 private ContentResolver mResolver;
12666 private final KeyValueListParser mParser = new KeyValueListParser(',');
12667
12668 public Constants(Handler handler) {
12669 super(handler);
12670 }
12671
12672 public void startObserving(ContentResolver resolver) {
12673 mResolver = resolver;
12674 mResolver.registerContentObserver(
12675 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
12676 false /* notifyForDescendants */, this);
12677 updateConstants();
12678 }
12679
12680 @Override
12681 public void onChange(boolean selfChange, Uri uri) {
12682 updateConstants();
12683 }
12684
12685 private void updateConstants() {
12686 synchronized (BatteryStatsImpl.this) {
12687 try {
12688 mParser.setString(Settings.Global.getString(mResolver,
12689 Settings.Global.BATTERY_STATS_CONSTANTS));
12690 } catch (IllegalArgumentException e) {
12691 // Failed to parse the settings string, log this and move on
12692 // with defaults.
12693 Slog.e(TAG, "Bad batterystats settings", e);
12694 }
12695
12696 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
12697 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
12698 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
12699 }
12700 }
12701
12702 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
12703 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
12704 if (isEnabled && !wasEnabled) {
12705 mKernelSingleUidTimeReader.markDataAsStale(true);
12706 mExternalSync.scheduleCpuSyncDueToSettingChange();
12707 }
12708 }
12709
12710 public void dumpLocked(PrintWriter pw) {
12711 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
12712 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
12713 }
12714 }
12715
12716 public void dumpConstantsLocked(PrintWriter pw) {
12717 mConstants.dumpLocked(pw);
12718 }
12719
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012720 Parcel mPendingWrite = null;
12721 final ReentrantLock mWriteLock = new ReentrantLock();
12722
12723 public void writeAsyncLocked() {
12724 writeLocked(false);
12725 }
12726
12727 public void writeSyncLocked() {
12728 writeLocked(true);
12729 }
12730
12731 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012732 if (mFile == null) {
12733 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012734 return;
12735 }
12736
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012737 if (mShuttingDown) {
12738 return;
12739 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012740
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012741 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012742 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080012743 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012744
12745 if (mPendingWrite != null) {
12746 mPendingWrite.recycle();
12747 }
12748 mPendingWrite = out;
12749
12750 if (sync) {
12751 commitPendingDataToDisk();
12752 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012753 BackgroundThread.getHandler().post(new Runnable() {
12754 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012755 commitPendingDataToDisk();
12756 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012757 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012758 }
12759 }
12760
12761 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070012762 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012763 synchronized (this) {
12764 next = mPendingWrite;
12765 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070012766 if (next == null) {
12767 return;
12768 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012769 }
12770
Amith Yamasanid2450862017-02-07 15:58:24 -080012771 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012772 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012773 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012774 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012775 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070012776 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012777 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012778 mFile.commit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012779 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012780 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012781 mFile.rollback();
12782 } finally {
12783 next.recycle();
12784 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070012785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012786 }
12787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012788 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012789 if (mDailyFile != null) {
12790 readDailyStatsLocked();
12791 }
12792
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012793 if (mFile == null) {
12794 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012795 return;
12796 }
12797
12798 mUidStats.clear();
12799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012800 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012801 File file = mFile.chooseForRead();
12802 if (!file.exists()) {
12803 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012804 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012805 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012806
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012807 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012808 Parcel in = Parcel.obtain();
12809 in.unmarshall(raw, 0, raw.length);
12810 in.setDataPosition(0);
12811 stream.close();
12812
12813 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080012814 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012815 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012816 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012817 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012818
Dianne Hackborncd0e3352014-08-07 17:08:09 -070012819 mEndPlatformVersion = Build.ID;
12820
Dianne Hackborne5167ca2014-03-08 14:39:10 -080012821 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012822 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080012823 final long elapsedRealtime = mClocks.elapsedRealtime();
12824 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080012825 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012826 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080012827 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012828 addHistoryBufferLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
12829 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070012830 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012831
12832 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012833 }
12834
12835 public int describeContents() {
12836 return 0;
12837 }
12838
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012839 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070012840 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012841
12842 mHistoryBuffer.setDataSize(0);
12843 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080012844 mHistoryTagPool.clear();
12845 mNextHistoryTagIdx = 0;
12846 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080012847
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080012848 int numTags = in.readInt();
12849 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080012850 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080012851 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012852 if (str == null) {
12853 throw new ParcelFormatException("null history tag string");
12854 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080012855 int uid = in.readInt();
12856 HistoryTag tag = new HistoryTag();
12857 tag.string = str;
12858 tag.uid = uid;
12859 tag.poolIdx = idx;
12860 mHistoryTagPool.put(tag, idx);
12861 if (idx >= mNextHistoryTagIdx) {
12862 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080012863 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080012864 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080012865 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012866
12867 int bufSize = in.readInt();
12868 int curPos = in.dataPosition();
12869 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012870 throw new ParcelFormatException("File corrupt: history data buffer too large " +
12871 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012872 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012873 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
12874 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012875 } else {
12876 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
12877 + " bytes at " + curPos);
12878 mHistoryBuffer.appendFrom(in, curPos, bufSize);
12879 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012880 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012881
Dianne Hackbornae384452011-06-28 12:33:48 -070012882 if (andOldHistory) {
12883 readOldHistory(in);
12884 }
12885
12886 if (DEBUG_HISTORY) {
12887 StringBuilder sb = new StringBuilder(128);
12888 sb.append("****************** OLD mHistoryBaseTime: ");
12889 TimeUtils.formatDuration(mHistoryBaseTime, sb);
12890 Slog.i(TAG, sb.toString());
12891 }
12892 mHistoryBaseTime = historyBaseTime;
12893 if (DEBUG_HISTORY) {
12894 StringBuilder sb = new StringBuilder(128);
12895 sb.append("****************** NEW mHistoryBaseTime: ");
12896 TimeUtils.formatDuration(mHistoryBaseTime, sb);
12897 Slog.i(TAG, sb.toString());
12898 }
12899
12900 // We are just arbitrarily going to insert 1 minute from the sample of
12901 // the last run until samples in this run.
12902 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080012903 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012904 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070012905 if (DEBUG_HISTORY) {
12906 StringBuilder sb = new StringBuilder(128);
12907 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
12908 TimeUtils.formatDuration(mHistoryBaseTime, sb);
12909 Slog.i(TAG, sb.toString());
12910 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070012911 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012912 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012913
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012914 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070012915 if (!USE_OLD_HISTORY) {
12916 return;
12917 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012918 mHistory = mHistoryEnd = mHistoryCache = null;
12919 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070012920 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012921 HistoryItem rec = new HistoryItem(time, in);
12922 addHistoryRecordLocked(rec);
12923 }
12924 }
12925
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012926 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070012927 if (DEBUG_HISTORY) {
12928 StringBuilder sb = new StringBuilder(128);
12929 sb.append("****************** WRITING mHistoryBaseTime: ");
12930 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070012931 sb.append(" mLastHistoryElapsedRealtime: ");
12932 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070012933 Slog.i(TAG, sb.toString());
12934 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012935 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012936 if (!inclData) {
12937 out.writeInt(0);
12938 out.writeInt(0);
12939 return;
12940 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080012941 out.writeInt(mHistoryTagPool.size());
12942 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
12943 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080012944 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080012945 out.writeString(tag.string);
12946 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080012947 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012948 out.writeInt(mHistoryBuffer.dataSize());
12949 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
12950 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
12951 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070012952
12953 if (andOldHistory) {
12954 writeOldHistory(out);
12955 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012956 }
12957
12958 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070012959 if (!USE_OLD_HISTORY) {
12960 return;
12961 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012962 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012963 while (rec != null) {
12964 if (rec.time >= 0) rec.writeToParcel(out, 0);
12965 rec = rec.next;
12966 }
12967 out.writeLong(-1);
12968 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012969
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012970 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012971 final int version = in.readInt();
12972 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012973 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012974 + ", expected " + VERSION + "; erasing old stats");
12975 return;
12976 }
12977
Dianne Hackbornae384452011-06-28 12:33:48 -070012978 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012980 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012981 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012982 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080012983 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070012984 mStartPlatformVersion = in.readString();
12985 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012986 mOnBatteryTimeBase.readSummaryFromParcel(in);
12987 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012988 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012989 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070012990 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012991 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012992 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070012993 mMinLearnedBatteryCapacity = in.readInt();
12994 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012995 mLowDischargeAmountSinceCharge = in.readInt();
12996 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012997 mDischargeAmountScreenOnSinceCharge = in.readInt();
12998 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070012999 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013000 mDischargeStepTracker.readFromParcel(in);
13001 mChargeStepTracker.readFromParcel(in);
13002 mDailyDischargeStepTracker.readFromParcel(in);
13003 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013004 mDischargeCounter.readSummaryFromParcelLocked(in);
13005 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013006 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013007 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13008 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013009 int NPKG = in.readInt();
13010 if (NPKG > 0) {
13011 mDailyPackageChanges = new ArrayList<>(NPKG);
13012 while (NPKG > 0) {
13013 NPKG--;
13014 PackageChange pc = new PackageChange();
13015 pc.mPackageName = in.readString();
13016 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013017 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013018 mDailyPackageChanges.add(pc);
13019 }
13020 } else {
13021 mDailyPackageChanges = null;
13022 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013023 mDailyStartTime = in.readLong();
13024 mNextMinDailyDeadline = in.readLong();
13025 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013027 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013028
Jeff Browne95c3cd2014-05-02 16:59:26 -070013029 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013030 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013031 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013032 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13033 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13034 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013035 mInteractive = false;
13036 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013037 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013038 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013039 mLongestLightIdleTime = in.readLong();
13040 mLongestFullIdleTime = in.readLong();
13041 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13042 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13043 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013044 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013045 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013046 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013047 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13048 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013049 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013050 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13051 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13052 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013053 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013054 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13055 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013056 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013057 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013058 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013059 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013060 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013061 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13062 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013063 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013064 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013065 mWifiOn = false;
13066 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013067 mGlobalWifiRunning = false;
13068 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013069 for (int i=0; i<NUM_WIFI_STATES; i++) {
13070 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13071 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013072 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13073 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13074 }
13075 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13076 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13077 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013078 mWifiActivity.readSummaryFromParcel(in);
13079 mBluetoothActivity.readSummaryFromParcel(in);
13080 mModemActivity.readSummaryFromParcel(in);
13081 mHasWifiReporting = in.readInt() != 0;
13082 mHasBluetoothReporting = in.readInt() != 0;
13083 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013084
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013085 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013086 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013087 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013088 mCameraOnNesting = 0;
13089 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013090 mBluetoothScanNesting = 0;
13091 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013092
Bookatz50df7112017-08-04 14:53:26 -070013093 int NRPMS = in.readInt();
13094 if (NRPMS > 10000) {
13095 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13096 }
13097 for (int irpm = 0; irpm < NRPMS; irpm++) {
13098 if (in.readInt() != 0) {
13099 String rpmName = in.readString();
13100 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13101 }
13102 }
13103 int NSORPMS = in.readInt();
13104 if (NSORPMS > 10000) {
13105 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13106 }
13107 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13108 if (in.readInt() != 0) {
13109 String rpmName = in.readString();
13110 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13111 }
13112 }
13113
Evan Millarc64edde2009-04-18 12:26:32 -070013114 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013115 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013116 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013117 }
Evan Millarc64edde2009-04-18 12:26:32 -070013118 for (int ikw = 0; ikw < NKW; ikw++) {
13119 if (in.readInt() != 0) {
13120 String kwltName = in.readString();
13121 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13122 }
13123 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013124
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013125 int NWR = in.readInt();
13126 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013127 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013128 }
13129 for (int iwr = 0; iwr < NWR; iwr++) {
13130 if (in.readInt() != 0) {
13131 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013132 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013133 }
13134 }
13135
James Carr3a226052016-07-01 14:49:52 -070013136 int NMS = in.readInt();
13137 for (int ims = 0; ims < NMS; ims++) {
13138 if (in.readInt() != 0) {
13139 long kmstName = in.readLong();
13140 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13141 }
13142 }
13143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013144 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013145 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013146 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013148 for (int iu = 0; iu < NU; iu++) {
13149 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013150 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013151 mUidStats.put(uid, u);
13152
Bookatz867c0d72017-03-07 18:23:42 -080013153 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013154 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013155
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013156 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013157 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013158 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013159 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013160 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013161 if (in.readInt() != 0) {
13162 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13163 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013164 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013165 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013166 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013167 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013168 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13169 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13170 if (in.readInt() != 0) {
13171 u.makeWifiBatchedScanBin(i, null);
13172 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13173 }
13174 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013175 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013176 if (in.readInt() != 0) {
13177 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13178 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013179 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013180 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013181 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013182 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013183 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13184 }
13185 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013186 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13187 }
13188 if (in.readInt() != 0) {
13189 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13190 }
13191 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013192 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13193 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013194 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013195 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13196 }
13197 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013198 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13199 }
13200 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013201 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13202 }
Bookatz956f36bf2017-04-28 09:48:17 -070013203 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013204 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13205 }
13206 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013207 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13208 }
Bookatzb1f04f32017-05-19 13:57:32 -070013209 if (in.readInt() != 0) {
13210 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13211 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013212 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013213 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13214 if (in.readInt() != 0) {
13215 u.makeProcessState(i, null);
13216 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13217 }
13218 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013219 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013220 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013221 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013222
Dianne Hackborn617f8772009-03-31 15:04:46 -070013223 if (in.readInt() != 0) {
13224 if (u.mUserActivityCounters == null) {
13225 u.initUserActivityLocked();
13226 }
13227 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13228 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13229 }
13230 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013231
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013232 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013233 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013234 u.initNetworkActivityLocked();
13235 }
13236 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013237 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13238 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013239 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013240 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13241 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013242 }
13243
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013244 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13245 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13246
Adam Lesinski6832f392015-09-05 18:05:40 -070013247 if (in.readInt() != 0) {
13248 final int numClusters = in.readInt();
13249 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13250 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013251 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013252
Sudheer Shankaaf857412017-07-21 00:14:24 -070013253 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013254 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013255 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013256 final int NSB = in.readInt();
13257 if (mPowerProfile != null &&
13258 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13259 throw new ParcelFormatException("File corrupt: too many speed bins " +
13260 NSB);
13261 }
13262
Sudheer Shankaaf857412017-07-21 00:14:24 -070013263 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070013264 for (int speed = 0; speed < NSB; speed++) {
13265 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013266 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070013267 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013268 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070013269 }
13270 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070013271 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013272 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070013273 }
13274 }
13275 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013276 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013277 }
13278
Sudheer Shanka59f5c002017-05-15 10:57:15 -070013279 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13280 in, mOnBatteryTimeBase);
13281 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13282 in, mOnBatteryScreenOffTimeBase);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013283 int length = in.readInt();
13284 if (length == Uid.NUM_PROCESS_STATE) {
13285 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
13286 for (int procState = 0; procState < length; ++procState) {
13287 u.mProcStateTimeMs[procState]
13288 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13289 in, mOnBatteryTimeBase);
13290 }
13291 } else {
13292 u.mProcStateTimeMs = null;
13293 }
13294 length = in.readInt();
13295 if (length == Uid.NUM_PROCESS_STATE) {
13296 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
13297 for (int procState = 0; procState < length; ++procState) {
13298 u.mProcStateScreenOffTimeMs[procState]
13299 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13300 in, mOnBatteryScreenOffTimeBase);
13301 }
13302 } else {
13303 u.mProcStateScreenOffTimeMs = null;
13304 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070013305
13306 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070013307 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13308 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
13309 } else {
13310 u.mMobileRadioApWakeupCount = null;
13311 }
13312
13313 if (in.readInt() != 0) {
13314 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13315 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
13316 } else {
13317 u.mWifiRadioApWakeupCount = null;
13318 }
13319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013320 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013321 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013322 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013324 for (int iw = 0; iw < NW; iw++) {
13325 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013326 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013327 }
13328
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013329 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013330 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013331 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013332 }
13333 for (int is = 0; is < NS; is++) {
13334 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013335 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013336 }
13337
13338 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013339 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013340 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013341 }
13342 for (int ij = 0; ij < NJ; ij++) {
13343 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013344 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013345 }
13346
Dianne Hackborn94326cb2017-06-28 16:17:20 -070013347 u.readJobCompletionsFromParcelLocked(in);
13348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013349 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013350 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013351 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013353 for (int is = 0; is < NP; is++) {
13354 int seNumber = in.readInt();
13355 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080013356 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013357 }
13358 }
13359
13360 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013361 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013362 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013364 for (int ip = 0; ip < NP; ip++) {
13365 String procName = in.readString();
13366 Uid.Proc p = u.getProcessStatsLocked(procName);
13367 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013368 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013369 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013370 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013371 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
13372 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013373 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013374 }
13375
13376 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013377 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013378 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013380 for (int ip = 0; ip < NP; ip++) {
13381 String pkgName = in.readString();
13382 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013383 final int NWA = in.readInt();
13384 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013385 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013386 }
13387 p.mWakeupAlarms.clear();
13388 for (int iwa=0; iwa<NWA; iwa++) {
13389 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070013390 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013391 c.readSummaryFromParcelLocked(in);
13392 p.mWakeupAlarms.put(tag, c);
13393 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013394 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013395 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013396 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013398 for (int is = 0; is < NS; is++) {
13399 String servName = in.readString();
13400 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
13401 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013402 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013403 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013404 }
13405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013406 }
13407 }
13408
13409 /**
13410 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
13411 * disk. This format does not allow a lossless round-trip.
13412 *
13413 * @param out the Parcel to be written to.
13414 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013415 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013416 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013417
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013418 // Pull the clock time. This may update the time and make a new history entry
13419 // if we had originally pulled a time before the RTC was set.
13420 long startClockTime = getStartClockTime();
13421
Joe Onoratoabded112016-02-08 16:49:39 -080013422 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
13423 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013424
13425 out.writeInt(VERSION);
13426
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013427 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013429 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013430 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013431 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013432 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013433 out.writeString(mStartPlatformVersion);
13434 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013435 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
13436 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013437 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013438 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070013439 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013440 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013441 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070013442 out.writeInt(mMinLearnedBatteryCapacity);
13443 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080013444 out.writeInt(getLowDischargeAmountSinceCharge());
13445 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013446 out.writeInt(getDischargeAmountScreenOnSinceCharge());
13447 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070013448 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013449 mDischargeStepTracker.writeToParcel(out);
13450 mChargeStepTracker.writeToParcel(out);
13451 mDailyDischargeStepTracker.writeToParcel(out);
13452 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070013453 mDischargeCounter.writeSummaryFromParcelLocked(out);
13454 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070013455 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080013456 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
13457 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013458 if (mDailyPackageChanges != null) {
13459 final int NPKG = mDailyPackageChanges.size();
13460 out.writeInt(NPKG);
13461 for (int i=0; i<NPKG; i++) {
13462 PackageChange pc = mDailyPackageChanges.get(i);
13463 out.writeString(pc.mPackageName);
13464 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070013465 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013466 }
13467 } else {
13468 out.writeInt(0);
13469 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013470 out.writeLong(mDailyStartTime);
13471 out.writeLong(mNextMinDailyDeadline);
13472 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013473
13474 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070013475 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013476 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013477 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013478 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013479 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013480 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013481 out.writeLong(mLongestLightIdleTime);
13482 out.writeLong(mLongestFullIdleTime);
13483 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13484 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13485 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013486 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013487 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080013488 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013489 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013490 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013491 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013492 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013493 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013494 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013495 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013496 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
13497 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013498 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013499 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13500 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013501 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013502 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
13503 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013504 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013505 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13506 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013507 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013508 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013509 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013510 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13511 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13512 }
13513 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13514 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13515 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013516 mWifiActivity.writeSummaryToParcel(out);
13517 mBluetoothActivity.writeSummaryToParcel(out);
13518 mModemActivity.writeSummaryToParcel(out);
13519 out.writeInt(mHasWifiReporting ? 1 : 0);
13520 out.writeInt(mHasBluetoothReporting ? 1 : 0);
13521 out.writeInt(mHasModemReporting ? 1 : 0);
13522
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013523 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013524 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013525 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013526 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013527
Bookatz50df7112017-08-04 14:53:26 -070013528 out.writeInt(mRpmStats.size());
13529 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
13530 Timer rpmt = ent.getValue();
13531 if (rpmt != null) {
13532 out.writeInt(1);
13533 out.writeString(ent.getKey());
13534 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13535 } else {
13536 out.writeInt(0);
13537 }
13538 }
13539 out.writeInt(mScreenOffRpmStats.size());
13540 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
13541 Timer rpmt = ent.getValue();
13542 if (rpmt != null) {
13543 out.writeInt(1);
13544 out.writeString(ent.getKey());
13545 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13546 } else {
13547 out.writeInt(0);
13548 }
13549 }
13550
Evan Millarc64edde2009-04-18 12:26:32 -070013551 out.writeInt(mKernelWakelockStats.size());
13552 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
13553 Timer kwlt = ent.getValue();
13554 if (kwlt != null) {
13555 out.writeInt(1);
13556 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013557 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13558 } else {
13559 out.writeInt(0);
13560 }
13561 }
13562
13563 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013564 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
13565 SamplingTimer timer = ent.getValue();
13566 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013567 out.writeInt(1);
13568 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013569 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070013570 } else {
13571 out.writeInt(0);
13572 }
13573 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013574
James Carr3a226052016-07-01 14:49:52 -070013575 out.writeInt(mKernelMemoryStats.size());
13576 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
13577 Timer kmt = mKernelMemoryStats.valueAt(i);
13578 if (kmt != null) {
13579 out.writeInt(1);
13580 out.writeLong(mKernelMemoryStats.keyAt(i));
13581 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13582 } else {
13583 out.writeInt(0);
13584 }
13585 }
13586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013587 final int NU = mUidStats.size();
13588 out.writeInt(NU);
13589 for (int iu = 0; iu < NU; iu++) {
13590 out.writeInt(mUidStats.keyAt(iu));
13591 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013592
Bookatz867c0d72017-03-07 18:23:42 -080013593 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070013594 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080013595
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013596 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013597 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013598 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013599 } else {
13600 out.writeInt(0);
13601 }
13602 if (u.mFullWifiLockTimer != null) {
13603 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013604 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013605 } else {
13606 out.writeInt(0);
13607 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013608 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013609 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013610 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013611 } else {
13612 out.writeInt(0);
13613 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013614 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13615 if (u.mWifiBatchedScanTimer[i] != null) {
13616 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013617 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070013618 } else {
13619 out.writeInt(0);
13620 }
13621 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013622 if (u.mWifiMulticastTimer != null) {
13623 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013624 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013625 } else {
13626 out.writeInt(0);
13627 }
13628 if (u.mAudioTurnedOnTimer != null) {
13629 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013630 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013631 } else {
13632 out.writeInt(0);
13633 }
13634 if (u.mVideoTurnedOnTimer != null) {
13635 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013636 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013637 } else {
13638 out.writeInt(0);
13639 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013640 if (u.mFlashlightTurnedOnTimer != null) {
13641 out.writeInt(1);
13642 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13643 } else {
13644 out.writeInt(0);
13645 }
13646 if (u.mCameraTurnedOnTimer != null) {
13647 out.writeInt(1);
13648 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13649 } else {
13650 out.writeInt(0);
13651 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013652 if (u.mForegroundActivityTimer != null) {
13653 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013654 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013655 } else {
13656 out.writeInt(0);
13657 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013658 if (u.mForegroundServiceTimer != null) {
13659 out.writeInt(1);
13660 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13661 } else {
13662 out.writeInt(0);
13663 }
Bookatzc8c44962017-05-11 12:12:54 -070013664 if (u.mAggregatedPartialWakelockTimer != null) {
13665 out.writeInt(1);
13666 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13667 } else {
13668 out.writeInt(0);
13669 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013670 if (u.mBluetoothScanTimer != null) {
13671 out.writeInt(1);
13672 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13673 } else {
13674 out.writeInt(0);
13675 }
Bookatzb1f04f32017-05-19 13:57:32 -070013676 if (u.mBluetoothUnoptimizedScanTimer != null) {
13677 out.writeInt(1);
13678 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13679 } else {
13680 out.writeInt(0);
13681 }
Bookatz956f36bf2017-04-28 09:48:17 -070013682 if (u.mBluetoothScanResultCounter != null) {
13683 out.writeInt(1);
13684 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
13685 } else {
13686 out.writeInt(0);
13687 }
Bookatzb1f04f32017-05-19 13:57:32 -070013688 if (u.mBluetoothScanResultBgCounter != null) {
13689 out.writeInt(1);
13690 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
13691 } else {
13692 out.writeInt(0);
13693 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070013694 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13695 if (u.mProcessStateTimer[i] != null) {
13696 out.writeInt(1);
13697 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13698 } else {
13699 out.writeInt(0);
13700 }
13701 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013702 if (u.mVibratorOnTimer != null) {
13703 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013704 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013705 } else {
13706 out.writeInt(0);
13707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013708
Dianne Hackborn617f8772009-03-31 15:04:46 -070013709 if (u.mUserActivityCounters == null) {
13710 out.writeInt(0);
13711 } else {
13712 out.writeInt(1);
13713 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13714 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
13715 }
13716 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013717
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013718 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013719 out.writeInt(0);
13720 } else {
13721 out.writeInt(1);
13722 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013723 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
13724 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013725 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013726 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
13727 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013728 }
13729
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013730 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
13731 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
13732
Sudheer Shankaaf857412017-07-21 00:14:24 -070013733 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013734 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013735 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
13736 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013737 if (cpuSpeeds != null) {
13738 out.writeInt(1);
13739 out.writeInt(cpuSpeeds.length);
13740 for (LongSamplingCounter c : cpuSpeeds) {
13741 if (c != null) {
13742 out.writeInt(1);
13743 c.writeSummaryFromParcelLocked(out);
13744 } else {
13745 out.writeInt(0);
13746 }
13747 }
13748 } else {
13749 out.writeInt(0);
13750 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013751 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013752 } else {
13753 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013754 }
13755
Sudheer Shanka59f5c002017-05-15 10:57:15 -070013756 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
13757 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070013758
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013759 if (u.mProcStateTimeMs != null) {
13760 out.writeInt(u.mProcStateTimeMs.length);
13761 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
13762 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
13763 }
13764 } else {
13765 out.writeInt(0);
13766 }
13767 if (u.mProcStateScreenOffTimeMs != null) {
13768 out.writeInt(u.mProcStateScreenOffTimeMs.length);
13769 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
13770 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
13771 }
13772 } else {
13773 out.writeInt(0);
13774 }
13775
Adam Lesinski5f056f62016-07-14 16:56:08 -070013776 if (u.mMobileRadioApWakeupCount != null) {
13777 out.writeInt(1);
13778 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
13779 } else {
13780 out.writeInt(0);
13781 }
13782
13783 if (u.mWifiRadioApWakeupCount != null) {
13784 out.writeInt(1);
13785 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
13786 } else {
13787 out.writeInt(0);
13788 }
13789
Dianne Hackbornd953c532014-08-16 18:17:38 -070013790 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
13791 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013792 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070013793 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070013794 out.writeString(wakeStats.keyAt(iw));
13795 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070013796 if (wl.mTimerFull != null) {
13797 out.writeInt(1);
13798 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13799 } else {
13800 out.writeInt(0);
13801 }
13802 if (wl.mTimerPartial != null) {
13803 out.writeInt(1);
13804 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13805 } else {
13806 out.writeInt(0);
13807 }
13808 if (wl.mTimerWindow != null) {
13809 out.writeInt(1);
13810 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13811 } else {
13812 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013813 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070013814 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070013815 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070013816 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070013817 } else {
13818 out.writeInt(0);
13819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013820 }
13821
Bookatz2bffb5b2017-04-13 11:59:33 -070013822 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013823 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013824 out.writeInt(NS);
13825 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070013826 out.writeString(syncStats.keyAt(is));
13827 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013828 }
13829
Bookatzaa4594a2017-03-24 12:39:56 -070013830 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013831 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013832 out.writeInt(NJ);
13833 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070013834 out.writeString(jobStats.keyAt(ij));
13835 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013836 }
13837
Dianne Hackborn94326cb2017-06-28 16:17:20 -070013838 u.writeJobCompletionsToParcelLocked(out);
13839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013840 int NSE = u.mSensorStats.size();
13841 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070013842 for (int ise=0; ise<NSE; ise++) {
13843 out.writeInt(u.mSensorStats.keyAt(ise));
13844 Uid.Sensor se = u.mSensorStats.valueAt(ise);
13845 if (se.mTimer != null) {
13846 out.writeInt(1);
13847 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13848 } else {
13849 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013850 }
13851 }
13852
13853 int NP = u.mProcessStats.size();
13854 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070013855 for (int ip=0; ip<NP; ip++) {
13856 out.writeString(u.mProcessStats.keyAt(ip));
13857 Uid.Proc ps = u.mProcessStats.valueAt(ip);
13858 out.writeLong(ps.mUserTime);
13859 out.writeLong(ps.mSystemTime);
13860 out.writeLong(ps.mForegroundTime);
13861 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013862 out.writeInt(ps.mNumCrashes);
13863 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070013864 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013865 }
13866
13867 NP = u.mPackageStats.size();
13868 out.writeInt(NP);
13869 if (NP > 0) {
13870 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
13871 : u.mPackageStats.entrySet()) {
13872 out.writeString(ent.getKey());
13873 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013874 final int NWA = ps.mWakeupAlarms.size();
13875 out.writeInt(NWA);
13876 for (int iwa=0; iwa<NWA; iwa++) {
13877 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
13878 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
13879 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013880 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013881 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013882 for (int is=0; is<NS; is++) {
13883 out.writeString(ps.mServiceStats.keyAt(is));
13884 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
13885 long time = ss.getStartTimeToNowLocked(
13886 mOnBatteryTimeBase.getUptime(NOW_SYS));
13887 out.writeLong(time);
13888 out.writeInt(ss.mStarts);
13889 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013890 }
13891 }
13892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013893 }
13894 }
13895
13896 public void readFromParcel(Parcel in) {
13897 readFromParcelLocked(in);
13898 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013900 void readFromParcelLocked(Parcel in) {
13901 int magic = in.readInt();
13902 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013903 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013904 }
13905
Dianne Hackbornae384452011-06-28 12:33:48 -070013906 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013908 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013909 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013910 mStartPlatformVersion = in.readString();
13911 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013912 mUptime = in.readLong();
13913 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013914 mRealtime = in.readLong();
13915 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013916 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013917 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013918 mMinLearnedBatteryCapacity = in.readInt();
13919 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013920 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013921 mOnBatteryTimeBase.readFromParcel(in);
13922 mOnBatteryScreenOffTimeBase.readFromParcel(in);
13923
Jeff Browne95c3cd2014-05-02 16:59:26 -070013924 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080013925 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070013926 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013927 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080013928 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
13929 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013930 }
Dianne Hackborn29325132014-05-21 15:01:03 -070013931 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080013932 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013933 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080013934 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
13935 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013936 mLongestLightIdleTime = in.readLong();
13937 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080013938 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
13939 mOnBatteryTimeBase, in);
13940 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
13941 mOnBatteryTimeBase, in);
13942 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
13943 mOnBatteryTimeBase, in);
13944 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
13945 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013946 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080013947 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013948 null, mOnBatteryTimeBase, in);
13949 }
Joe Onoratoabded112016-02-08 16:49:39 -080013950 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
13951 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013952 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080013953 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013954 null, mOnBatteryTimeBase, in);
13955 }
13956 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
13957 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
13958 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
13959 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013960 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080013961 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
13962 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070013963 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080013964 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013965 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013966 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
13967 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013968 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
13969 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013970 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013971 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080013972 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013973 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080013974 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
13975 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013976 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080013977 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013978 null, mOnBatteryTimeBase, in);
13979 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013980 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080013981 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070013982 null, mOnBatteryTimeBase, in);
13983 }
13984 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080013985 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070013986 null, mOnBatteryTimeBase, in);
13987 }
Adam Lesinski33dac552015-03-09 15:24:48 -070013988
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013989 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
13990 NUM_WIFI_TX_LEVELS, in);
13991 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
13992 NUM_BT_TX_LEVELS, in);
13993 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
13994 ModemActivityInfo.TX_POWER_LEVELS, in);
13995 mHasWifiReporting = in.readInt() != 0;
13996 mHasBluetoothReporting = in.readInt() != 0;
13997 mHasModemReporting = in.readInt() != 0;
13998
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013999 mNumConnectivityChange = in.readInt();
14000 mLoadedNumConnectivityChange = in.readInt();
14001 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014002 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014003 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014004 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014005 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014006 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014007 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014008 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014009 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014010 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014011 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014012 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014013 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014014 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014015 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014016 mLowDischargeAmountSinceCharge = in.readInt();
14017 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014018 mDischargeAmountScreenOn = in.readInt();
14019 mDischargeAmountScreenOnSinceCharge = in.readInt();
14020 mDischargeAmountScreenOff = in.readInt();
14021 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014022 mDischargeAmountScreenDoze = in.readInt();
14023 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014024 mDischargeStepTracker.readFromParcel(in);
14025 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014026 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014027 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14028 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014029 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14030 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014031 mLastWriteTime = in.readLong();
14032
Bookatz50df7112017-08-04 14:53:26 -070014033 mRpmStats.clear();
14034 int NRPMS = in.readInt();
14035 for (int irpm = 0; irpm < NRPMS; irpm++) {
14036 if (in.readInt() != 0) {
14037 String rpmName = in.readString();
14038 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14039 mRpmStats.put(rpmName, rpmt);
14040 }
14041 }
14042 mScreenOffRpmStats.clear();
14043 int NSORPMS = in.readInt();
14044 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14045 if (in.readInt() != 0) {
14046 String rpmName = in.readString();
14047 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14048 mScreenOffRpmStats.put(rpmName, rpmt);
14049 }
14050 }
14051
Evan Millarc64edde2009-04-18 12:26:32 -070014052 mKernelWakelockStats.clear();
14053 int NKW = in.readInt();
14054 for (int ikw = 0; ikw < NKW; ikw++) {
14055 if (in.readInt() != 0) {
14056 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014057 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014058 mKernelWakelockStats.put(wakelockName, kwlt);
14059 }
14060 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014061
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014062 mWakeupReasonStats.clear();
14063 int NWR = in.readInt();
14064 for (int iwr = 0; iwr < NWR; iwr++) {
14065 if (in.readInt() != 0) {
14066 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014067 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014068 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014069 }
14070 }
14071
James Carr3a226052016-07-01 14:49:52 -070014072 mKernelMemoryStats.clear();
14073 int nmt = in.readInt();
14074 for (int imt = 0; imt < nmt; imt++) {
14075 if (in.readInt() != 0) {
14076 Long bucket = in.readLong();
14077 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14078 mKernelMemoryStats.put(bucket, kmt);
14079 }
14080 }
14081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014082 mPartialTimers.clear();
14083 mFullTimers.clear();
14084 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014085 mWifiRunningTimers.clear();
14086 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014087 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014088 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014089 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014090 mAudioTurnedOnTimers.clear();
14091 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014092 mFlashlightTurnedOnTimers.clear();
14093 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014094
14095 int numUids = in.readInt();
14096 mUidStats.clear();
14097 for (int i = 0; i < numUids; i++) {
14098 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014099 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014100 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014101 mUidStats.append(uid, u);
14102 }
14103 }
14104
14105 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014106 writeToParcelLocked(out, true, flags);
14107 }
14108
14109 public void writeToParcelWithoutUids(Parcel out, int flags) {
14110 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014111 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014112
14113 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014114 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014115 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014116 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014117
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014118 // Pull the clock time. This may update the time and make a new history entry
14119 // if we had originally pulled a time before the RTC was set.
14120 long startClockTime = getStartClockTime();
14121
Joe Onoratoabded112016-02-08 16:49:39 -080014122 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14123 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014124 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14125 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014127 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014128
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014129 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014131 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014132 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014133 out.writeString(mStartPlatformVersion);
14134 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014135 out.writeLong(mUptime);
14136 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014137 out.writeLong(mRealtime);
14138 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014139 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014140 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014141 out.writeInt(mMinLearnedBatteryCapacity);
14142 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014143 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14144 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14145
14146 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014147 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014148 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14149 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14150 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014151 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014152 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014153 out.writeLong(mLongestLightIdleTime);
14154 out.writeLong(mLongestFullIdleTime);
14155 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14156 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14157 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014158 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014159 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14160 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14161 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14162 }
14163 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14164 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14165 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14166 }
14167 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14168 mNetworkByteActivityCounters[i].writeToParcel(out);
14169 mNetworkPacketActivityCounters[i].writeToParcel(out);
14170 }
14171 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14172 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014173 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014174 mMobileRadioActiveUnknownTime.writeToParcel(out);
14175 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014176 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014177 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14178 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14179 for (int i=0; i<NUM_WIFI_STATES; i++) {
14180 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14181 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014182 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14183 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14184 }
14185 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14186 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14187 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014188 mWifiActivity.writeToParcel(out, 0);
14189 mBluetoothActivity.writeToParcel(out, 0);
14190 mModemActivity.writeToParcel(out, 0);
14191 out.writeInt(mHasWifiReporting ? 1 : 0);
14192 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14193 out.writeInt(mHasModemReporting ? 1 : 0);
14194
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014195 out.writeInt(mNumConnectivityChange);
14196 out.writeInt(mLoadedNumConnectivityChange);
14197 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014198 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014199 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014200 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014201 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014202 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014203 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014204 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014205 out.writeInt(mLowDischargeAmountSinceCharge);
14206 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014207 out.writeInt(mDischargeAmountScreenOn);
14208 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14209 out.writeInt(mDischargeAmountScreenOff);
14210 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014211 out.writeInt(mDischargeAmountScreenDoze);
14212 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014213 mDischargeStepTracker.writeToParcel(out);
14214 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014215 mDischargeCounter.writeToParcel(out);
14216 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014217 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080014218 mDischargeLightDozeCounter.writeToParcel(out);
14219 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014220 out.writeLong(mLastWriteTime);
14221
Bookatz50df7112017-08-04 14:53:26 -070014222 out.writeInt(mRpmStats.size());
14223 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14224 SamplingTimer rpmt = ent.getValue();
14225 if (rpmt != null) {
14226 out.writeInt(1);
14227 out.writeString(ent.getKey());
14228 rpmt.writeToParcel(out, uSecRealtime);
14229 } else {
14230 out.writeInt(0);
14231 }
14232 }
14233 out.writeInt(mScreenOffRpmStats.size());
14234 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14235 SamplingTimer rpmt = ent.getValue();
14236 if (rpmt != null) {
14237 out.writeInt(1);
14238 out.writeString(ent.getKey());
14239 rpmt.writeToParcel(out, uSecRealtime);
14240 } else {
14241 out.writeInt(0);
14242 }
14243 }
14244
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014245 if (inclUids) {
14246 out.writeInt(mKernelWakelockStats.size());
14247 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14248 SamplingTimer kwlt = ent.getValue();
14249 if (kwlt != null) {
14250 out.writeInt(1);
14251 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014252 kwlt.writeToParcel(out, uSecRealtime);
14253 } else {
14254 out.writeInt(0);
14255 }
14256 }
14257 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014258 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14259 SamplingTimer timer = ent.getValue();
14260 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014261 out.writeInt(1);
14262 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014263 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014264 } else {
14265 out.writeInt(0);
14266 }
Evan Millarc64edde2009-04-18 12:26:32 -070014267 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014268 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070014269 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014270 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070014271 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070014272
James Carr3a226052016-07-01 14:49:52 -070014273 out.writeInt(mKernelMemoryStats.size());
14274 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14275 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
14276 if (kmt != null) {
14277 out.writeInt(1);
14278 out.writeLong(mKernelMemoryStats.keyAt(i));
14279 kmt.writeToParcel(out, uSecRealtime);
14280 } else {
14281 out.writeInt(0);
14282 }
14283 }
14284
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014285 if (inclUids) {
14286 int size = mUidStats.size();
14287 out.writeInt(size);
14288 for (int i = 0; i < size; i++) {
14289 out.writeInt(mUidStats.keyAt(i));
14290 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014291
Bookatz867c0d72017-03-07 18:23:42 -080014292 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014293 }
14294 } else {
14295 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014296 }
14297 }
14298
14299 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
14300 new Parcelable.Creator<BatteryStatsImpl>() {
14301 public BatteryStatsImpl createFromParcel(Parcel in) {
14302 return new BatteryStatsImpl(in);
14303 }
14304
14305 public BatteryStatsImpl[] newArray(int size) {
14306 return new BatteryStatsImpl[size];
14307 }
14308 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014309
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014310 public void prepareForDumpLocked() {
14311 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014312 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014313
14314 // Pull the clock time. This may update the time and make a new history entry
14315 // if we had originally pulled a time before the RTC was set.
14316 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014317 }
14318
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014319 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014320 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014321 pw.println("mOnBatteryTimeBase:");
14322 mOnBatteryTimeBase.dump(pw, " ");
14323 pw.println("mOnBatteryScreenOffTimeBase:");
14324 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014325 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070014326 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014327 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070014328 pr.println("*** Screen doze timer:");
14329 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014330 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014331 pr.println("*** Screen brightness #" + i + ":");
14332 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014333 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014334 pr.println("*** Interactive timer:");
14335 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014336 pr.println("*** Power save mode timer:");
14337 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014338 pr.println("*** Device idle mode light timer:");
14339 mDeviceIdleModeLightTimer.logState(pr, " ");
14340 pr.println("*** Device idle mode full timer:");
14341 mDeviceIdleModeFullTimer.logState(pr, " ");
14342 pr.println("*** Device light idling timer:");
14343 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014344 pr.println("*** Device idling timer:");
14345 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014346 pr.println("*** Phone timer:");
14347 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080014348 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070014349 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014350 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014351 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070014352 pr.println("*** Signal scanning :");
14353 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014354 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014355 pr.println("*** Data connection type #" + i + ":");
14356 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014357 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014358 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080014359 pr.println("*** Mobile network active timer:");
14360 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014361 pr.println("*** Mobile network active adjusted timer:");
14362 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014363 pr.println("*** Wifi Multicast WakeLock Timer:");
14364 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014365 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014366 pr.println("*** Wifi timer:");
14367 mWifiOnTimer.logState(pr, " ");
14368 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014369 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014370 for (int i=0; i<NUM_WIFI_STATES; i++) {
14371 pr.println("*** Wifi state #" + i + ":");
14372 mWifiStateTimer[i].logState(pr, " ");
14373 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014374 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14375 pr.println("*** Wifi suppl state #" + i + ":");
14376 mWifiSupplStateTimer[i].logState(pr, " ");
14377 }
14378 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14379 pr.println("*** Wifi signal strength #" + i + ":");
14380 mWifiSignalStrengthsTimer[i].logState(pr, " ");
14381 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014382 pr.println("*** Flashlight timer:");
14383 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014384 pr.println("*** Camera timer:");
14385 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014386 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014387 super.dumpLocked(context, pw, flags, reqUid, histStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014389}