blob: ee3bec803b51d5e688c5b99e27d00e8b9d0c1d57 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.os;
18
Sudheer Shanka9b735c52017-05-09 18:26:18 -070019import android.annotation.NonNull;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070020import android.annotation.Nullable;
Dianne Hackborn61659e52014-07-09 16:13:01 -070021import android.app.ActivityManager;
Adam Lesinski33dac552015-03-09 15:24:48 -070022import android.bluetooth.BluetoothActivityEnergyInfo;
Adam Lesinski50e47602015-12-04 17:04:54 -080023import android.bluetooth.UidTraffic;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080024import android.content.ContentResolver;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080025import android.content.Context;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070026import android.content.Intent;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080027import android.database.ContentObserver;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070028import android.net.ConnectivityManager;
29import android.net.NetworkStats;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080030import android.net.Uri;
Adam Lesinski33dac552015-03-09 15:24:48 -070031import android.net.wifi.WifiActivityEnergyInfo;
Dianne Hackborn3251b902014-06-20 14:40:53 -070032import android.net.wifi.WifiManager;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070033import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.os.BatteryStats;
Dianne Hackborncd0e3352014-08-07 17:08:09 -070035import android.os.Build;
Siddharth Raya1fd0572017-11-13 14:20:47 -080036import android.os.connectivity.CellularBatteryStats;
Siddharth Rayb50a6842017-12-14 15:15:28 -080037import android.os.connectivity.WifiBatteryStats;
Siddharth Ray78ccaf52017-12-23 16:16:21 -080038import android.os.connectivity.GpsBatteryStats;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070039import android.os.FileUtils;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070040import android.os.Handler;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080041import android.os.IBatteryPropertiesRegistrar;
Jeff Brown6f357d32014-01-15 20:40:55 -080042import android.os.Looper;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070043import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.Parcel;
45import android.os.ParcelFormatException;
46import android.os.Parcelable;
Evan Millarc64edde2009-04-18 12:26:32 -070047import android.os.Process;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080048import android.os.RemoteException;
49import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.SystemClock;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070051import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070052import android.os.WorkSource;
Narayan Kamath81822022017-12-08 11:56:01 +000053import android.os.WorkSource.WorkChain;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080054import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070055import android.telephony.DataConnectionRealTimeInfo;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080056import android.telephony.ModemActivityInfo;
Amith Yamasanif37447b2009-10-08 18:28:01 -070057import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070058import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070059import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070060import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070061import android.util.ArrayMap;
Sudheer Shankab2f83c12017-11-13 19:25:01 -080062import android.util.IntArray;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080063import android.util.KeyValueListParser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070065import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070066import android.util.LongSparseArray;
67import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070068import android.util.MutableInt;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070069import android.util.Pools;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070070import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070072import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080074import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070075import android.util.SparseLongArray;
Bookatzc1a050a2017-10-10 15:49:28 -070076import android.util.StatsLog;
Dianne Hackbornae384452011-06-28 12:33:48 -070077import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080078import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070079import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080
Adam Lesinski14ae39a2017-05-26 11:50:40 -070081import com.android.internal.annotations.GuardedBy;
Adam Lesinski98f0d462016-04-19 16:46:20 -070082import com.android.internal.annotations.VisibleForTesting;
Siddharth Ray78ccaf52017-12-23 16:16:21 -080083import com.android.internal.location.gnssmetrics.GnssMetrics;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070084import com.android.internal.net.NetworkStatsFactory;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080085import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070086import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080087import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070088import com.android.internal.util.JournaledFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080089import com.android.internal.util.XmlUtils;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070090
Narayan Kamath81822022017-12-08 11:56:01 +000091import java.util.List;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070092import libcore.util.EmptyArray;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080093import org.xmlpull.v1.XmlPullParser;
94import org.xmlpull.v1.XmlPullParserException;
95import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070096
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080097import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import java.io.File;
99import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800100import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import java.io.FileOutputStream;
102import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -0700103import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100104import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.ArrayList;
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700106import java.util.Arrays;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800107import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.HashMap;
Evan Millarc64edde2009-04-18 12:26:32 -0700109import java.util.Iterator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Map;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700111import java.util.concurrent.Future;
Christopher Tate4cee7252010-03-19 14:50:40 -0700112import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700113import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
115/**
116 * All information we are collecting about things that can happen that impact
117 * battery life. All times are represented in microseconds except where indicated
118 * otherwise.
119 */
Joe Onoratoabded112016-02-08 16:49:39 -0800120public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800122 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700123 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800124 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700125 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700126 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700127 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700128
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700129 // TODO: remove "tcp" from network methods, since we measure total stats.
130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700132 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133
134 // Current on-disk Parcel version
Siddharth Rayb50a6842017-12-14 15:15:28 -0800135 private static final int VERSION = 174 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700136
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700137 // Maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100138 private static final int MAX_HISTORY_ITEMS;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700139
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700140 // No, really, THIS is the maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100141 private static final int MAX_MAX_HISTORY_ITEMS;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700142
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800143 // The maximum number of names wakelocks we will keep track of
144 // per uid; once the limit is reached, we batch the remaining wakelocks
145 // in to one common name.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100146 private static final int MAX_WAKELOCKS_PER_UID;
147
148 static final int MAX_HISTORY_BUFFER; // 256KB
149 static final int MAX_MAX_HISTORY_BUFFER; // 320KB
150
151 static {
152 if (ActivityManager.isLowRamDeviceStatic()) {
153 MAX_HISTORY_ITEMS = 800;
154 MAX_MAX_HISTORY_ITEMS = 1200;
155 MAX_WAKELOCKS_PER_UID = 40;
156 MAX_HISTORY_BUFFER = 96*1024; // 96KB
157 MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
158 } else {
Makoto Onuki44d64602018-01-18 08:44:28 -0800159 MAX_HISTORY_ITEMS = 4000;
160 MAX_MAX_HISTORY_ITEMS = 6000;
161 MAX_WAKELOCKS_PER_UID = 200;
162 MAX_HISTORY_BUFFER = 512*1024; // 512KB
163 MAX_MAX_HISTORY_BUFFER = 640*1024; // 640KB
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100164 }
165 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700166
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800167 // Number of transmit power states the Wifi controller can be in.
168 private static final int NUM_WIFI_TX_LEVELS = 1;
169
170 // Number of transmit power states the Bluetooth controller can be in.
171 private static final int NUM_BT_TX_LEVELS = 1;
172
Sudheer Shanka38383232017-07-25 09:55:03 -0700173 /**
174 * Holding a wakelock costs more than just using the cpu.
175 * Currently, we assign only half the cpu time to an app that is running but
176 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
177 * If no app is holding a wakelock, then the distribution is normal.
178 */
179 @VisibleForTesting
180 public static final int WAKE_LOCK_WEIGHT = 50;
181
Joe Onoratoabded112016-02-08 16:49:39 -0800182 protected Clocks mClocks;
183
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700184 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700185 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800186 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700188 static final int MSG_UPDATE_WAKELOCKS = 1;
189 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700190 static final int MSG_REPORT_CHARGING = 3;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700191 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700192
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700193 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
194 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
195
Sudheer Shanka38383232017-07-25 09:55:03 -0700196 @VisibleForTesting
197 protected KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
198 @VisibleForTesting
199 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
200 @VisibleForTesting
201 protected KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700202 new KernelUidCpuFreqTimeReader();
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800203 @VisibleForTesting
Mike Ma3d422c32017-10-25 11:08:57 -0700204 protected KernelUidCpuActiveTimeReader mKernelUidCpuActiveTimeReader =
205 new KernelUidCpuActiveTimeReader();
206 @VisibleForTesting
207 protected KernelUidCpuClusterTimeReader mKernelUidCpuClusterTimeReader =
208 new KernelUidCpuClusterTimeReader();
209 @VisibleForTesting
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800210 protected KernelSingleUidTimeReader mKernelSingleUidTimeReader;
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700211
James Carr3a226052016-07-01 14:49:52 -0700212 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
213 = new KernelMemoryBandwidthStats();
214 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
215 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
216 return mKernelMemoryStats;
217 }
218
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800219 @GuardedBy("this")
220 public boolean mPerProcStateCpuTimesAvailable = true;
221
222 /**
223 * Uids for which per-procstate cpu times need to be updated.
224 *
225 * Contains uid -> procState mappings.
226 */
227 @GuardedBy("this")
228 @VisibleForTesting
229 protected final SparseIntArray mPendingUids = new SparseIntArray();
230
Bookatz0b8a0502017-09-13 11:51:52 -0700231 /** Container for Resource Power Manager stats. Updated by updateRpmStatsLocked. */
Bookatz50df7112017-08-04 14:53:26 -0700232 private final RpmStats mTmpRpmStats = new RpmStats();
Bookatz0b8a0502017-09-13 11:51:52 -0700233 /** The soonest the RPM stats can be updated after it was last updated. */
234 private static final long RPM_STATS_UPDATE_FREQ_MS = 1000;
235 /** Last time that RPM stats were updated by updateRpmStatsLocked. */
236 private long mLastRpmStatsUpdateTimeMs = -RPM_STATS_UPDATE_FREQ_MS;
Bookatz50df7112017-08-04 14:53:26 -0700237
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700238 public interface BatteryCallback {
239 public void batteryNeedsCpuUpdate();
240 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700241 public void batterySendBroadcast(Intent intent);
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700242 }
243
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700244 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700245 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700246 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000247 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700248 }
249
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700250 public static abstract class UserInfoProvider {
251 private int[] userIds;
252 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700253 @VisibleForTesting
254 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700255 userIds = getUserIds();
256 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700257 @VisibleForTesting
258 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700259 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
260 }
261 }
262
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700263 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
264
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700265 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800266 public MyHandler(Looper looper) {
267 super(looper, null, true);
268 }
269
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700270 @Override
271 public void handleMessage(Message msg) {
272 BatteryCallback cb = mCallback;
273 switch (msg.what) {
274 case MSG_UPDATE_WAKELOCKS:
Adam Lesinski72478f02015-06-17 15:39:43 -0700275 synchronized (BatteryStatsImpl.this) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -0700276 updateCpuTimeLocked();
Adam Lesinski72478f02015-06-17 15:39:43 -0700277 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700278 if (cb != null) {
279 cb.batteryNeedsCpuUpdate();
280 }
281 break;
282 case MSG_REPORT_POWER_CHANGE:
283 if (cb != null) {
284 cb.batteryPowerChanged(msg.arg1 != 0);
285 }
286 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700287 case MSG_REPORT_CHARGING:
288 if (cb != null) {
289 final String action;
290 synchronized (BatteryStatsImpl.this) {
291 action = mCharging ? BatteryManager.ACTION_CHARGING
292 : BatteryManager.ACTION_DISCHARGING;
293 }
294 Intent intent = new Intent(action);
295 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
296 cb.batterySendBroadcast(intent);
297 }
298 break;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700299 }
300 }
301 }
302
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800303 /**
304 * Update per-freq cpu times for all the uids in {@link #mPendingUids}.
305 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800306 public void updateProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800307 final SparseIntArray uidStates;
308 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800309 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
310 return;
311 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800312 if(!initKernelSingleUidTimeReaderLocked()) {
313 return;
314 }
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800315 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
316 // compute deltas since it might result in mis-attributing cpu times to wrong states.
317 if (mKernelSingleUidTimeReader.hasStaleData()) {
318 mPendingUids.clear();
319 return;
320 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800321
322 if (mPendingUids.size() == 0) {
323 return;
324 }
325 uidStates = mPendingUids.clone();
326 mPendingUids.clear();
327 }
328 for (int i = uidStates.size() - 1; i >= 0; --i) {
329 final int uid = uidStates.keyAt(i);
330 final int procState = uidStates.valueAt(i);
331 final int[] isolatedUids;
332 final Uid u;
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800333 synchronized (BatteryStatsImpl.this) {
334 // It's possible that uid no longer exists and any internal references have
335 // already been deleted, so using {@link #getAvailableUidStatsLocked} to avoid
336 // creating an UidStats object if it doesn't already exist.
337 u = getAvailableUidStatsLocked(uid);
338 if (u == null) {
339 continue;
340 }
341 if (u.mChildUids == null) {
342 isolatedUids = null;
343 } else {
344 isolatedUids = u.mChildUids.toArray();
345 for (int j = isolatedUids.length - 1; j >= 0; --j) {
346 isolatedUids[j] = u.mChildUids.get(j);
347 }
348 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800349 }
350 long[] cpuTimesMs = mKernelSingleUidTimeReader.readDeltaMs(uid);
351 if (isolatedUids != null) {
352 for (int j = isolatedUids.length - 1; j >= 0; --j) {
353 cpuTimesMs = addCpuTimes(cpuTimesMs,
354 mKernelSingleUidTimeReader.readDeltaMs(isolatedUids[j]));
355 }
356 }
357 if (onBattery && cpuTimesMs != null) {
358 synchronized (BatteryStatsImpl.this) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800359 u.addProcStateTimesMs(procState, cpuTimesMs, onBattery);
360 u.addProcStateScreenOffTimesMs(procState, cpuTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800361 }
362 }
363 }
364 }
365
Sudheer Shankae544d162017-12-28 17:06:20 -0800366 public void copyFromAllUidsCpuTimes() {
367 synchronized (BatteryStatsImpl.this) {
368 copyFromAllUidsCpuTimes(
369 mOnBatteryTimeBase.isRunning(), mOnBatteryScreenOffTimeBase.isRunning());
370 }
371 }
372
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800373 /**
374 * When the battery/screen state changes, we don't attribute the cpu times to any process
375 * but we still need to snapshots of all uids to get correct deltas later on. Since we
376 * already read this data for updating per-freq cpu times, we can use the same data for
377 * per-procstate cpu times.
378 */
Sudheer Shankae544d162017-12-28 17:06:20 -0800379 public void copyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800380 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800381 if (!mConstants.TRACK_CPU_TIMES_BY_PROC_STATE) {
382 return;
383 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800384 if(!initKernelSingleUidTimeReaderLocked()) {
385 return;
386 }
387
388 final SparseArray<long[]> allUidCpuFreqTimesMs =
389 mKernelUidCpuFreqTimeReader.getAllUidCpuFreqTimeMs();
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800390 // If the KernelSingleUidTimeReader has stale cpu times, then we shouldn't try to
391 // compute deltas since it might result in mis-attributing cpu times to wrong states.
392 if (mKernelSingleUidTimeReader.hasStaleData()) {
393 mKernelSingleUidTimeReader.setAllUidsCpuTimesMs(allUidCpuFreqTimesMs);
394 mKernelSingleUidTimeReader.markDataAsStale(false);
395 mPendingUids.clear();
396 return;
397 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800398 for (int i = allUidCpuFreqTimesMs.size() - 1; i >= 0; --i) {
399 final int uid = allUidCpuFreqTimesMs.keyAt(i);
400 final Uid u = getAvailableUidStatsLocked(mapUid(uid));
401 if (u == null) {
402 continue;
403 }
404 final long[] cpuTimesMs = allUidCpuFreqTimesMs.valueAt(i);
405 if (cpuTimesMs == null) {
406 continue;
407 }
408 final long[] deltaTimesMs = mKernelSingleUidTimeReader.computeDelta(
409 uid, cpuTimesMs.clone());
Sudheer Shankae544d162017-12-28 17:06:20 -0800410 if (onBattery && deltaTimesMs != null) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800411 final int procState;
412 final int idx = mPendingUids.indexOfKey(uid);
413 if (idx >= 0) {
414 procState = mPendingUids.valueAt(idx);
415 mPendingUids.removeAt(idx);
416 } else {
417 procState = u.mProcessState;
418 }
419 if (procState >= 0 && procState < Uid.NUM_PROCESS_STATE) {
Sudheer Shankae544d162017-12-28 17:06:20 -0800420 u.addProcStateTimesMs(procState, deltaTimesMs, onBattery);
421 u.addProcStateScreenOffTimesMs(procState, deltaTimesMs, onBatteryScreenOff);
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800422 }
423 }
424 }
425 }
426 }
427
428 @VisibleForTesting
429 public long[] addCpuTimes(long[] timesA, long[] timesB) {
430 if (timesA != null && timesB != null) {
431 for (int i = timesA.length - 1; i >= 0; --i) {
432 timesA[i] += timesB[i];
433 }
434 return timesA;
435 }
436 return timesA == null ? (timesB == null ? null : timesB) : timesA;
437 }
438
439 @GuardedBy("this")
440 private boolean initKernelSingleUidTimeReaderLocked() {
441 if (mKernelSingleUidTimeReader == null) {
442 if (mPowerProfile == null) {
443 return false;
444 }
445 if (mCpuFreqs == null) {
446 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
447 }
448 if (mCpuFreqs != null) {
449 mKernelSingleUidTimeReader = new KernelSingleUidTimeReader(mCpuFreqs.length);
450 } else {
451 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable();
452 return false;
453 }
454 }
455 mPerProcStateCpuTimesAvailable = mKernelUidCpuFreqTimeReader.allUidTimesAvailable()
456 && mKernelSingleUidTimeReader.singleUidCpuTimesAvailable();
457 return true;
458 }
459
Joe Onoratoabded112016-02-08 16:49:39 -0800460 public interface Clocks {
461 public long elapsedRealtime();
462 public long uptimeMillis();
463 }
464
465 public static class SystemClocks implements Clocks {
466 public long elapsedRealtime() {
467 return SystemClock.elapsedRealtime();
468 }
469
470 public long uptimeMillis() {
471 return SystemClock.uptimeMillis();
472 }
473 }
474
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700475 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700476 int UPDATE_CPU = 0x01;
477 int UPDATE_WIFI = 0x02;
478 int UPDATE_RADIO = 0x04;
479 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700480 int UPDATE_RPM = 0x10; // 16
481 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800482
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700483 Future<?> scheduleSync(String reason, int flags);
484 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Sudheer Shankae544d162017-12-28 17:06:20 -0800485 Future<?> scheduleReadProcStateCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
486 Future<?> scheduleCopyFromAllUidsCpuTimes(boolean onBattery, boolean onBatteryScreenOff);
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800487 Future<?> scheduleCpuSyncDueToSettingChange();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700488 }
489
Sudheer Shankab2f83c12017-11-13 19:25:01 -0800490 public Handler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700491 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700492 @VisibleForTesting
493 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700494
495 private BatteryCallback mCallback;
496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800498 * Mapping isolated uids to the actual owning app uid.
499 */
500 final SparseIntArray mIsolatedUids = new SparseIntArray();
501
502 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 * The statistics we have collected organized by uids.
504 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800505 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506
507 // A set of pools of currently active timers. When a timer is queried, we will divide the
508 // elapsed time by the number of active timers to arrive at that timer's share of the time.
509 // In order to do this, we must refresh each timer whenever the number of active timers
510 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700511 @VisibleForTesting
512 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700513 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
514 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700515 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700516 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
517 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
518 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
519 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
520 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
521 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
522 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
523 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700524 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
525 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800526 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700528 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700529 @VisibleForTesting
530 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 // These are the objects that will want to do something when the device
533 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800534 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800535
536 // These are the objects that will want to do something when the device
Mike Mac2f518a2017-09-19 16:06:03 -0700537 // is unplugged from power *and* the screen is off or doze.
538 protected final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800539
540 // Set to true when we want to distribute CPU across wakelocks for the next
541 // CPU update, even if we aren't currently running wake locks.
542 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700543
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700544 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700545
Dianne Hackborn37de0982014-05-09 09:32:18 -0700546 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800547
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700548 long mHistoryBaseTime;
Narayan Kamath695cf722017-12-21 18:32:47 +0000549 protected boolean mHaveBatteryLevel = false;
550 protected boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700551 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700552
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700553 final Parcel mHistoryBuffer = Parcel.obtain();
554 final HistoryItem mHistoryLastWritten = new HistoryItem();
555 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700556 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700557 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700558 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800559 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800560 int[] mReadHistoryUids;
561 int mReadHistoryChars;
562 int mNextHistoryTagIdx = 0;
563 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700564 int mHistoryBufferLastPos = -1;
565 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700566 int mActiveHistoryStates = 0xffffffff;
567 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700568 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700569 long mTrackRunningHistoryElapsedRealtime = 0;
570 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700571
572 final HistoryItem mHistoryCur = new HistoryItem();
573
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700574 HistoryItem mHistory;
575 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700576 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700577 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700578
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800579 // Used by computeHistoryStepDetails
580 HistoryStepDetails mLastHistoryStepDetails = null;
581 byte mLastHistoryStepLevel = 0;
582 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
583 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
584 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700585
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800586 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700587 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800588 */
589 long mLastStepCpuUserTime;
590 long mCurStepCpuUserTime;
591 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700592 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800593 */
594 long mLastStepCpuSystemTime;
595 long mCurStepCpuSystemTime;
596 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700597 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800598 */
599 long mLastStepStatUserTime;
600 long mLastStepStatSystemTime;
601 long mLastStepStatIOWaitTime;
602 long mLastStepStatIrqTime;
603 long mLastStepStatSoftIrqTime;
604 long mLastStepStatIdleTime;
605 long mCurStepStatUserTime;
606 long mCurStepStatSystemTime;
607 long mCurStepStatIOWaitTime;
608 long mCurStepStatIrqTime;
609 long mCurStepStatSoftIrqTime;
610 long mCurStepStatIdleTime;
611
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700612 private HistoryItem mHistoryIterator;
613 private boolean mReadOverflow;
614 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 int mStartCount;
617
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800618 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700619 String mStartPlatformVersion;
620 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 long mUptime;
623 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 long mRealtime;
625 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700626
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800627 int mWakeLockNesting;
628 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700629 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700630 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800631
Mike Mac2f518a2017-09-19 16:06:03 -0700632 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
633 protected int mScreenState = Display.STATE_UNKNOWN;
634 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
635 protected StopwatchTimer mScreenOnTimer;
636 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
637 protected StopwatchTimer mScreenDozeTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700638
Dianne Hackborn617f8772009-03-31 15:04:46 -0700639 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700640 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700641
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800642 boolean mPretendScreenOff;
643
Jeff Browne95c3cd2014-05-02 16:59:26 -0700644 boolean mInteractive;
645 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700646
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700647 boolean mPowerSaveModeEnabled;
648 StopwatchTimer mPowerSaveModeEnabledTimer;
649
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700650 boolean mDeviceIdling;
651 StopwatchTimer mDeviceIdlingTimer;
652
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700653 boolean mDeviceLightIdling;
654 StopwatchTimer mDeviceLightIdlingTimer;
655
656 int mDeviceIdleMode;
657 long mLastIdleTimeStart;
658 long mLongestLightIdleTime;
659 long mLongestFullIdleTime;
660 StopwatchTimer mDeviceIdleModeLightTimer;
661 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700664 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700665
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700666 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700667 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700668
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700669 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700670 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700671
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700672 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700673 StopwatchTimer mFlashlightOnTimer;
674
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700675 int mCameraOnNesting;
676 StopwatchTimer mCameraOnTimer;
677
Siddharth Ray78ccaf52017-12-23 16:16:21 -0800678 int mGpsSignalQualityBin = -1;
679 final StopwatchTimer[] mGpsSignalQualityTimer =
680 new StopwatchTimer[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
681
Dianne Hackborn627bba72009-03-24 22:32:56 -0700682 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800683 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700684 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800685 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700686
687 StopwatchTimer mPhoneSignalScanningTimer;
688
Dianne Hackborn627bba72009-03-24 22:32:56 -0700689 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700690 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700691 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700692
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800693 final LongSamplingCounter[] mNetworkByteActivityCounters =
694 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
695 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700696 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
697
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800698 /**
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -0800699 * The WiFi Overall wakelock timer
700 * This timer tracks the actual aggregate time for which MC wakelocks are enabled
701 * since addition of per UID timers would not result in an accurate value due to overlapp of
702 * per uid wakelock timers
703 */
704 StopwatchTimer mWifiMulticastWakelockTimer;
705
706 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800707 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
708 */
709 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700710
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800711 /**
712 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
713 */
714 ControllerActivityCounterImpl mBluetoothActivity;
715
716 /**
717 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
718 */
719 ControllerActivityCounterImpl mModemActivity;
720
721 /**
722 * Whether the device supports WiFi controller energy reporting. This is set to true on
723 * the first WiFi energy report. See {@link #mWifiActivity}.
724 */
725 boolean mHasWifiReporting = false;
726
727 /**
728 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
729 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
730 */
731 boolean mHasBluetoothReporting = false;
732
733 /**
734 * Whether the device supports Modem controller energy reporting. This is set to true on
735 * the first Modem energy report. See {@link #mModemActivity}.
736 */
737 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700738
The Android Open Source Project10592532009-03-18 17:39:46 -0700739 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700740 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700741
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700742 boolean mGlobalWifiRunning;
743 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700744
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800745 int mWifiState = -1;
746 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
747
Dianne Hackborn3251b902014-06-20 14:40:53 -0700748 int mWifiSupplState = -1;
749 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
750
751 int mWifiSignalStrengthBin = -1;
752 final StopwatchTimer[] mWifiSignalStrengthsTimer =
753 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
754
Siddharth Rayb50a6842017-12-14 15:15:28 -0800755 StopwatchTimer mWifiActiveTimer;
756
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800757 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800758 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
759 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800760
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700761 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700762 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800763 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800764 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700765 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800766 LongSamplingCounter mMobileRadioActiveUnknownTime;
767 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800768
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700769 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 /**
772 * These provide time bases that discount the time the device is plugged
773 * in to power.
774 */
775 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700776 @VisibleForTesting
777 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700778
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700779 /**
780 * External reporting of whether the device is actually charging.
781 */
782 boolean mCharging = true;
783 int mLastChargingStateLevel;
784
The Android Open Source Project10592532009-03-18 17:39:46 -0700785 /*
786 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
787 */
Evan Millar633a1742009-04-02 16:36:33 -0700788 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700789 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700790 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700791 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700792 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700793 int mLowDischargeAmountSinceCharge;
794 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800795 int mDischargeScreenOnUnplugLevel;
796 int mDischargeScreenOffUnplugLevel;
Mike Mac2f518a2017-09-19 16:06:03 -0700797 int mDischargeScreenDozeUnplugLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800798 int mDischargeAmountScreenOn;
799 int mDischargeAmountScreenOnSinceCharge;
800 int mDischargeAmountScreenOff;
801 int mDischargeAmountScreenOffSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -0700802 int mDischargeAmountScreenDoze;
803 int mDischargeAmountScreenDozeSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700804
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700805 private LongSamplingCounter mDischargeScreenOffCounter;
Mike Mac2f518a2017-09-19 16:06:03 -0700806 private LongSamplingCounter mDischargeScreenDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700807 private LongSamplingCounter mDischargeCounter;
Mike Ma15313c92017-11-15 17:58:21 -0800808 private LongSamplingCounter mDischargeLightDozeCounter;
809 private LongSamplingCounter mDischargeDeepDozeCounter;
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700810
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700811 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700812
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700813 int mInitStepMode = 0;
814 int mCurStepMode = 0;
815 int mModStepMode = 0;
816
Dianne Hackborn260c5022014-04-29 11:23:16 -0700817 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700818 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800819 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
820 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700821 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700822
823 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700824 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800825 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
826 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
827
828 static final int MAX_DAILY_ITEMS = 10;
829
830 long mDailyStartTime = 0;
831 long mNextMinDailyDeadline = 0;
832 long mNextMaxDailyDeadline = 0;
833
834 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700837
Amith Yamasanif37447b2009-10-08 18:28:01 -0700838 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800839 private int mPhoneServiceStateRaw = -1;
840 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700841
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800842 private int mNumConnectivityChange;
843 private int mLoadedNumConnectivityChange;
844 private int mUnpluggedNumConnectivityChange;
845
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700846 private int mEstimatedBatteryCapacity = -1;
847
Jocelyn Dangc627d102017-04-14 13:15:14 -0700848 private int mMinLearnedBatteryCapacity = -1;
849 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800850
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700851 private long[] mCpuFreqs;
852
Sudheer Shanka38383232017-07-25 09:55:03 -0700853 @VisibleForTesting
854 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700855
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800856 @GuardedBy("this")
857 private final Constants mConstants;
858
Evan Millarc64edde2009-04-18 12:26:32 -0700859 /*
Bookatz50df7112017-08-04 14:53:26 -0700860 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
861 * recording their times when on-battery (regardless of screen state).
862 */
863 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
864 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
865 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
866
867 @Override
868 public Map<String, ? extends Timer> getRpmStats() {
869 return mRpmStats;
870 }
871
Bookatz82b341172017-09-07 19:06:08 -0700872 // TODO: Note: screenOffRpmStats has been disabled via SCREEN_OFF_RPM_STATS_ENABLED.
Bookatz50df7112017-08-04 14:53:26 -0700873 @Override
874 public Map<String, ? extends Timer> getScreenOffRpmStats() {
875 return mScreenOffRpmStats;
876 }
877
878 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700879 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
880 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700881 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700882
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700883 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700884 return mKernelWakelockStats;
885 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700886
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700887 String mLastWakeupReason = null;
888 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700889 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700890
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700891 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700892 return mWakeupReasonStats;
893 }
894
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700895 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700896 public long getUahDischarge(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700897 return mDischargeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700898 }
899
900 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700901 public long getUahDischargeScreenOff(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700902 return mDischargeScreenOffCounter.getCountLocked(which);
903 }
904
905 @Override
Kweku Adams87b19ec2017-10-09 12:40:03 -0700906 public long getUahDischargeScreenDoze(int which) {
Mike Mac2f518a2017-09-19 16:06:03 -0700907 return mDischargeScreenDozeCounter.getCountLocked(which);
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700908 }
909
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700910 @Override
Mike Ma15313c92017-11-15 17:58:21 -0800911 public long getUahDischargeLightDoze(int which) {
912 return mDischargeLightDozeCounter.getCountLocked(which);
913 }
914
915 @Override
916 public long getUahDischargeDeepDoze(int which) {
917 return mDischargeDeepDozeCounter.getCountLocked(which);
918 }
919
920 @Override
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700921 public int getEstimatedBatteryCapacity() {
922 return mEstimatedBatteryCapacity;
923 }
924
Jocelyn Dangc627d102017-04-14 13:15:14 -0700925 @Override
926 public int getMinLearnedBatteryCapacity() {
927 return mMinLearnedBatteryCapacity;
928 }
929
930 @Override
931 public int getMaxLearnedBatteryCapacity() {
932 return mMaxLearnedBatteryCapacity;
933 }
934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -0800936 this(new SystemClocks());
937 }
938
939 public BatteryStatsImpl(Clocks clocks) {
940 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700941 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700942 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800943 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700944 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700945 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700946 mUserInfoProvider = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -0800947 mConstants = new Constants(mHandler);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700948 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 }
950
Joe Onoratoabded112016-02-08 16:49:39 -0800951 private void init(Clocks clocks) {
952 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -0800953 }
954
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700955 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800956 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
957 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
958 }
959
Joe Onoratoabded112016-02-08 16:49:39 -0800960 // methods are protected not private to be VisibleForTesting
961 public static class TimeBase {
962 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800963
Joe Onoratoabded112016-02-08 16:49:39 -0800964 protected long mUptime;
965 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800966
Joe Onoratoabded112016-02-08 16:49:39 -0800967 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800968
Joe Onoratoabded112016-02-08 16:49:39 -0800969 protected long mPastUptime;
970 protected long mUptimeStart;
971 protected long mPastRealtime;
972 protected long mRealtimeStart;
973 protected long mUnpluggedUptime;
974 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800975
976 public void dump(PrintWriter pw, String prefix) {
977 StringBuilder sb = new StringBuilder(128);
978 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
979 sb.setLength(0);
980 sb.append(prefix);
981 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700982 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800983 pw.println(sb.toString());
984 sb.setLength(0);
985 sb.append(prefix);
986 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700987 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800988 pw.println(sb.toString());
989 sb.setLength(0);
990 sb.append(prefix);
991 sb.append("mPastUptime=");
992 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
993 formatTimeMs(sb, mUptimeStart / 1000);
994 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
995 pw.println(sb.toString());
996 sb.setLength(0);
997 sb.append(prefix);
998 sb.append("mPastRealtime=");
999 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
1000 formatTimeMs(sb, mRealtimeStart / 1000);
1001 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
1002 pw.println(sb.toString());
1003 }
1004
1005 public void add(TimeBaseObs observer) {
1006 mObservers.add(observer);
1007 }
1008
1009 public void remove(TimeBaseObs observer) {
1010 if (!mObservers.remove(observer)) {
1011 Slog.wtf(TAG, "Removed unknown observer: " + observer);
1012 }
1013 }
1014
Joe Onoratoabded112016-02-08 16:49:39 -08001015 public boolean hasObserver(TimeBaseObs observer) {
1016 return mObservers.contains(observer);
1017 }
1018
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001019 public void init(long uptime, long realtime) {
1020 mRealtime = 0;
1021 mUptime = 0;
1022 mPastUptime = 0;
1023 mPastRealtime = 0;
1024 mUptimeStart = uptime;
1025 mRealtimeStart = realtime;
1026 mUnpluggedUptime = getUptime(mUptimeStart);
1027 mUnpluggedRealtime = getRealtime(mRealtimeStart);
1028 }
1029
1030 public void reset(long uptime, long realtime) {
1031 if (!mRunning) {
1032 mPastUptime = 0;
1033 mPastRealtime = 0;
1034 } else {
1035 mUptimeStart = uptime;
1036 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -08001037 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
1038 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001039 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -08001040 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001041 mUnpluggedRealtime = getRealtime(realtime);
1042 }
1043 }
1044
1045 public long computeUptime(long curTime, int which) {
1046 switch (which) {
1047 case STATS_SINCE_CHARGED:
1048 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001049 case STATS_CURRENT:
1050 return getUptime(curTime);
1051 case STATS_SINCE_UNPLUGGED:
1052 return getUptime(curTime) - mUnpluggedUptime;
1053 }
1054 return 0;
1055 }
1056
1057 public long computeRealtime(long curTime, int which) {
1058 switch (which) {
1059 case STATS_SINCE_CHARGED:
1060 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001061 case STATS_CURRENT:
1062 return getRealtime(curTime);
1063 case STATS_SINCE_UNPLUGGED:
1064 return getRealtime(curTime) - mUnpluggedRealtime;
1065 }
1066 return 0;
1067 }
1068
1069 public long getUptime(long curTime) {
1070 long time = mPastUptime;
1071 if (mRunning) {
1072 time += curTime - mUptimeStart;
1073 }
1074 return time;
1075 }
1076
1077 public long getRealtime(long curTime) {
1078 long time = mPastRealtime;
1079 if (mRunning) {
1080 time += curTime - mRealtimeStart;
1081 }
1082 return time;
1083 }
1084
1085 public long getUptimeStart() {
1086 return mUptimeStart;
1087 }
1088
1089 public long getRealtimeStart() {
1090 return mRealtimeStart;
1091 }
1092
1093 public boolean isRunning() {
1094 return mRunning;
1095 }
1096
1097 public boolean setRunning(boolean running, long uptime, long realtime) {
1098 if (mRunning != running) {
1099 mRunning = running;
1100 if (running) {
1101 mUptimeStart = uptime;
1102 mRealtimeStart = realtime;
1103 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
1104 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
1105
1106 for (int i = mObservers.size() - 1; i >= 0; i--) {
1107 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
1108 }
1109 } else {
1110 mPastUptime += uptime - mUptimeStart;
1111 mPastRealtime += realtime - mRealtimeStart;
1112
1113 long batteryUptime = getUptime(uptime);
1114 long batteryRealtime = getRealtime(realtime);
1115
1116 for (int i = mObservers.size() - 1; i >= 0; i--) {
1117 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
1118 }
1119 }
1120 return true;
1121 }
1122 return false;
1123 }
1124
1125 public void readSummaryFromParcel(Parcel in) {
1126 mUptime = in.readLong();
1127 mRealtime = in.readLong();
1128 }
1129
1130 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
1131 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
1132 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
1133 }
1134
1135 public void readFromParcel(Parcel in) {
1136 mRunning = false;
1137 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001138 mPastUptime = in.readLong();
1139 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001140 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001141 mPastRealtime = in.readLong();
1142 mRealtimeStart = in.readLong();
1143 mUnpluggedUptime = in.readLong();
1144 mUnpluggedRealtime = in.readLong();
1145 }
1146
1147 public void writeToParcel(Parcel out, long uptime, long realtime) {
1148 final long runningUptime = getUptime(uptime);
1149 final long runningRealtime = getRealtime(realtime);
1150 out.writeLong(mUptime);
1151 out.writeLong(runningUptime);
1152 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -07001153 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001154 out.writeLong(runningRealtime);
1155 out.writeLong(mRealtimeStart);
1156 out.writeLong(mUnpluggedUptime);
1157 out.writeLong(mUnpluggedRealtime);
1158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -07001162 * State for keeping track of counting information.
1163 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001164 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -07001165 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001166 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001167 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001168 int mUnpluggedCount;
1169 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001170
Bookatz8c6f3c52017-05-24 12:00:17 -07001171 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001172 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -07001173 mPluggedCount = in.readInt();
1174 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001175 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001176 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001177 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001178 }
1179
Bookatz8c6f3c52017-05-24 12:00:17 -07001180 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001181 mTimeBase = timeBase;
1182 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001183 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001184
Dianne Hackborn617f8772009-03-31 15:04:46 -07001185 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001186 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -07001187 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001188 out.writeInt(mUnpluggedCount);
1189 }
1190
Bookatz8c6f3c52017-05-24 12:00:17 -07001191 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001192 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001193 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001194 }
1195
Bookatz8c6f3c52017-05-24 12:00:17 -07001196 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001197 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001198 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -07001199 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001200
Dianne Hackborn617f8772009-03-31 15:04:46 -07001201 /**
1202 * Writes a possibly null Counter to a Parcel.
1203 *
1204 * @param out the Parcel to be written to.
1205 * @param counter a Counter, or null.
1206 */
1207 public static void writeCounterToParcel(Parcel out, Counter counter) {
1208 if (counter == null) {
1209 out.writeInt(0); // indicates null
1210 return;
1211 }
1212 out.writeInt(1); // indicates non-null
1213
1214 counter.writeToParcel(out);
1215 }
1216
1217 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001218 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001219 int val = mCount.get();
1220 if (which == STATS_SINCE_UNPLUGGED) {
1221 val -= mUnpluggedCount;
1222 } else if (which != STATS_SINCE_CHARGED) {
1223 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001224 }
1225
1226 return val;
1227 }
1228
1229 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001230 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -07001231 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -07001232 + " mUnpluggedCount=" + mUnpluggedCount
1233 + " mPluggedCount=" + mPluggedCount);
1234 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001235
Bookatz8c6f3c52017-05-24 12:00:17 -07001236 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1237 public void stepAtomic() {
1238 if (mTimeBase.isRunning()) {
1239 mCount.incrementAndGet();
1240 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07001241 }
1242
Bookatz4ebc0642017-05-11 12:21:19 -07001243 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001244 if (mTimeBase.isRunning()) {
1245 mCount.addAndGet(delta);
1246 }
Bookatz4ebc0642017-05-11 12:21:19 -07001247 }
1248
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001249 /**
1250 * Clear state of this counter.
1251 */
1252 void reset(boolean detachIfReset) {
1253 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -07001254 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001255 if (detachIfReset) {
1256 detach();
1257 }
1258 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001259
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001260 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001261 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001262 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001263
Bookatz8c6f3c52017-05-24 12:00:17 -07001264 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1265 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001266 int count = mCount.get();
1267 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001268 }
1269
Bookatz8c6f3c52017-05-24 12:00:17 -07001270 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1271 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001272 mLoadedCount = in.readInt();
1273 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001274 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001275 }
1276 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001277
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001278 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001279 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1280 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001281 public long[] mCounts;
1282 public long[] mLoadedCounts;
1283 public long[] mUnpluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001284
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001285 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001286 mTimeBase = timeBase;
Sudheer Shankae544d162017-12-28 17:06:20 -08001287 mCounts = in.createLongArray();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001288 mLoadedCounts = in.createLongArray();
1289 mUnpluggedCounts = in.createLongArray();
1290 timeBase.add(this);
1291 }
1292
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001293 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001294 mTimeBase = timeBase;
1295 timeBase.add(this);
1296 }
1297
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001298 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001299 out.writeLongArray(mCounts);
1300 out.writeLongArray(mLoadedCounts);
1301 out.writeLongArray(mUnpluggedCounts);
1302 }
1303
1304 @Override
1305 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001306 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001307 }
1308
1309 @Override
1310 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001311 }
1312
1313 @Override
1314 public long[] getCountsLocked(int which) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001315 long[] val = copyArray(mCounts, null);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001316 if (which == STATS_SINCE_UNPLUGGED) {
1317 subtract(val, mUnpluggedCounts);
1318 } else if (which != STATS_SINCE_CHARGED) {
1319 subtract(val, mLoadedCounts);
1320 }
1321 return val;
1322 }
1323
1324 @Override
1325 public void logState(Printer pw, String prefix) {
1326 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1327 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
Sudheer Shankae544d162017-12-28 17:06:20 -08001328 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts));
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001329 }
1330
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001331 public void addCountLocked(long[] counts) {
Sudheer Shankae544d162017-12-28 17:06:20 -08001332 addCountLocked(counts, mTimeBase.isRunning());
1333 }
1334
1335 public void addCountLocked(long[] counts, boolean isRunning) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001336 if (counts == null) {
1337 return;
1338 }
Sudheer Shankae544d162017-12-28 17:06:20 -08001339 if (isRunning) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001340 if (mCounts == null) {
1341 mCounts = new long[counts.length];
1342 }
1343 for (int i = 0; i < counts.length; ++i) {
1344 mCounts[i] += counts[i];
1345 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001346 }
1347 }
1348
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001349 public int getSize() {
1350 return mCounts == null ? 0 : mCounts.length;
1351 }
1352
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001353 /**
1354 * Clear state of this counter.
1355 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001356 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001357 fillArray(mCounts, 0);
1358 fillArray(mLoadedCounts, 0);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001359 fillArray(mUnpluggedCounts, 0);
1360 if (detachIfReset) {
1361 detach();
1362 }
1363 }
1364
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001365 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001366 mTimeBase.remove(this);
1367 }
1368
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001369 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001370 out.writeLongArray(mCounts);
1371 }
1372
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001373 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001374 mCounts = in.createLongArray();
1375 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1376 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001377 }
1378
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001379 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1380 if (counterArray != null) {
1381 out.writeInt(1);
1382 counterArray.writeToParcel(out);
1383 } else {
1384 out.writeInt(0);
1385 }
1386 }
1387
1388 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1389 if (in.readInt() != 0) {
1390 return new LongSamplingCounterArray(timeBase, in);
1391 } else {
1392 return null;
1393 }
1394 }
1395
1396 public static void writeSummaryToParcelLocked(Parcel out,
1397 LongSamplingCounterArray counterArray) {
1398 if (counterArray != null) {
1399 out.writeInt(1);
1400 counterArray.writeSummaryToParcelLocked(out);
1401 } else {
1402 out.writeInt(0);
1403 }
1404 }
1405
1406 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1407 TimeBase timeBase) {
1408 if (in.readInt() != 0) {
1409 final LongSamplingCounterArray counterArray
1410 = new LongSamplingCounterArray(timeBase);
1411 counterArray.readSummaryFromParcelLocked(in);
1412 return counterArray;
1413 } else {
1414 return null;
1415 }
1416 }
1417
Bookatz8c6f3c52017-05-24 12:00:17 -07001418 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001419 if (a != null) {
1420 Arrays.fill(a, val);
1421 }
1422 }
1423
Bookatz8c6f3c52017-05-24 12:00:17 -07001424 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001425 if (toSubtract == null) {
1426 return;
1427 }
1428 for (int i = 0; i < val.length; i++) {
1429 val[i] -= toSubtract[i];
1430 }
1431 }
1432
Bookatz8c6f3c52017-05-24 12:00:17 -07001433 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001434 if (src == null) {
1435 return null;
1436 } else {
1437 if (dest == null) {
1438 dest = new long[src.length];
1439 }
1440 System.arraycopy(src, 0, dest, 0, src.length);
1441 return dest;
1442 }
1443 }
1444 }
1445
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001446 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001447 final TimeBase mTimeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001448 long mCount;
1449 long mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001450 long mUnpluggedCount;
1451 long mPluggedCount;
1452
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001453 LongSamplingCounter(TimeBase timeBase, Parcel in) {
1454 mTimeBase = timeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001455 mPluggedCount = in.readLong();
1456 mCount = mPluggedCount;
1457 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001458 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001459 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001460 }
1461
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001462 LongSamplingCounter(TimeBase timeBase) {
1463 mTimeBase = timeBase;
1464 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001465 }
1466
1467 public void writeToParcel(Parcel out) {
1468 out.writeLong(mCount);
1469 out.writeLong(mLoadedCount);
1470 out.writeLong(mUnpluggedCount);
1471 }
1472
1473 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001474 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001475 mUnpluggedCount = mPluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001476 }
1477
1478 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001479 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001480 mPluggedCount = mCount;
1481 }
1482
1483 public long getCountLocked(int which) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001484 long val = mTimeBase.isRunning() ? mCount : mPluggedCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001485 if (which == STATS_SINCE_UNPLUGGED) {
1486 val -= mUnpluggedCount;
1487 } else if (which != STATS_SINCE_CHARGED) {
1488 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001489 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001490 return val;
1491 }
1492
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001493 @Override
1494 public void logState(Printer pw, String prefix) {
1495 pw.println(prefix + "mCount=" + mCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001496 + " mLoadedCount=" + mLoadedCount
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001497 + " mUnpluggedCount=" + mUnpluggedCount
1498 + " mPluggedCount=" + mPluggedCount);
1499 }
1500
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001501 void addCountLocked(long count) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001502 if (mTimeBase.isRunning()) {
1503 mCount += count;
1504 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001505 }
1506
1507 /**
1508 * Clear state of this counter.
1509 */
1510 void reset(boolean detachIfReset) {
1511 mCount = 0;
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001512 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001513 if (detachIfReset) {
1514 detach();
1515 }
1516 }
1517
1518 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001519 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001520 }
1521
1522 void writeSummaryFromParcelLocked(Parcel out) {
1523 out.writeLong(mCount);
1524 }
1525
1526 void readSummaryFromParcelLocked(Parcel in) {
1527 mLoadedCount = in.readLong();
1528 mCount = mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001529 mUnpluggedCount = mPluggedCount = mLoadedCount;
1530 }
1531 }
1532
Dianne Hackborn617f8772009-03-31 15:04:46 -07001533 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 * State for keeping track of timing information.
1535 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001536 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001537 protected final Clocks mClocks;
1538 protected final int mType;
1539 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001540
Joe Onoratoabded112016-02-08 16:49:39 -08001541 protected int mCount;
1542 protected int mLoadedCount;
1543 protected int mLastCount;
1544 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 // Times are in microseconds for better accuracy when dividing by the
1547 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 /**
1550 * The total time we have accumulated since the start of the original
1551 * boot, to the last time something interesting happened in the
1552 * current run.
1553 */
Joe Onoratoabded112016-02-08 16:49:39 -08001554 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 /**
1557 * The total time we loaded for the previous runs. Subtract this from
1558 * mTotalTime to find the time for the current run of the system.
1559 */
Joe Onoratoabded112016-02-08 16:49:39 -08001560 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 /**
1563 * The run time of the last run of the system, as loaded from the
1564 * saved data.
1565 */
Joe Onoratoabded112016-02-08 16:49:39 -08001566 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 /**
1569 * The value of mTotalTime when unplug() was last called. Subtract
1570 * this from mTotalTime to find the time since the last unplug from
1571 * power.
1572 */
Joe Onoratoabded112016-02-08 16:49:39 -08001573 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001574
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001575 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001576 * The total time this timer has been running until the latest mark has been set.
1577 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1578 */
Joe Onoratoabded112016-02-08 16:49:39 -08001579 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001580
1581 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001582 * Constructs from a parcel.
1583 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001584 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001585 * @param in
1586 */
Joe Onoratoabded112016-02-08 16:49:39 -08001587 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1588 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001590 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 mCount = in.readInt();
1593 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001594 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 mUnpluggedCount = in.readInt();
1596 mTotalTime = in.readLong();
1597 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001598 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001600 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001601 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001602 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 }
1604
Joe Onoratoabded112016-02-08 16:49:39 -08001605 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1606 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001608 mTimeBase = timeBase;
1609 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 }
Evan Millarc64edde2009-04-18 12:26:32 -07001611
1612 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001613
Evan Millarc64edde2009-04-18 12:26:32 -07001614 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001615
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001616 /**
1617 * Clear state of this timer. Returns true if the timer is inactive
1618 * so can be completely dropped.
1619 */
Joe Onoratoabded112016-02-08 16:49:39 -08001620 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001621 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001622 mCount = mLoadedCount = mLastCount = 0;
1623 if (detachIfReset) {
1624 detach();
1625 }
1626 return true;
1627 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001628
Joe Onoratoabded112016-02-08 16:49:39 -08001629 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001630 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001631 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001632
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001633 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001634 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1635 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001636 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001639 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001642 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 }
1644
Adam Lesinskie08af192015-03-25 16:42:59 -07001645 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001646 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001648 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 + " old mUnpluggedTime=" + mUnpluggedTime
1650 + " old mUnpluggedCount=" + mUnpluggedCount);
1651 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001652 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001653 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 if (DEBUG && mType < 0) {
1655 Log.v(TAG, "unplug #" + mType
1656 + ": new mUnpluggedTime=" + mUnpluggedTime
1657 + " new mUnpluggedCount=" + mUnpluggedCount);
1658 }
1659 }
1660
Adam Lesinskie08af192015-03-25 16:42:59 -07001661 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001662 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001663 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001664 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001665 + " old mTotalTime=" + mTotalTime);
1666 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001667 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001668 mCount = computeCurrentCountLocked();
1669 if (DEBUG && mType < 0) {
1670 Log.v(TAG, "plug #" + mType
1671 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
1673 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 /**
1676 * Writes a possibly null Timer to a Parcel.
1677 *
1678 * @param out the Parcel to be written to.
1679 * @param timer a Timer, or null.
1680 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001681 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 if (timer == null) {
1683 out.writeInt(0); // indicates null
1684 return;
1685 }
1686 out.writeInt(1); // indicates non-null
1687
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001688 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
1690
1691 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001692 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001693 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1694 if (which == STATS_SINCE_UNPLUGGED) {
1695 val -= mUnpluggedTime;
1696 } else if (which != STATS_SINCE_CHARGED) {
1697 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 }
1699
1700 return val;
1701 }
1702
1703 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001704 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001705 int val = computeCurrentCountLocked();
1706 if (which == STATS_SINCE_UNPLUGGED) {
1707 val -= mUnpluggedCount;
1708 } else if (which != STATS_SINCE_CHARGED) {
1709 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
1711
1712 return val;
1713 }
1714
Adam Lesinskie08af192015-03-25 16:42:59 -07001715 @Override
1716 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1717 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1718 return val - mTimeBeforeMark;
1719 }
1720
1721 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001722 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001723 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1725 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001726 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001728 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001730 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001731
1732
Joe Onoratoabded112016-02-08 16:49:39 -08001733 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001734 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1735 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001736 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001737 }
1738
Joe Onoratoabded112016-02-08 16:49:39 -08001739 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001740 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001741 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001742 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001743 mUnpluggedTime = mTotalTime;
1744 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001745 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001746 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001747
1748 // When reading the summary, we set the mark to be the latest information.
1749 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001750 }
1751 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001752
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001753 /**
1754 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1755 * method. The state of the timer according to its {@link TimeBase} will determine how much
1756 * of the value is recorded.
1757 *
1758 * If the value being recorded resets, {@link #endSample()} can be called in order to
1759 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1760 * between calls, the {@link #endSample()} is automatically called and the new value is
1761 * expected to increase monotonically from that point on.
1762 */
Joe Onoratoabded112016-02-08 16:49:39 -08001763 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001764
Evan Millarc64edde2009-04-18 12:26:32 -07001765 /**
1766 * The most recent reported count from /proc/wakelocks.
1767 */
1768 int mCurrentReportedCount;
1769
1770 /**
1771 * The reported count from /proc/wakelocks when unplug() was last
1772 * called.
1773 */
1774 int mUnpluggedReportedCount;
1775
1776 /**
1777 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001778 */
Evan Millarc64edde2009-04-18 12:26:32 -07001779 long mCurrentReportedTotalTime;
1780
1781
1782 /**
1783 * The reported total_time from /proc/wakelocks when unplug() was last
1784 * called.
1785 */
1786 long mUnpluggedReportedTotalTime;
1787
1788 /**
1789 * Whether we are currently in a discharge cycle.
1790 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001791 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001792
1793 /**
1794 * Whether we are currently recording reported values.
1795 */
1796 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001797
Evan Millarc64edde2009-04-18 12:26:32 -07001798 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001799 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001800 */
1801 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001802
Adam Lesinski98f0d462016-04-19 16:46:20 -07001803 @VisibleForTesting
1804 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001805 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001806 mCurrentReportedCount = in.readInt();
1807 mUnpluggedReportedCount = in.readInt();
1808 mCurrentReportedTotalTime = in.readLong();
1809 mUnpluggedReportedTotalTime = in.readLong();
1810 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001811 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001812 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001813
Adam Lesinski98f0d462016-04-19 16:46:20 -07001814 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001815 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001816 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001817 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001818 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001819 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001820
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001821 /**
1822 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1823 * be less than the values used for a previous invocation.
1824 */
1825 public void endSample() {
1826 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1827 mCount = computeCurrentCountLocked();
1828 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1829 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001830 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001831
Evan Millarc64edde2009-04-18 12:26:32 -07001832 public void setUpdateVersion(int version) {
1833 mUpdateVersion = version;
1834 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001835
Evan Millarc64edde2009-04-18 12:26:32 -07001836 public int getUpdateVersion() {
1837 return mUpdateVersion;
1838 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001839
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001840 /**
1841 * Updates the current recorded values. These are meant to be monotonically increasing
1842 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1843 *
1844 * If the values being recorded have been reset, the monotonically increasing requirement
1845 * will be broken. In this case, {@link #endSample()} is automatically called and
1846 * the total value of totalTime and count are recorded, starting a new monotonically
1847 * increasing sample.
1848 *
1849 * @param totalTime total time of sample in microseconds.
1850 * @param count total number of times the event being sampled occurred.
1851 */
1852 public void update(long totalTime, int count) {
1853 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001854 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001855 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001856 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001857 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001858
1859 mTrackingReportedValues = true;
1860
1861 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1862 endSample();
1863 }
1864
1865 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001866 mCurrentReportedCount = count;
1867 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001868
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001869 /**
1870 * Adds deltaTime and deltaCount to the current sample.
1871 *
1872 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1873 * @param deltaCount additional number of times the event being sampled occurred.
1874 */
1875 public void add(long deltaTime, int deltaCount) {
1876 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001877 }
1878
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001879 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001880 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
1881 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001882 if (mTrackingReportedValues) {
1883 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
1884 mUnpluggedReportedCount = mCurrentReportedCount;
1885 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001886 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07001887 }
1888
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001889 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001890 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1891 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1892 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07001893 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001894
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001895 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001896 public void logState(Printer pw, String prefix) {
1897 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001898 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07001899 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
1900 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
1901 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
1902 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001903
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001904 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001905 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001906 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001907 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
1908 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001909
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001910 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001911 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001912 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001913 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
1914 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001915
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001916 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001917 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1918 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001919 out.writeInt(mCurrentReportedCount);
1920 out.writeInt(mUnpluggedReportedCount);
1921 out.writeLong(mCurrentReportedTotalTime);
1922 out.writeLong(mUnpluggedReportedTotalTime);
1923 out.writeInt(mTrackingReportedValues ? 1 : 0);
1924 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001925
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001926 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001927 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001928 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001929 mTrackingReportedValues = false;
1930 mUnpluggedReportedTotalTime = 0;
1931 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001932 return true;
1933 }
Evan Millarc64edde2009-04-18 12:26:32 -07001934 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001935
Evan Millarc64edde2009-04-18 12:26:32 -07001936 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001937 * A timer that increments in batches. It does not run for durations, but just jumps
1938 * for a pre-determined amount.
1939 */
Joe Onoratoabded112016-02-08 16:49:39 -08001940 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001941 final Uid mUid;
1942
1943 /**
1944 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
1945 */
1946 long mLastAddedTime;
1947
1948 /**
1949 * The last duration that we added to the timer. This is in microseconds.
1950 */
1951 long mLastAddedDuration;
1952
1953 /**
1954 * Whether we are currently in a discharge cycle.
1955 */
1956 boolean mInDischarge;
1957
Joe Onoratoabded112016-02-08 16:49:39 -08001958 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
1959 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001960 mUid = uid;
1961 mLastAddedTime = in.readLong();
1962 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001963 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001964 }
1965
Joe Onoratoabded112016-02-08 16:49:39 -08001966 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
1967 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001968 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001969 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001970 }
1971
1972 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001973 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1974 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001975 out.writeLong(mLastAddedTime);
1976 out.writeLong(mLastAddedDuration);
1977 }
1978
1979 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001980 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001981 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001982 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001983 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001984 }
1985
1986 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001987 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001988 recomputeLastDuration(elapsedRealtime, false);
1989 mInDischarge = true;
1990 // If we are still within the last added duration, then re-added whatever remains.
1991 if (mLastAddedTime == elapsedRealtime) {
1992 mTotalTime += mLastAddedDuration;
1993 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001994 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001995 }
1996
1997 @Override
1998 public void logState(Printer pw, String prefix) {
1999 super.logState(pw, prefix);
2000 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
2001 + " mLastAddedDuration=" + mLastAddedDuration);
2002 }
2003
2004 private long computeOverage(long curTime) {
2005 if (mLastAddedTime > 0) {
2006 return mLastTime + mLastAddedDuration - curTime;
2007 }
2008 return 0;
2009 }
2010
2011 private void recomputeLastDuration(long curTime, boolean abort) {
2012 final long overage = computeOverage(curTime);
2013 if (overage > 0) {
2014 // Aborting before the duration ran out -- roll back the remaining
2015 // duration. Only do this if currently discharging; otherwise we didn't
2016 // actually add the time.
2017 if (mInDischarge) {
2018 mTotalTime -= overage;
2019 }
2020 if (abort) {
2021 mLastAddedTime = 0;
2022 } else {
2023 mLastAddedTime = curTime;
2024 mLastAddedDuration -= overage;
2025 }
2026 }
2027 }
2028
2029 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08002030 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002031 recomputeLastDuration(now, true);
2032 mLastAddedTime = now;
2033 mLastAddedDuration = durationMillis * 1000;
2034 if (mInDischarge) {
2035 mTotalTime += mLastAddedDuration;
2036 mCount++;
2037 }
2038 }
2039
2040 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08002041 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002042 recomputeLastDuration(now, true);
2043 }
2044
2045 @Override
2046 protected int computeCurrentCountLocked() {
2047 return mCount;
2048 }
2049
2050 @Override
2051 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08002052 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002053 if (overage > 0) {
2054 return mTotalTime = overage;
2055 }
2056 return mTotalTime;
2057 }
2058
2059 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002060 public boolean reset(boolean detachIfReset) {
2061 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002062 recomputeLastDuration(now, true);
2063 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002064 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002065 return !stillActive;
2066 }
2067 }
2068
Joe Onorato92fd23f2016-07-25 11:18:42 -07002069
2070 /**
2071 * A StopwatchTimer that also tracks the total and max individual
2072 * time spent active according to the given timebase. Whereas
2073 * StopwatchTimer apportions the time amongst all in the pool,
2074 * the total and max durations are not apportioned.
2075 */
2076 public static class DurationTimer extends StopwatchTimer {
2077 /**
2078 * The time (in ms) that the timer was last acquired or the time base
2079 * last (re-)started. Increasing the nesting depth does not reset this time.
2080 *
2081 * -1 if the timer is currently not running or the time base is not running.
2082 *
2083 * If written to a parcel, the start time is reset, as is mNesting in the base class
2084 * StopwatchTimer.
2085 */
2086 long mStartTimeMs = -1;
2087
2088 /**
Bookatz867c0d72017-03-07 18:23:42 -08002089 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002090 */
2091 long mMaxDurationMs;
2092
2093 /**
Bookatz867c0d72017-03-07 18:23:42 -08002094 * The time (in ms) that that the timer has been active since most recent
2095 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002096 */
2097 long mCurrentDurationMs;
2098
Bookatz867c0d72017-03-07 18:23:42 -08002099 /**
2100 * The total time (in ms) that that the timer has been active since most recent reset()
2101 * prior to the current startRunningLocked. This is the sum of all past currentDurations
2102 * (but not including the present currentDuration) since reset. Not pooled.
2103 */
2104 long mTotalDurationMs;
2105
Joe Onorato92fd23f2016-07-25 11:18:42 -07002106 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2107 TimeBase timeBase, Parcel in) {
2108 super(clocks, uid, type, timerPool, timeBase, in);
2109 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002110 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07002111 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002112 }
2113
2114 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2115 TimeBase timeBase) {
2116 super(clocks, uid, type, timerPool, timeBase);
2117 }
2118
2119 @Override
2120 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2121 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002122 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07002123 out.writeLong(mTotalDurationMs);
2124 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002125 }
2126
2127 /**
2128 * Write the summary to the parcel.
2129 *
2130 * Since the time base is probably meaningless after we come back, reading
2131 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08002132 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002133 */
2134 @Override
2135 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
2136 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08002137 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08002138 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07002139 }
2140
2141 /**
2142 * Read the summary parcel.
2143 *
2144 * Has the side effect of stopping the timer.
2145 */
2146 @Override
2147 public void readSummaryFromParcelLocked(Parcel in) {
2148 super.readSummaryFromParcelLocked(in);
2149 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08002150 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07002151 mStartTimeMs = -1;
2152 mCurrentDurationMs = 0;
2153 }
2154
2155 /**
2156 * The TimeBase time started (again).
2157 *
2158 * If the timer is also running, store the start time.
2159 */
2160 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
2161 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
2162 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002163 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002164 }
2165 }
2166
2167 /**
2168 * The TimeBase stopped running.
2169 *
2170 * If the timer is running, add the duration into mCurrentDurationMs.
2171 */
2172 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08002173 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
2174 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002175 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002176 // baseRealtimeUs has already been converted to the timebase's realtime.
2177 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002178 }
2179 mStartTimeMs = -1;
2180 }
2181
2182 @Override
2183 public void logState(Printer pw, String prefix) {
2184 super.logState(pw, prefix);
2185 }
2186
2187 @Override
2188 public void startRunningLocked(long elapsedRealtimeMs) {
2189 super.startRunningLocked(elapsedRealtimeMs);
2190 if (mNesting == 1 && mTimeBase.isRunning()) {
2191 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08002192 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002193 }
2194 }
2195
2196 /**
2197 * Decrements the mNesting ref-count on this timer.
2198 *
2199 * If it actually stopped (mNesting went to 0), then possibly update
2200 * mMaxDuration if the current duration was the longest ever.
2201 */
2202 @Override
2203 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08002204 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07002205 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002206 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002207 if (durationMs > mMaxDurationMs) {
2208 mMaxDurationMs = durationMs;
2209 }
2210 mStartTimeMs = -1;
2211 mCurrentDurationMs = 0;
2212 }
Kweku Adams47db5a82016-12-09 19:04:50 -08002213 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
2214 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
2215 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07002216 }
2217
2218 @Override
2219 public boolean reset(boolean detachIfReset) {
2220 boolean result = super.reset(detachIfReset);
2221 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08002222 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002223 mCurrentDurationMs = 0;
2224 if (mNesting > 0) {
2225 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
2226 } else {
2227 mStartTimeMs = -1;
2228 }
2229 return result;
2230 }
2231
2232 /**
2233 * Returns the max duration that this timer has ever seen.
2234 *
2235 * Note that this time is NOT split between the timers in the timer group that
2236 * this timer is attached to. It is the TOTAL time.
2237 */
2238 @Override
2239 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
2240 if (mNesting > 0) {
2241 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
2242 if (durationMs > mMaxDurationMs) {
2243 return durationMs;
2244 }
2245 }
2246 return mMaxDurationMs;
2247 }
2248
2249 /**
2250 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08002251 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002252 *
2253 * Note that this time is NOT split between the timers in the timer group that
2254 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07002255 *
2256 * Note that if running timer is parceled and unparceled, this method will return
2257 * current duration value at the time of parceling even though timer may not be
2258 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002259 */
2260 @Override
2261 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2262 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002263 if (mNesting > 0 && mTimeBase.isRunning()) {
2264 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2265 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002266 }
2267 return durationMs;
2268 }
Bookatz867c0d72017-03-07 18:23:42 -08002269
2270 /**
2271 * Returns the total cumulative duration that this timer has been on since reset().
2272 * If mTimerPool == null, this should be the same
2273 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2274 *
2275 * Note that this time is NOT split between the timers in the timer group that
2276 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2277 * the result will not be equivalent to getTotalTimeLocked.
2278 */
2279 @Override
2280 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2281 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2282 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002283 }
2284
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002285 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002286 * State for keeping track of timing information.
2287 */
Joe Onoratoabded112016-02-08 16:49:39 -08002288 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002289 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002290 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002291
Evan Millarc64edde2009-04-18 12:26:32 -07002292 int mNesting;
2293
Evan Millarc64edde2009-04-18 12:26:32 -07002294 /**
2295 * The last time at which we updated the timer. If mNesting is > 0,
2296 * subtract this from the current battery time to find the amount of
2297 * time we have been running since we last computed an update.
2298 */
2299 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002300
Evan Millarc64edde2009-04-18 12:26:32 -07002301 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002302 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002303 * was actually held for an interesting duration. If time base was not running when timer
2304 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002305 */
Bookatzceebafe2017-04-06 11:59:13 -07002306 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002307
Amith Yamasanif37447b2009-10-08 18:28:01 -07002308 long mTimeout;
2309
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002310 /**
2311 * For partial wake locks, keep track of whether we are in the list
2312 * to consume CPU cycles.
2313 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002314 @VisibleForTesting
2315 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002316
Joe Onoratoabded112016-02-08 16:49:39 -08002317 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002318 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002319 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002320 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002321 mTimerPool = timerPool;
2322 mUpdateTime = in.readLong();
2323 }
2324
Joe Onoratoabded112016-02-08 16:49:39 -08002325 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002326 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002327 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002328 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002329 mTimerPool = timerPool;
2330 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002331
Joe Onoratoabded112016-02-08 16:49:39 -08002332 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002333 mTimeout = timeout;
2334 }
2335
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002336 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2337 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002338 out.writeLong(mUpdateTime);
2339 }
2340
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002341 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002342 if (mNesting > 0) {
2343 if (DEBUG && mType < 0) {
2344 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2345 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002346 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2347 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002348 if (DEBUG && mType < 0) {
2349 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2350 }
2351 }
2352 }
2353
2354 public void logState(Printer pw, String prefix) {
2355 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002356 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002357 + " mAcquireTime=" + mAcquireTime);
2358 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002359
Joe Onoratoabded112016-02-08 16:49:39 -08002360 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002362 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002363 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 if (mTimerPool != null) {
2365 // Accumulate time to all currently active timers before adding
2366 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002367 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 // Add this timer to the active pool
2369 mTimerPool.add(this);
2370 }
Bookatzceebafe2017-04-06 11:59:13 -07002371 if (mTimeBase.isRunning()) {
2372 // Increment the count
2373 mCount++;
2374 mAcquireTime = mTotalTime;
2375 } else {
2376 mAcquireTime = -1;
2377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 if (DEBUG && mType < 0) {
2379 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2380 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2381 + " mAcquireTime=" + mAcquireTime);
2382 }
2383 }
2384 }
2385
Joe Onoratoabded112016-02-08 16:49:39 -08002386 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002387 return mNesting > 0;
2388 }
2389
Joe Onoratoabded112016-02-08 16:49:39 -08002390 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 // Ignore attempt to stop a timer that isn't running
2392 if (mNesting == 0) {
2393 return;
2394 }
2395 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002396 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 if (mTimerPool != null) {
2398 // Accumulate time to all active counters, scaled by the total
2399 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002400 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 // Remove this timer from the active pool
2402 mTimerPool.remove(this);
2403 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 mNesting = 1;
2405 mTotalTime = computeRunTimeLocked(batteryRealtime);
2406 mNesting = 0;
2407 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 if (DEBUG && mType < 0) {
2410 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2411 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2412 + " mAcquireTime=" + mAcquireTime);
2413 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002414
Bookatzceebafe2017-04-06 11:59:13 -07002415 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 // If there was no change in the time, then discard this
2417 // count. A somewhat cheezy strategy, but hey.
2418 mCount--;
2419 }
2420 }
2421 }
2422
Joe Onoratoabded112016-02-08 16:49:39 -08002423 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002424 if (mNesting > 0) {
2425 mNesting = 1;
2426 stopRunningLocked(elapsedRealtimeMs);
2427 }
2428 }
2429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 // Update the total time for all other running Timers with the same type as this Timer
2431 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002432 private static long refreshTimersLocked(long batteryRealtime,
2433 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002434 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 final int N = pool.size();
2436 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002437 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 long heldTime = batteryRealtime - t.mUpdateTime;
2439 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002440 final long myTime = heldTime / N;
2441 if (t == self) {
2442 selfTime = myTime;
2443 }
2444 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 }
2446 t.mUpdateTime = batteryRealtime;
2447 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002448 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 }
2450
Evan Millarc64edde2009-04-18 12:26:32 -07002451 @Override
2452 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002453 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2454 curBatteryRealtime = mUpdateTime + mTimeout;
2455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 return mTotalTime + (mNesting > 0
2457 ? (curBatteryRealtime - mUpdateTime)
2458 / (mTimerPool != null ? mTimerPool.size() : 1)
2459 : 0);
2460 }
2461
Evan Millarc64edde2009-04-18 12:26:32 -07002462 @Override
2463 protected int computeCurrentCountLocked() {
2464 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 }
2466
Adam Lesinskie08af192015-03-25 16:42:59 -07002467 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002468 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002469 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002470 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002471 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002472 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002473 }
Bookatzceebafe2017-04-06 11:59:13 -07002474 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002475 return canDetach;
2476 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002477
Adam Lesinskie08af192015-03-25 16:42:59 -07002478 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002479 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002480 super.detach();
2481 if (mTimerPool != null) {
2482 mTimerPool.remove(this);
2483 }
2484 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002485
Adam Lesinskie08af192015-03-25 16:42:59 -07002486 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002487 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002488 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 mNesting = 0;
2490 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002491
2492 /**
2493 * Set the mark so that we can query later for the total time the timer has
2494 * accumulated since this point. The timer can be running or not.
2495 *
2496 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2497 */
2498 public void setMark(long elapsedRealtimeMs) {
2499 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2500 if (mNesting > 0) {
2501 // We are running.
2502 if (mTimerPool != null) {
2503 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2504 } else {
2505 mTotalTime += batteryRealtime - mUpdateTime;
2506 mUpdateTime = batteryRealtime;
2507 }
2508 }
2509 mTimeBeforeMark = mTotalTime;
2510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002512
Bookatz867c0d72017-03-07 18:23:42 -08002513 /**
2514 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2515 * TimeBase is effectively a subset of the other.
2516 */
Bookatzaa4594a2017-03-24 12:39:56 -07002517 public static class DualTimer extends DurationTimer {
2518 // This class both is a DurationTimer and also holds a second DurationTimer.
2519 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2520 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2521 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002522 // mSubTimer typically tracks only part of the total time, such as background time, as
2523 // determined by a subTimeBase. It is NOT pooled.
2524 private final DurationTimer mSubTimer;
2525
2526 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002527 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2528 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002529 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002530 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002531 */
2532 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2533 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002534 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002535 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2536 }
2537
2538 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002539 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2540 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002541 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002542 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002543 */
2544 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2545 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002546 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002547 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2548 }
2549
Bookatz867c0d72017-03-07 18:23:42 -08002550 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002551 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002552 public DurationTimer getSubTimer() {
2553 return mSubTimer;
2554 }
2555
Bookatzaa4594a2017-03-24 12:39:56 -07002556 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002557 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002558 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002559 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2560 }
2561
Bookatzaa4594a2017-03-24 12:39:56 -07002562 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002563 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002564 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002565 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2566 }
2567
Bookatzaa4594a2017-03-24 12:39:56 -07002568 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002569 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002570 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002571 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2572 }
2573
Bookatzaa4594a2017-03-24 12:39:56 -07002574 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002575 public boolean reset(boolean detachIfReset) {
2576 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002577 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2578 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002579 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002580 return !active;
2581 }
2582
Bookatzaa4594a2017-03-24 12:39:56 -07002583 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002584 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002585 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002586 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002587 }
2588
Bookatzaa4594a2017-03-24 12:39:56 -07002589 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002590 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002591 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002592 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2593 }
2594
Bookatzaa4594a2017-03-24 12:39:56 -07002595 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002596 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002597 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002598 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2599 }
2600
Bookatzaa4594a2017-03-24 12:39:56 -07002601 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002602 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002603 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002604 mSubTimer.readSummaryFromParcelLocked(in);
2605 }
2606 }
2607
2608
Dianne Hackbornd953c532014-08-16 18:17:38 -07002609 public abstract class OverflowArrayMap<T> {
2610 private static final String OVERFLOW_NAME = "*overflow*";
2611
Dianne Hackborn657153b2016-07-29 14:54:14 -07002612 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002613 final ArrayMap<String, T> mMap = new ArrayMap<>();
2614 T mCurOverflow;
2615 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002616 long mLastOverflowTime;
2617 long mLastOverflowFinishTime;
2618 long mLastClearTime;
2619 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002620
Dianne Hackborn657153b2016-07-29 14:54:14 -07002621 public OverflowArrayMap(int uid) {
2622 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002623 }
2624
2625 public ArrayMap<String, T> getMap() {
2626 return mMap;
2627 }
2628
2629 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002630 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002631 mMap.clear();
2632 mCurOverflow = null;
2633 mActiveOverflow = null;
2634 }
2635
2636 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002637 if (name == null) {
2638 name = "";
2639 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002640 mMap.put(name, obj);
2641 if (OVERFLOW_NAME.equals(name)) {
2642 mCurOverflow = obj;
2643 }
2644 }
2645
2646 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002647 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002648 if (mActiveOverflow != null) {
2649 if (mActiveOverflow.size() == 0) {
2650 mActiveOverflow = null;
2651 }
2652 }
2653 if (mActiveOverflow == null) {
2654 // There is no currently active overflow, so we should no longer have
2655 // an overflow entry.
2656 if (mMap.containsKey(OVERFLOW_NAME)) {
2657 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2658 + mMap.get(OVERFLOW_NAME));
2659 mMap.remove(OVERFLOW_NAME);
2660 }
2661 mCurOverflow = null;
2662 } else {
2663 // There is currently active overflow, so we should still have an overflow entry.
2664 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2665 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2666 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2667 }
2668 }
2669 }
2670
2671 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002672 if (name == null) {
2673 name = "";
2674 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002675 T obj = mMap.get(name);
2676 if (obj != null) {
2677 return obj;
2678 }
2679
2680 // No object exists for the given name, but do we currently have it
2681 // running as part of the overflow?
2682 if (mActiveOverflow != null) {
2683 MutableInt over = mActiveOverflow.get(name);
2684 if (over != null) {
2685 // We are already actively counting this name in the overflow object.
2686 obj = mCurOverflow;
2687 if (obj == null) {
2688 // Shouldn't be here, but we'll try to recover.
2689 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2690 obj = mCurOverflow = instantiateObject();
2691 mMap.put(OVERFLOW_NAME, obj);
2692 }
2693 over.value++;
2694 return obj;
2695 }
2696 }
2697
2698 // No object exists for given name nor in the overflow; we need to make
2699 // a new one.
2700 final int N = mMap.size();
2701 if (N >= MAX_WAKELOCKS_PER_UID) {
2702 // Went over the limit on number of objects to track; this one goes
2703 // in to the overflow.
2704 obj = mCurOverflow;
2705 if (obj == null) {
2706 // Need to start overflow now...
2707 obj = mCurOverflow = instantiateObject();
2708 mMap.put(OVERFLOW_NAME, obj);
2709 }
2710 if (mActiveOverflow == null) {
2711 mActiveOverflow = new ArrayMap<>();
2712 }
2713 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002714 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002715 return obj;
2716 }
2717
2718 // Normal case where we just need to make a new object.
2719 obj = instantiateObject();
2720 mMap.put(name, obj);
2721 return obj;
2722 }
2723
2724 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002725 if (name == null) {
2726 name = "";
2727 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002728 T obj = mMap.get(name);
2729 if (obj != null) {
2730 return obj;
2731 }
2732
2733 // No object exists for the given name, but do we currently have it
2734 // running as part of the overflow?
2735 if (mActiveOverflow != null) {
2736 MutableInt over = mActiveOverflow.get(name);
2737 if (over != null) {
2738 // We are already actively counting this name in the overflow object.
2739 obj = mCurOverflow;
2740 if (obj != null) {
2741 over.value--;
2742 if (over.value <= 0) {
2743 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002744 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002745 }
2746 return obj;
2747 }
2748 }
2749 }
2750
2751 // Huh, they are stopping an active operation but we can't find one!
2752 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002753 StringBuilder sb = new StringBuilder();
2754 sb.append("Unable to find object for ");
2755 sb.append(name);
2756 sb.append(" in uid ");
2757 sb.append(mUid);
2758 sb.append(" mapsize=");
2759 sb.append(mMap.size());
2760 sb.append(" activeoverflow=");
2761 sb.append(mActiveOverflow);
2762 sb.append(" curoverflow=");
2763 sb.append(mCurOverflow);
2764 long now = SystemClock.elapsedRealtime();
2765 if (mLastOverflowTime != 0) {
2766 sb.append(" lastOverflowTime=");
2767 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2768 }
2769 if (mLastOverflowFinishTime != 0) {
2770 sb.append(" lastOverflowFinishTime=");
2771 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2772 }
2773 if (mLastClearTime != 0) {
2774 sb.append(" lastClearTime=");
2775 TimeUtils.formatDuration(mLastClearTime-now, sb);
2776 }
2777 if (mLastCleanupTime != 0) {
2778 sb.append(" lastCleanupTime=");
2779 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2780 }
2781 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002782 return null;
2783 }
2784
2785 public abstract T instantiateObject();
2786 }
2787
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002788 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2789 implements Parcelable {
2790 private final LongSamplingCounter mIdleTimeMillis;
Siddharth Rayb50a6842017-12-14 15:15:28 -08002791 private final LongSamplingCounter mScanTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002792 private final LongSamplingCounter mRxTimeMillis;
2793 private final LongSamplingCounter[] mTxTimeMillis;
2794 private final LongSamplingCounter mPowerDrainMaMs;
2795
2796 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2797 mIdleTimeMillis = new LongSamplingCounter(timeBase);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002798 mScanTimeMillis = new LongSamplingCounter(timeBase);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002799 mRxTimeMillis = new LongSamplingCounter(timeBase);
2800 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2801 for (int i = 0; i < numTxStates; i++) {
2802 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2803 }
2804 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2805 }
2806
2807 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2808 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002809 mScanTimeMillis = new LongSamplingCounter(timeBase, in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002810 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2811 final int recordedTxStates = in.readInt();
2812 if (recordedTxStates != numTxStates) {
2813 throw new ParcelFormatException("inconsistent tx state lengths");
2814 }
2815
2816 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2817 for (int i = 0; i < numTxStates; i++) {
2818 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2819 }
2820 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2821 }
2822
2823 public void readSummaryFromParcel(Parcel in) {
2824 mIdleTimeMillis.readSummaryFromParcelLocked(in);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002825 mScanTimeMillis.readSummaryFromParcelLocked(in);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002826 mRxTimeMillis.readSummaryFromParcelLocked(in);
2827 final int recordedTxStates = in.readInt();
2828 if (recordedTxStates != mTxTimeMillis.length) {
2829 throw new ParcelFormatException("inconsistent tx state lengths");
2830 }
2831 for (LongSamplingCounter counter : mTxTimeMillis) {
2832 counter.readSummaryFromParcelLocked(in);
2833 }
2834 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2835 }
2836
2837 @Override
2838 public int describeContents() {
2839 return 0;
2840 }
2841
2842 public void writeSummaryToParcel(Parcel dest) {
2843 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002844 mScanTimeMillis.writeSummaryFromParcelLocked(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002845 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2846 dest.writeInt(mTxTimeMillis.length);
2847 for (LongSamplingCounter counter : mTxTimeMillis) {
2848 counter.writeSummaryFromParcelLocked(dest);
2849 }
2850 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2851 }
2852
2853 @Override
2854 public void writeToParcel(Parcel dest, int flags) {
2855 mIdleTimeMillis.writeToParcel(dest);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002856 mScanTimeMillis.writeToParcel(dest);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002857 mRxTimeMillis.writeToParcel(dest);
2858 dest.writeInt(mTxTimeMillis.length);
2859 for (LongSamplingCounter counter : mTxTimeMillis) {
2860 counter.writeToParcel(dest);
2861 }
2862 mPowerDrainMaMs.writeToParcel(dest);
2863 }
2864
2865 public void reset(boolean detachIfReset) {
2866 mIdleTimeMillis.reset(detachIfReset);
Siddharth Rayb50a6842017-12-14 15:15:28 -08002867 mScanTimeMillis.reset(detachIfReset);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002868 mRxTimeMillis.reset(detachIfReset);
2869 for (LongSamplingCounter counter : mTxTimeMillis) {
2870 counter.reset(detachIfReset);
2871 }
2872 mPowerDrainMaMs.reset(detachIfReset);
2873 }
2874
2875 public void detach() {
2876 mIdleTimeMillis.detach();
Siddharth Rayb50a6842017-12-14 15:15:28 -08002877 mScanTimeMillis.detach();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002878 mRxTimeMillis.detach();
2879 for (LongSamplingCounter counter : mTxTimeMillis) {
2880 counter.detach();
2881 }
2882 mPowerDrainMaMs.detach();
2883 }
2884
2885 /**
2886 * @return a LongSamplingCounter, measuring time spent in the idle state in
2887 * milliseconds.
2888 */
2889 @Override
2890 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07002891 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002892 }
2893
2894 /**
Siddharth Rayb50a6842017-12-14 15:15:28 -08002895 * @return a LongSamplingCounter, measuring time spent in the scan state in
2896 * milliseconds.
2897 */
2898 @Override
2899 public LongSamplingCounter getScanTimeCounter() {
2900 return mScanTimeMillis;
2901 }
2902
2903 /**
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002904 * @return a LongSamplingCounter, measuring time spent in the receive state in
2905 * milliseconds.
2906 */
2907 @Override
2908 public LongSamplingCounter getRxTimeCounter() {
2909 return mRxTimeMillis;
2910 }
2911
2912 /**
2913 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
2914 * milliseconds.
2915 */
2916 @Override
2917 public LongSamplingCounter[] getTxTimeCounters() {
2918 return mTxTimeMillis;
2919 }
2920
2921 /**
2922 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
2923 */
2924 @Override
2925 public LongSamplingCounter getPowerCounter() {
2926 return mPowerDrainMaMs;
2927 }
2928 }
2929
Bookatz50df7112017-08-04 14:53:26 -07002930 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
2931 public SamplingTimer getRpmTimerLocked(String name) {
2932 SamplingTimer rpmt = mRpmStats.get(name);
2933 if (rpmt == null) {
2934 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2935 mRpmStats.put(name, rpmt);
2936 }
2937 return rpmt;
2938 }
2939
2940 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
2941 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
2942 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
2943 if (rpmt == null) {
2944 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
2945 mScreenOffRpmStats.put(name, rpmt);
2946 }
2947 return rpmt;
2948 }
2949
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002950 /*
2951 * Get the wakeup reason counter, and create a new one if one
2952 * doesn't already exist.
2953 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002954 public SamplingTimer getWakeupReasonTimerLocked(String name) {
2955 SamplingTimer timer = mWakeupReasonStats.get(name);
2956 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002957 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002958 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002959 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002960 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002961 }
2962
Evan Millarc64edde2009-04-18 12:26:32 -07002963 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002964 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07002965 * doesn't already exist.
2966 */
2967 public SamplingTimer getKernelWakelockTimerLocked(String name) {
2968 SamplingTimer kwlt = mKernelWakelockStats.get(name);
2969 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002970 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07002971 mKernelWakelockStats.put(name, kwlt);
2972 }
2973 return kwlt;
2974 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07002975
James Carr3a226052016-07-01 14:49:52 -07002976 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
2977 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
2978 if (kmt == null) {
2979 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2980 mKernelMemoryStats.put(bucket, kmt);
2981 }
2982 return kmt;
2983 }
2984
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002985 private int writeHistoryTag(HistoryTag tag) {
2986 Integer idxObj = mHistoryTagPool.get(tag);
2987 int idx;
2988 if (idxObj != null) {
2989 idx = idxObj;
2990 } else {
2991 idx = mNextHistoryTagIdx;
2992 HistoryTag key = new HistoryTag();
2993 key.setTo(tag);
2994 tag.poolIdx = idx;
2995 mHistoryTagPool.put(key, idx);
2996 mNextHistoryTagIdx++;
2997 mNumHistoryTagChars += key.string.length() + 1;
2998 }
2999 return idx;
3000 }
3001
3002 private void readHistoryTag(int index, HistoryTag tag) {
3003 tag.string = mReadHistoryStrings[index];
3004 tag.uid = mReadHistoryUids[index];
3005 tag.poolIdx = index;
3006 }
3007
Adam Lesinski926969b2016-04-28 17:31:12 -07003008 /*
3009 The history delta format uses flags to denote further data in subsequent ints in the parcel.
3010
3011 There is always the first token, which may contain the delta time, or an indicator of
3012 the length of the time (int or long) following this token.
3013
3014 First token: always present,
3015 31 23 15 7 0
3016 â–ˆM|L|K|J|I|H|G|Fâ–ˆE|D|C|B|A|T|T|Tâ–ˆT|T|T|T|T|T|T|Tâ–ˆT|T|T|T|T|T|T|Tâ–ˆ
3017
3018 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
3019 follows containing the time, and 0x7ffff indicates a long immediately follows with the
3020 delta time.
3021 A: battery level changed and an int follows with battery data.
3022 B: state changed and an int follows with state change data.
3023 C: state2 has changed and an int follows with state2 change data.
3024 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
3025 E: event data has changed and an event struct follows.
3026 F: battery charge in coulombs has changed and an int with the charge follows.
3027 G: state flag denoting that the mobile radio was active.
3028 H: state flag denoting that the wifi radio was active.
3029 I: state flag denoting that a wifi scan occurred.
3030 J: state flag denoting that a wifi full lock was held.
3031 K: state flag denoting that the gps was on.
3032 L: state flag denoting that a wakelock was held.
3033 M: state flag denoting that the cpu was running.
3034
3035 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
3036 with the time delta.
3037
3038 Battery level int: if A in the first token is set,
3039 31 23 15 7 0
3040 â–ˆL|L|L|L|L|L|L|Tâ–ˆT|T|T|T|T|T|T|Tâ–ˆT|V|V|V|V|V|V|Vâ–ˆV|V|V|V|V|V|V|Dâ–ˆ
3041
3042 D: indicates that extra history details follow.
3043 V: the battery voltage.
3044 T: the battery temperature.
3045 L: the battery level (out of 100).
3046
3047 State change int: if B in the first token is set,
3048 31 23 15 7 0
3049 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
3050
3051 A: wifi multicast was on.
3052 B: battery was plugged in.
3053 C: screen was on.
3054 D: phone was scanning for signal.
3055 E: audio was on.
3056 F: a sensor was active.
3057
3058 State2 change int: if C in the first token is set,
3059 31 23 15 7 0
3060 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
3061
3062 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
3063 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
3064 C: a bluetooth scan was active.
3065 D: the camera was active.
3066 E: bluetooth was on.
3067 F: a phone call was active.
3068 G: the device was charging.
3069 H: 2 bits indicating the device-idle (doze) state: off, light, full
3070 I: the flashlight was on.
3071 J: wifi was on.
3072 K: wifi was running.
3073 L: video was playing.
3074 M: power save mode was on.
3075
3076 Wakelock/wakereason struct: if D in the first token is set,
3077 TODO(adamlesinski): describe wakelock/wakereason struct.
3078
3079 Event struct: if E in the first token is set,
3080 TODO(adamlesinski): describe the event struct.
3081
3082 History step details struct: if D in the battery level int is set,
3083 TODO(adamlesinski): describe the history step details struct.
3084
3085 Battery charge int: if F in the first token is set, an int representing the battery charge
3086 in coulombs follows.
3087 */
3088
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003089 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003090 static final int DELTA_TIME_MASK = 0x7ffff;
3091 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
3092 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
3093 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003094 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003095 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003096 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003097 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08003098 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07003099 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003100 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07003101 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003102 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07003103 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003104 // Flag in delta int: contains the battery charge count in uAh.
3105 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003106 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07003107 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003108
3109 // These are the pieces of battery state that are packed in to the upper bits of
3110 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07003111 // in STATE_BATTERY_MASK.
3112 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003113 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
3114 static final int STATE_BATTERY_STATUS_SHIFT = 29;
3115 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
3116 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
3117 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
3118 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003119
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003120 // We use the low bit of the battery state int to indicate that we have full details
3121 // from a battery level change.
3122 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
3123
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003124 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003125 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003126 dest.writeInt(DELTA_TIME_ABS);
3127 cur.writeToParcel(dest, 0);
3128 return;
3129 }
3130
3131 final long deltaTime = cur.time - last.time;
3132 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
3133 final int lastStateInt = buildStateInt(last);
3134
3135 int deltaTimeToken;
3136 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
3137 deltaTimeToken = DELTA_TIME_LONG;
3138 } else if (deltaTime >= DELTA_TIME_ABS) {
3139 deltaTimeToken = DELTA_TIME_INT;
3140 } else {
3141 deltaTimeToken = (int)deltaTime;
3142 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003143 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003144 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
3145 ? BATTERY_DELTA_LEVEL_FLAG : 0;
3146 final boolean computeStepDetails = includeStepDetails != 0
3147 || mLastHistoryStepDetails == null;
3148 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003149 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
3150 if (batteryLevelIntChanged) {
3151 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
3152 }
3153 final int stateInt = buildStateInt(cur);
3154 final boolean stateIntChanged = stateInt != lastStateInt;
3155 if (stateIntChanged) {
3156 firstToken |= DELTA_STATE_FLAG;
3157 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003158 final boolean state2IntChanged = cur.states2 != last.states2;
3159 if (state2IntChanged) {
3160 firstToken |= DELTA_STATE2_FLAG;
3161 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003162 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003163 firstToken |= DELTA_WAKELOCK_FLAG;
3164 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003165 if (cur.eventCode != HistoryItem.EVENT_NONE) {
3166 firstToken |= DELTA_EVENT_FLAG;
3167 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003168
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003169 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
3170 if (batteryChargeChanged) {
3171 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07003172 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003173 dest.writeInt(firstToken);
3174 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3175 + " deltaTime=" + deltaTime);
3176
3177 if (deltaTimeToken >= DELTA_TIME_INT) {
3178 if (deltaTimeToken == DELTA_TIME_INT) {
3179 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
3180 dest.writeInt((int)deltaTime);
3181 } else {
3182 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
3183 dest.writeLong(deltaTime);
3184 }
3185 }
3186 if (batteryLevelIntChanged) {
3187 dest.writeInt(batteryLevelInt);
3188 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
3189 + Integer.toHexString(batteryLevelInt)
3190 + " batteryLevel=" + cur.batteryLevel
3191 + " batteryTemp=" + cur.batteryTemperature
3192 + " batteryVolt=" + (int)cur.batteryVoltage);
3193 }
3194 if (stateIntChanged) {
3195 dest.writeInt(stateInt);
3196 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
3197 + Integer.toHexString(stateInt)
3198 + " batteryStatus=" + cur.batteryStatus
3199 + " batteryHealth=" + cur.batteryHealth
3200 + " batteryPlugType=" + cur.batteryPlugType
3201 + " states=0x" + Integer.toHexString(cur.states));
3202 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003203 if (state2IntChanged) {
3204 dest.writeInt(cur.states2);
3205 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
3206 + Integer.toHexString(cur.states2));
3207 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003208 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
3209 int wakeLockIndex;
3210 int wakeReasonIndex;
3211 if (cur.wakelockTag != null) {
3212 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
3213 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3214 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3215 } else {
3216 wakeLockIndex = 0xffff;
3217 }
3218 if (cur.wakeReasonTag != null) {
3219 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
3220 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3221 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3222 } else {
3223 wakeReasonIndex = 0xffff;
3224 }
3225 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003226 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003227 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003228 int index = writeHistoryTag(cur.eventTag);
3229 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003230 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003231 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
3232 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3233 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003234 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003235 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003236 if (mPlatformIdleStateCallback != null) {
3237 mCurHistoryStepDetails.statPlatformIdleState =
3238 mPlatformIdleStateCallback.getPlatformLowPowerStats();
3239 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
3240 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00003241
3242 mCurHistoryStepDetails.statSubsystemPowerState =
3243 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
3244 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
3245 mCurHistoryStepDetails.statSubsystemPowerState);
3246
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07003247 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003248 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
3249 if (includeStepDetails != 0) {
3250 mCurHistoryStepDetails.writeToParcel(dest);
3251 }
3252 cur.stepDetails = mCurHistoryStepDetails;
3253 mLastHistoryStepDetails = mCurHistoryStepDetails;
3254 } else {
3255 cur.stepDetails = null;
3256 }
3257 if (mLastHistoryStepLevel < cur.batteryLevel) {
3258 mLastHistoryStepDetails = null;
3259 }
3260 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07003261
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003262 if (batteryChargeChanged) {
3263 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
3264 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07003265 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003266 }
3267
3268 private int buildBatteryLevelInt(HistoryItem h) {
3269 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08003270 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
3271 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
3272 }
3273
3274 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
3275 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3276 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3277 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003278 }
3279
3280 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003281 int plugType = 0;
3282 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3283 plugType = 1;
3284 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3285 plugType = 2;
3286 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3287 plugType = 3;
3288 }
3289 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3290 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3291 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003292 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003293 }
3294
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003295 private void computeHistoryStepDetails(final HistoryStepDetails out,
3296 final HistoryStepDetails last) {
3297 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3298
3299 // Perform a CPU update right after we do this collection, so we have started
3300 // collecting good data for the next step.
3301 requestImmediateCpuUpdate();
3302
3303 if (last == null) {
3304 // We are not generating a delta, so all we need to do is reset the stats
3305 // we will later be doing a delta from.
3306 final int NU = mUidStats.size();
3307 for (int i=0; i<NU; i++) {
3308 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3309 uid.mLastStepUserTime = uid.mCurStepUserTime;
3310 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3311 }
3312 mLastStepCpuUserTime = mCurStepCpuUserTime;
3313 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3314 mLastStepStatUserTime = mCurStepStatUserTime;
3315 mLastStepStatSystemTime = mCurStepStatSystemTime;
3316 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3317 mLastStepStatIrqTime = mCurStepStatIrqTime;
3318 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3319 mLastStepStatIdleTime = mCurStepStatIdleTime;
3320 tmp.clear();
3321 return;
3322 }
3323 if (DEBUG) {
3324 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3325 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3326 + " irq=" + mLastStepStatIrqTime + " sirq="
3327 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3328 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3329 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3330 + " irq=" + mCurStepStatIrqTime + " sirq="
3331 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3332 }
3333 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3334 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3335 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3336 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3337 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3338 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3339 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3340 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3341 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3342 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3343 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3344 final int NU = mUidStats.size();
3345 for (int i=0; i<NU; i++) {
3346 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3347 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3348 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3349 final int totalTime = totalUTime + totalSTime;
3350 uid.mLastStepUserTime = uid.mCurStepUserTime;
3351 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3352 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3353 continue;
3354 }
3355 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3356 out.appCpuUid3 = uid.mUid;
3357 out.appCpuUTime3 = totalUTime;
3358 out.appCpuSTime3 = totalSTime;
3359 } else {
3360 out.appCpuUid3 = out.appCpuUid2;
3361 out.appCpuUTime3 = out.appCpuUTime2;
3362 out.appCpuSTime3 = out.appCpuSTime2;
3363 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3364 out.appCpuUid2 = uid.mUid;
3365 out.appCpuUTime2 = totalUTime;
3366 out.appCpuSTime2 = totalSTime;
3367 } else {
3368 out.appCpuUid2 = out.appCpuUid1;
3369 out.appCpuUTime2 = out.appCpuUTime1;
3370 out.appCpuSTime2 = out.appCpuSTime1;
3371 out.appCpuUid1 = uid.mUid;
3372 out.appCpuUTime1 = totalUTime;
3373 out.appCpuSTime1 = totalSTime;
3374 }
3375 }
3376 }
3377 mLastStepCpuUserTime = mCurStepCpuUserTime;
3378 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3379 mLastStepStatUserTime = mCurStepStatUserTime;
3380 mLastStepStatSystemTime = mCurStepStatSystemTime;
3381 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3382 mLastStepStatIrqTime = mCurStepStatIrqTime;
3383 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3384 mLastStepStatIdleTime = mCurStepStatIdleTime;
3385 }
3386
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003387 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3388 int firstToken = src.readInt();
3389 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003390 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003391 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003392 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3393 + " deltaTimeToken=" + deltaTimeToken);
3394
3395 if (deltaTimeToken < DELTA_TIME_ABS) {
3396 cur.time += deltaTimeToken;
3397 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3398 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003399 cur.numReadInts += 2;
3400 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003401 cur.readFromParcel(src);
3402 return;
3403 } else if (deltaTimeToken == DELTA_TIME_INT) {
3404 int delta = src.readInt();
3405 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003406 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003407 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3408 } else {
3409 long delta = src.readLong();
3410 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3411 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003412 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003413 }
3414
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003415 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003416 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003417 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003418 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003419 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003420 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3421 + Integer.toHexString(batteryLevelInt)
3422 + " batteryLevel=" + cur.batteryLevel
3423 + " batteryTemp=" + cur.batteryTemperature
3424 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003425 } else {
3426 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003427 }
3428
3429 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3430 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003431 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003432 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3433 & STATE_BATTERY_STATUS_MASK);
3434 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3435 & STATE_BATTERY_HEALTH_MASK);
3436 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3437 & STATE_BATTERY_PLUG_MASK);
3438 switch (cur.batteryPlugType) {
3439 case 1:
3440 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3441 break;
3442 case 2:
3443 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3444 break;
3445 case 3:
3446 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3447 break;
3448 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003449 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003450 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3451 + Integer.toHexString(stateInt)
3452 + " batteryStatus=" + cur.batteryStatus
3453 + " batteryHealth=" + cur.batteryHealth
3454 + " batteryPlugType=" + cur.batteryPlugType
3455 + " states=0x" + Integer.toHexString(cur.states));
3456 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003457 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003458 }
3459
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003460 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3461 cur.states2 = src.readInt();
3462 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3463 + Integer.toHexString(cur.states2));
3464 }
3465
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003466 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003467 int indexes = src.readInt();
3468 int wakeLockIndex = indexes&0xffff;
3469 int wakeReasonIndex = (indexes>>16)&0xffff;
3470 if (wakeLockIndex != 0xffff) {
3471 cur.wakelockTag = cur.localWakelockTag;
3472 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3473 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3474 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3475 } else {
3476 cur.wakelockTag = null;
3477 }
3478 if (wakeReasonIndex != 0xffff) {
3479 cur.wakeReasonTag = cur.localWakeReasonTag;
3480 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3481 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3482 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3483 } else {
3484 cur.wakeReasonTag = null;
3485 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003486 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003487 } else {
3488 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003489 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003490 }
3491
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003492 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003493 cur.eventTag = cur.localEventTag;
3494 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003495 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003496 final int index = ((codeAndIndex>>16)&0xffff);
3497 readHistoryTag(index, cur.eventTag);
3498 cur.numReadInts += 1;
3499 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3500 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3501 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003502 } else {
3503 cur.eventCode = HistoryItem.EVENT_NONE;
3504 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003505
3506 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3507 cur.stepDetails = mReadHistoryStepDetails;
3508 cur.stepDetails.readFromParcel(src);
3509 } else {
3510 cur.stepDetails = null;
3511 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003512
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003513 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3514 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003515 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003516 }
3517
Dianne Hackbornfc064132014-06-02 12:42:12 -07003518 @Override
3519 public void commitCurrentHistoryBatchLocked() {
3520 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3521 }
3522
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003523 void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003524 if (!mHaveBatteryLevel || !mRecordingHistory) {
3525 return;
3526 }
3527
Dianne Hackborn40c87252014-03-19 16:55:40 -07003528 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003529 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3530 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003531 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003532 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003533 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3534 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003535 + Integer.toHexString(lastDiffStates) + " diff2="
3536 + Integer.toHexString(diffStates2) + " lastDiff2="
3537 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003538 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003539 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003540 && (diffStates2&lastDiffStates2) == 0
3541 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3542 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003543 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003544 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003545 || cur.eventCode == HistoryItem.EVENT_NONE)
3546 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3547 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3548 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3549 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3550 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3551 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003552 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003553 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003554 // as long as no bit has changed both between now and the last entry, as
3555 // well as the last entry and the one before it (so we capture any toggles).
3556 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003557 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3558 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3559 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003560 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003561 // If the last written history had a wakelock tag, we need to retain it.
3562 // Note that the condition above made sure that we aren't in a case where
3563 // both it and the current history item have a wakelock tag.
3564 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003565 cur.wakelockTag = cur.localWakelockTag;
3566 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003567 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003568 // If the last written history had a wake reason tag, we need to retain it.
3569 // Note that the condition above made sure that we aren't in a case where
3570 // both it and the current history item have a wakelock tag.
3571 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003572 cur.wakeReasonTag = cur.localWakeReasonTag;
3573 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003574 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003575 // If the last written history had an event, we need to retain it.
3576 // Note that the condition above made sure that we aren't in a case where
3577 // both it and the current history item have an event.
3578 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003579 cur.eventCode = mHistoryLastWritten.eventCode;
3580 cur.eventTag = cur.localEventTag;
3581 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003582 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003583 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003584 }
3585
Adam Lesinski45489782016-12-15 23:45:17 -08003586 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003587 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003588 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3589 // Clients can't deal with history buffers this large. This only
3590 // really happens when the device is on charger and interacted with
3591 // for long periods of time, like in retail mode. Since the device is
3592 // most likely charged, when unplugged, stats would have reset anyways.
3593 // Reset the stats and mark that we overflowed.
3594 // b/32540341
3595 resetAllStatsLocked();
3596
3597 // Mark that we want to set *OVERFLOW* event and the RESET:START
3598 // events.
3599 recordResetDueToOverflow = true;
3600
3601 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003602 if (!mHistoryOverflow) {
3603 mHistoryOverflow = true;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003604 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
3605 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003606 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003607 }
3608
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003609 // After overflow, we allow various bit-wise states to settle to 0.
3610 boolean writeAnyway = false;
3611 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3612 & mActiveHistoryStates;
3613 if (mHistoryLastWritten.states != curStates) {
3614 // mActiveHistoryStates keeps track of which bits in .states are now being
3615 // forced to 0.
3616 int old = mActiveHistoryStates;
3617 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3618 writeAnyway |= old != mActiveHistoryStates;
3619 }
3620 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3621 & mActiveHistoryStates2;
3622 if (mHistoryLastWritten.states2 != curStates2) {
3623 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3624 // forced to 0.
3625 int old = mActiveHistoryStates2;
3626 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3627 writeAnyway |= old != mActiveHistoryStates2;
3628 }
3629
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003630 // Once we've reached the maximum number of items, we only
3631 // record changes to the battery level and the most interesting states.
3632 // Once we've reached the maximum maximum number of items, we only
3633 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003634 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003635 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003636 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003637 & HistoryItem.MOST_INTERESTING_STATES) == 0
3638 || ((mHistoryLastWritten.states2^cur.states2)
3639 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003640 return;
3641 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003642
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003643 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003644 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003645 }
3646
Adam Lesinski45489782016-12-15 23:45:17 -08003647 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003648 // The history is currently empty; we need it to start with a time stamp.
3649 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003650 if (recordResetDueToOverflow) {
3651 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
3652 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003653 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_RESET, cur);
3654 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003655 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003656 }
3657
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003658 private void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd,
3659 HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003660 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003661 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003662 }
3663 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3664 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003665 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003666 mHistoryLastWritten.states &= mActiveHistoryStates;
3667 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003668 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003669 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003670 cur.wakelockTag = null;
3671 cur.wakeReasonTag = null;
3672 cur.eventCode = HistoryItem.EVENT_NONE;
3673 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003674 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3675 + " now " + mHistoryBuffer.dataPosition()
3676 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003677 }
3678
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003679 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003680 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003681
Dianne Hackborn40c87252014-03-19 16:55:40 -07003682 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003683 if (mTrackRunningHistoryElapsedRealtime != 0) {
3684 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3685 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3686 if (diffUptime < (diffElapsed-20)) {
3687 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3688 mHistoryAddTmp.setTo(mHistoryLastWritten);
3689 mHistoryAddTmp.wakelockTag = null;
3690 mHistoryAddTmp.wakeReasonTag = null;
3691 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3692 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
3693 addHistoryRecordInnerLocked(wakeElapsedTime, uptimeMs, mHistoryAddTmp);
3694 }
3695 }
3696 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3697 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3698 mTrackRunningHistoryUptime = uptimeMs;
3699 addHistoryRecordInnerLocked(elapsedRealtimeMs, uptimeMs, mHistoryCur);
3700 }
3701
3702 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
3703 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003704
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003705 if (!USE_OLD_HISTORY) {
3706 return;
3707 }
3708
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003709 if (!mHaveBatteryLevel || !mRecordingHistory) {
3710 return;
3711 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003712
3713 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003714 // and no states have since the last recorded entry changed and
3715 // are now resetting back to their original value, then just collapse
3716 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003717 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003718 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003719 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3720 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003721 // If the current is the same as the one before, then we no
3722 // longer need the entry.
3723 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003724 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003725 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003726 mHistoryLastEnd.next = null;
3727 mHistoryEnd.next = mHistoryCache;
3728 mHistoryCache = mHistoryEnd;
3729 mHistoryEnd = mHistoryLastEnd;
3730 mHistoryLastEnd = null;
3731 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003732 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3733 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003734 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003735 }
3736 return;
3737 }
3738
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003739 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003740 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003741
3742 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3743 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07003744 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003745 }
3746
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003747 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3748 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003749 // record changes to the battery level and the most interesting states.
3750 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003751 // record changes to the battery level.
3752 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003753 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003754 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003755 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003756 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003757 return;
3758 }
3759 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003760
Dianne Hackborn40c87252014-03-19 16:55:40 -07003761 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003762 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003763
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003764 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003765 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003766 mHistoryCur.eventCode = code;
3767 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3768 mHistoryCur.eventTag.string = name;
3769 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003770 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003771 }
3772
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003773 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003774 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003775 if (rec != null) {
3776 mHistoryCache = rec.next;
3777 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003778 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003779 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003780 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003781
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003782 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003783 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003784
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003785 void addHistoryRecordLocked(HistoryItem rec) {
3786 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003787 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003788 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003789 if (mHistoryEnd != null) {
3790 mHistoryEnd.next = rec;
3791 mHistoryEnd = rec;
3792 } else {
3793 mHistory = mHistoryEnd = rec;
3794 }
3795 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003796
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003797 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003798 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003799 if (USE_OLD_HISTORY) {
3800 if (mHistory != null) {
3801 mHistoryEnd.next = mHistoryCache;
3802 mHistoryCache = mHistory;
3803 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3804 }
3805 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003806 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003807
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003808 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003809 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003810 mTrackRunningHistoryElapsedRealtime = 0;
3811 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003812
3813 mHistoryBuffer.setDataSize(0);
3814 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003815 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003816 mHistoryLastLastWritten.clear();
3817 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003818 mHistoryTagPool.clear();
3819 mNextHistoryTagIdx = 0;
3820 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003821 mHistoryBufferLastPos = -1;
3822 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003823 mActiveHistoryStates = 0xffffffff;
3824 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003825 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003826
Mike Mac2f518a2017-09-19 16:06:03 -07003827 public void updateTimeBasesLocked(boolean unplugged, int screenState, long uptime,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003828 long realtime) {
Mike Maa7724752017-10-10 15:29:25 -07003829 final boolean screenOff = !isScreenOn(screenState);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003830 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3831 final boolean updateOnBatteryScreenOffTimeBase =
3832 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003833
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003834 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3835 if (updateOnBatteryScreenOffTimeBase) {
3836 updateKernelWakelocksLocked();
3837 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003838 }
Bookatz82b341172017-09-07 19:06:08 -07003839 // This if{} is only necessary due to SCREEN_OFF_RPM_STATS_ENABLED, which exists because
3840 // updateRpmStatsLocked is too slow to run each screen change. When the speed is
3841 // improved, remove the surrounding if{}.
3842 if (SCREEN_OFF_RPM_STATS_ENABLED || updateOnBatteryTimeBase) {
3843 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
3844 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003845 if (DEBUG_ENERGY_CPU) {
Mike Mac2f518a2017-09-19 16:06:03 -07003846 Slog.d(TAG, "Updating cpu time because screen is now "
3847 + Display.stateToString(screenState)
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003848 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003849 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -07003850 updateCpuTimeLocked();
Sudheer Shankae544d162017-12-28 17:06:20 -08003851 mExternalSync.scheduleCopyFromAllUidsCpuTimes(mOnBatteryTimeBase.isRunning(),
3852 mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003853
3854 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
Mike Mac2f518a2017-09-19 16:06:03 -07003855 if (updateOnBatteryTimeBase) {
3856 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3857 mUidStats.valueAt(i).updateOnBatteryBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003858 }
Mike Mac2f518a2017-09-19 16:06:03 -07003859 }
3860 if (updateOnBatteryScreenOffTimeBase) {
3861 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
3862 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3863 mUidStats.valueAt(i).updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003864 }
Bookatzc8c44962017-05-11 12:12:54 -07003865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 }
3867 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003868
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003869 private void updateBatteryPropertiesLocked() {
3870 try {
3871 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
3872 ServiceManager.getService("batteryproperties"));
3873 registrar.scheduleUpdate();
3874 } catch (RemoteException e) {
3875 // Ignore.
3876 }
3877 }
3878
Dianne Hackborn099bc622014-01-22 13:39:16 -08003879 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
3880 mIsolatedUids.put(isolatedUid, appUid);
David Chen21582962017-11-01 17:32:46 -07003881 StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid, 1);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003882 final Uid u = getUidStatsLocked(appUid);
3883 u.addIsolatedUid(isolatedUid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003884 }
3885
Adam Lesinski61db88f2015-07-01 15:05:07 -07003886 /**
3887 * Schedules a read of the latest cpu times before removing the isolated UID.
3888 * @see #removeIsolatedUidLocked(int)
3889 */
3890 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003891 int curUid = mIsolatedUids.get(isolatedUid, -1);
3892 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07003893 if (mExternalSync != null) {
3894 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
3895 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08003896 }
3897 }
3898
Adam Lesinski61db88f2015-07-01 15:05:07 -07003899 /**
3900 * This should only be called after the cpu times have been read.
3901 * @see #scheduleRemoveIsolatedUidLocked(int, int)
3902 */
3903 public void removeIsolatedUidLocked(int isolatedUid) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08003904 StatsLog.write(
3905 StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1), isolatedUid, 0);
3906 final int idx = mIsolatedUids.indexOfKey(isolatedUid);
3907 if (idx >= 0) {
3908 final int ownerUid = mIsolatedUids.valueAt(idx);
3909 final Uid u = getUidStatsLocked(ownerUid);
3910 u.removeIsolatedUid(isolatedUid);
3911 mIsolatedUids.removeAt(idx);
3912 }
3913 mKernelUidCpuTimeReader.removeUid(isolatedUid);
3914 mKernelUidCpuFreqTimeReader.removeUid(isolatedUid);
Mike Mafae87da2018-01-19 20:07:20 -08003915 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
3916 mKernelUidCpuActiveTimeReader.removeUid(isolatedUid);
3917 mKernelUidCpuClusterTimeReader.removeUid(isolatedUid);
3918 }
Adam Lesinski61db88f2015-07-01 15:05:07 -07003919 }
3920
Dianne Hackborn099bc622014-01-22 13:39:16 -08003921 public int mapUid(int uid) {
3922 int isolated = mIsolatedUids.get(uid, -1);
3923 return isolated > 0 ? isolated : uid;
3924 }
3925
3926 public void noteEventLocked(int code, String name, int uid) {
3927 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003928 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3929 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003930 }
Joe Onoratoabded112016-02-08 16:49:39 -08003931 final long elapsedRealtime = mClocks.elapsedRealtime();
3932 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003933 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003934 }
3935
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003936 boolean ensureStartClockTime(final long currentTime) {
3937 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
3938 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
3939 // If the start clock time has changed by more than a year, then presumably
3940 // the previous time was completely bogus. So we are going to figure out a
3941 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08003942 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003943 return true;
3944 }
3945 return false;
3946 }
3947
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003948 public void noteCurrentTimeChangedLocked() {
3949 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003950 final long elapsedRealtime = mClocks.elapsedRealtime();
3951 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003952 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003953 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003954 }
3955
Dianne Hackborn61659e52014-07-09 16:13:01 -07003956 public void noteProcessStartLocked(String name, int uid) {
3957 uid = mapUid(uid);
3958 if (isOnBattery()) {
3959 Uid u = getUidStatsLocked(uid);
3960 u.getProcessStatsLocked(name).incStartsLocked();
3961 }
3962 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3963 return;
3964 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003965 if (!mRecordAllHistory) {
3966 return;
3967 }
Joe Onoratoabded112016-02-08 16:49:39 -08003968 final long elapsedRealtime = mClocks.elapsedRealtime();
3969 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07003970 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
3971 }
3972
Dianne Hackborn1e01d162014-12-04 17:46:42 -08003973 public void noteProcessCrashLocked(String name, int uid) {
3974 uid = mapUid(uid);
3975 if (isOnBattery()) {
3976 Uid u = getUidStatsLocked(uid);
3977 u.getProcessStatsLocked(name).incNumCrashesLocked();
3978 }
3979 }
3980
3981 public void noteProcessAnrLocked(String name, int uid) {
3982 uid = mapUid(uid);
3983 if (isOnBattery()) {
3984 Uid u = getUidStatsLocked(uid);
3985 u.getProcessStatsLocked(name).incNumAnrsLocked();
3986 }
3987 }
3988
Dianne Hackborna8d10942015-11-19 17:55:19 -08003989 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07003990 int parentUid = mapUid(uid);
3991 if (uid != parentUid) {
3992 // Isolated UIDs process state is already rolled up into parent, so no need to track
3993 // Otherwise the parent's process state will get downgraded incorrectly
3994 return;
3995 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08003996 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003997 }
3998
3999 public void noteProcessFinishLocked(String name, int uid) {
4000 uid = mapUid(uid);
4001 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
4002 return;
4003 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004004 if (!mRecordAllHistory) {
4005 return;
4006 }
Joe Onoratoabded112016-02-08 16:49:39 -08004007 final long elapsedRealtime = mClocks.elapsedRealtime();
4008 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004009 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07004010 }
4011
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004012 public void noteSyncStartLocked(String name, int uid) {
4013 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004014 final long elapsedRealtime = mClocks.elapsedRealtime();
4015 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004016 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
4017 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
4018 return;
4019 }
4020 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
4021 }
4022
4023 public void noteSyncFinishLocked(String name, int uid) {
4024 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004025 final long elapsedRealtime = mClocks.elapsedRealtime();
4026 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004027 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
4028 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
4029 return;
4030 }
4031 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
4032 }
4033
4034 public void noteJobStartLocked(String name, int uid) {
4035 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004036 final long elapsedRealtime = mClocks.elapsedRealtime();
4037 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004038 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
4039 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
4040 return;
4041 }
4042 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
4043 }
4044
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004045 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004046 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004047 final long elapsedRealtime = mClocks.elapsedRealtime();
4048 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07004049 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07004050 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
4051 return;
4052 }
4053 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
4054 }
4055
Narayan Kamath695cf722017-12-21 18:32:47 +00004056 public void noteAlarmStartLocked(String name, WorkSource workSource, int uid) {
4057 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_START, name, workSource, uid);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004058 }
4059
Narayan Kamath695cf722017-12-21 18:32:47 +00004060 public void noteAlarmFinishLocked(String name, WorkSource workSource, int uid) {
4061 noteAlarmStartOrFinishLocked(HistoryItem.EVENT_ALARM_FINISH, name, workSource, uid);
4062 }
4063
4064 private void noteAlarmStartOrFinishLocked(int historyItem, String name, WorkSource workSource,
4065 int uid) {
Dianne Hackborn1e383822015-04-10 14:02:33 -07004066 if (!mRecordAllHistory) {
4067 return;
4068 }
Narayan Kamath695cf722017-12-21 18:32:47 +00004069
Joe Onoratoabded112016-02-08 16:49:39 -08004070 final long elapsedRealtime = mClocks.elapsedRealtime();
4071 final long uptime = mClocks.uptimeMillis();
Narayan Kamath695cf722017-12-21 18:32:47 +00004072
4073 if (workSource != null) {
4074 for (int i = 0; i < workSource.size(); ++i) {
4075 uid = mapUid(workSource.get(i));
4076 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4077 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4078 }
4079 }
4080
4081 List<WorkChain> workChains = workSource.getWorkChains();
4082 if (workChains != null) {
4083 for (int i = 0; i < workChains.size(); ++i) {
4084 uid = mapUid(workChains.get(i).getAttributionUid());
4085 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4086 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4087 }
4088 }
4089 }
4090 } else {
4091 uid = mapUid(uid);
4092
4093 if (mActiveEvents.updateState(historyItem, name, uid, 0)) {
4094 addHistoryEventLocked(elapsedRealtime, uptime, historyItem, name, uid);
4095 }
4096 }
4097 }
4098
4099 public void noteWakupAlarmLocked(String packageName, int uid, WorkSource workSource,
4100 String tag) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004101 if (workSource != null) {
4102 for (int i = 0; i < workSource.size(); ++i) {
4103 uid = workSource.get(i);
4104 final String workSourceName = workSource.getName(i);
4105
Tej Singh6f724c42018-01-03 20:02:03 -08004106 if (isOnBattery()) {
4107 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid,
4108 workSourceName != null ? workSourceName : packageName);
4109 pkg.noteWakeupAlarmLocked(tag);
4110 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004111 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, workSource.get(i),
4112 workSource.getName(i), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004113 }
4114
4115 ArrayList<WorkChain> workChains = workSource.getWorkChains();
4116 if (workChains != null) {
4117 for (int i = 0; i < workChains.size(); ++i) {
4118 final WorkChain wc = workChains.get(i);
4119 uid = wc.getAttributionUid();
4120
Tej Singh6f724c42018-01-03 20:02:03 -08004121 if (isOnBattery()) {
4122 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4123 pkg.noteWakeupAlarmLocked(tag);
4124 }
Yangster-macafad8c62018-01-05 22:30:49 -08004125 StatsLog.write(StatsLog.WAKEUP_ALARM_OCCURRED, wc.getUids(), wc.getTags(), tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004126 }
4127 }
4128 } else {
Tej Singh6f724c42018-01-03 20:02:03 -08004129 if (isOnBattery()) {
4130 BatteryStatsImpl.Uid.Pkg pkg = getPackageStatsLocked(uid, packageName);
4131 pkg.noteWakeupAlarmLocked(tag);
4132 }
Yangster-mac2f5daec2018-01-16 10:23:15 -08004133 StatsLog.write_non_chained(StatsLog.WAKEUP_ALARM_OCCURRED, uid, null, tag);
Narayan Kamath695cf722017-12-21 18:32:47 +00004134 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07004135 }
4136
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004137 private void requestWakelockCpuUpdate() {
4138 if (!mHandler.hasMessages(MSG_UPDATE_WAKELOCKS)) {
4139 Message m = mHandler.obtainMessage(MSG_UPDATE_WAKELOCKS);
4140 mHandler.sendMessageDelayed(m, DELAY_UPDATE_WAKELOCKS);
4141 }
4142 }
4143
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004144 private void requestImmediateCpuUpdate() {
4145 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
4146 mHandler.sendEmptyMessage(MSG_UPDATE_WAKELOCKS);
4147 }
4148
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004149 public void setRecordAllHistoryLocked(boolean enabled) {
4150 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004151 if (!enabled) {
4152 // Clear out any existing state.
4153 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07004154 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004155 // Record the currently running processes as stopping, now that we are no
4156 // longer tracking them.
4157 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4158 HistoryItem.EVENT_PROC);
4159 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004160 long mSecRealtime = mClocks.elapsedRealtime();
4161 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004162 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4163 SparseIntArray uids = ent.getValue();
4164 for (int j=0; j<uids.size(); j++) {
4165 addHistoryEventLocked(mSecRealtime, mSecUptime,
4166 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
4167 }
4168 }
4169 }
4170 } else {
4171 // Record the currently running processes as starting, now that we are tracking them.
4172 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
4173 HistoryItem.EVENT_PROC);
4174 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08004175 long mSecRealtime = mClocks.elapsedRealtime();
4176 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004177 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
4178 SparseIntArray uids = ent.getValue();
4179 for (int j=0; j<uids.size(); j++) {
4180 addHistoryEventLocked(mSecRealtime, mSecUptime,
4181 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
4182 }
4183 }
4184 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004185 }
4186 }
4187
Dianne Hackborn9a755432014-05-15 17:05:22 -07004188 public void setNoAutoReset(boolean enabled) {
4189 mNoAutoReset = enabled;
4190 }
4191
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004192 public void setPretendScreenOff(boolean pretendScreenOff) {
Mike Mac2f518a2017-09-19 16:06:03 -07004193 if (mPretendScreenOff != pretendScreenOff) {
4194 mPretendScreenOff = pretendScreenOff;
4195 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
4196 }
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004197 }
4198
Dianne Hackborn9a755432014-05-15 17:05:22 -07004199 private String mInitialAcquireWakeName;
4200 private int mInitialAcquireWakeUid = -1;
4201
Narayan Kamath81822022017-12-08 11:56:01 +00004202 public void noteStartWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4203 int type, boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004204 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004205 if (type == WAKE_TYPE_PARTIAL) {
4206 // Only care about partial wake locks, since full wake locks
4207 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004208 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004209 if (historyName == null) {
4210 historyName = name;
4211 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004212 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004213 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
4214 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004215 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004216 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004217 }
4218 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004219 if (mWakeLockNesting == 0) {
4220 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
4221 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
4222 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08004223 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004224 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004225 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004226 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004227 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07004228 } else if (!mWakeLockImportant && !unimportantForLogging
4229 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004230 if (mHistoryLastWritten.wakelockTag != null) {
4231 // We'll try to update the last tag.
4232 mHistoryLastWritten.wakelockTag = null;
4233 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004234 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07004235 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004236 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004237 }
4238 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004239 }
4240 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004241 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004242 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004243 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4244 // We only update the cpu time when a wake lock is acquired if the screen is off.
4245 // If the screen is on, we don't distribute the power amongst partial wakelocks.
4246 if (DEBUG_ENERGY_CPU) {
4247 Slog.d(TAG, "Updating cpu time because of +wake_lock");
4248 }
4249 requestWakelockCpuUpdate();
4250 }
Narayan Kamath81822022017-12-08 11:56:01 +00004251
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004252 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Narayan Kamath81822022017-12-08 11:56:01 +00004253
Yangster-mac20877162017-12-22 17:19:39 -08004254 if (wc != null) {
4255 StatsLog.write(
4256 StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(), type, name, 1);
Yangster-macafad8c62018-01-05 22:30:49 -08004257 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004258 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null, type, name,
4259 1);
Narayan Kamath81822022017-12-08 11:56:01 +00004260 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004261 }
4262 }
4263
Narayan Kamath81822022017-12-08 11:56:01 +00004264 public void noteStopWakeLocked(int uid, int pid, WorkChain wc, String name, String historyName,
4265 int type, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004266 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004267 if (type == WAKE_TYPE_PARTIAL) {
4268 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004269 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07004270 if (historyName == null) {
4271 historyName = name;
4272 }
4273 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
4274 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07004275 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07004276 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07004277 }
4278 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004279 if (mWakeLockNesting == 0) {
4280 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
4281 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
4282 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07004283 mInitialAcquireWakeName = null;
4284 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004285 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07004286 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004287 }
4288 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07004289 if (mOnBatteryScreenOffTimeBase.isRunning()) {
4290 if (DEBUG_ENERGY_CPU) {
4291 Slog.d(TAG, "Updating cpu time because of -wake_lock");
4292 }
4293 requestWakelockCpuUpdate();
4294 }
Narayan Kamath81822022017-12-08 11:56:01 +00004295
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004296 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Yangster-mac20877162017-12-22 17:19:39 -08004297 if (wc != null) {
4298 StatsLog.write(
4299 StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(), type, name, 0);
Yangster-macafad8c62018-01-05 22:30:49 -08004300 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004301 StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null, type, name,
4302 0);
Narayan Kamath81822022017-12-08 11:56:01 +00004303 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004304 }
4305 }
4306
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004307 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
4308 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004309 final long elapsedRealtime = mClocks.elapsedRealtime();
4310 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004311 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004312 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004313 noteStartWakeLocked(ws.get(i), pid, null, name, historyName, type,
4314 unimportantForLogging, elapsedRealtime, uptime);
4315 }
4316
4317 List<WorkChain> wcs = ws.getWorkChains();
4318 if (wcs != null) {
4319 for (int i = 0; i < wcs.size(); ++i) {
4320 final WorkChain wc = wcs.get(i);
4321 noteStartWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4322 unimportantForLogging, elapsedRealtime, uptime);
4323 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004324 }
4325 }
4326
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004327 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
4328 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004329 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08004330 final long elapsedRealtime = mClocks.elapsedRealtime();
4331 final long uptime = mClocks.uptimeMillis();
Narayan Kamath81822022017-12-08 11:56:01 +00004332
4333 List<WorkChain>[] wcs = WorkSource.diffChains(ws, newWs);
4334
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004335 // For correct semantics, we start the need worksources first, so that we won't
4336 // make inappropriate history items as if all wake locks went away and new ones
4337 // appeared. This is okay because tracking of wake locks allows nesting.
Narayan Kamath81822022017-12-08 11:56:01 +00004338 //
4339 // First the starts :
Dianne Hackborn40c87252014-03-19 16:55:40 -07004340 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004341 for (int i=0; i<NN; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004342 noteStartWakeLocked(newWs.get(i), newPid, null, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07004343 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004344 }
Narayan Kamath81822022017-12-08 11:56:01 +00004345 if (wcs != null) {
4346 List<WorkChain> newChains = wcs[0];
4347 if (newChains != null) {
4348 for (int i = 0; i < newChains.size(); ++i) {
4349 final WorkChain newChain = newChains.get(i);
4350 noteStartWakeLocked(newChain.getAttributionUid(), newPid, newChain, newName,
4351 newHistoryName, newType, newUnimportantForLogging, elapsedRealtime,
4352 uptime);
4353 }
4354 }
4355 }
4356
4357 // Then the stops :
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004358 final int NO = ws.size();
4359 for (int i=0; i<NO; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004360 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4361 uptime);
4362 }
4363 if (wcs != null) {
4364 List<WorkChain> goneChains = wcs[1];
4365 if (goneChains != null) {
4366 for (int i = 0; i < goneChains.size(); ++i) {
4367 final WorkChain goneChain = goneChains.get(i);
4368 noteStopWakeLocked(goneChain.getAttributionUid(), pid, goneChain, name,
4369 historyName, type, elapsedRealtime, uptime);
4370 }
4371 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004372 }
4373 }
4374
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004375 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
4376 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08004377 final long elapsedRealtime = mClocks.elapsedRealtime();
4378 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004379 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004380 for (int i=0; i<N; i++) {
Narayan Kamath81822022017-12-08 11:56:01 +00004381 noteStopWakeLocked(ws.get(i), pid, null, name, historyName, type, elapsedRealtime,
4382 uptime);
4383 }
4384
4385 List<WorkChain> wcs = ws.getWorkChains();
4386 if (wcs != null) {
4387 for (int i = 0; i < wcs.size(); ++i) {
4388 final WorkChain wc = wcs.get(i);
4389 noteStopWakeLocked(wc.getAttributionUid(), pid, wc, name, historyName, type,
4390 elapsedRealtime, uptime);
4391 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07004392 }
4393 }
4394
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004395 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004396 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4397 uid, null, name, historyName, 1);
Yangster-macafad8c62018-01-05 22:30:49 -08004398
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004399 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004400 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004401 }
4402
4403 public void noteLongPartialWakelockStartFromSource(String name, String historyName,
4404 WorkSource workSource) {
4405 final int N = workSource.size();
4406 for (int i = 0; i < N; ++i) {
4407 final int uid = mapUid(workSource.get(i));
4408 noteLongPartialWakeLockStartInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004409 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4410 workSource.get(i), workSource.getName(i), name, historyName, 1);
Narayan Kamath96a92562018-01-02 18:57:17 +00004411 }
4412
4413 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4414 if (workChains != null) {
4415 for (int i = 0; i < workChains.size(); ++i) {
4416 final WorkChain workChain = workChains.get(i);
4417 final int uid = workChain.getAttributionUid();
4418 noteLongPartialWakeLockStartInternal(name, historyName, uid);
4419
Yangster-macafad8c62018-01-05 22:30:49 -08004420 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4421 workChain.getUids(), workChain.getTags(), name, historyName, 1);
Narayan Kamath96a92562018-01-02 18:57:17 +00004422 }
4423 }
4424 }
4425
4426 private void noteLongPartialWakeLockStartInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004427 final long elapsedRealtime = mClocks.elapsedRealtime();
4428 final long uptime = mClocks.uptimeMillis();
4429 if (historyName == null) {
4430 historyName = name;
4431 }
4432 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
4433 0)) {
4434 return;
4435 }
4436 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
4437 historyName, uid);
4438 }
4439
4440 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08004441 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4442 uid, null, name, historyName, 0);
Yangster-macafad8c62018-01-05 22:30:49 -08004443
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004444 uid = mapUid(uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004445 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Narayan Kamath96a92562018-01-02 18:57:17 +00004446 }
4447
4448 public void noteLongPartialWakelockFinishFromSource(String name, String historyName,
4449 WorkSource workSource) {
4450 final int N = workSource.size();
4451 for (int i = 0; i < N; ++i) {
4452 final int uid = mapUid(workSource.get(i));
4453 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08004454 StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4455 workSource.get(i), workSource.getName(i), name, historyName, 0);
Narayan Kamath96a92562018-01-02 18:57:17 +00004456 }
4457
4458 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
4459 if (workChains != null) {
4460 for (int i = 0; i < workChains.size(); ++i) {
4461 final WorkChain workChain = workChains.get(i);
4462 final int uid = workChain.getAttributionUid();
Narayan Kamath96a92562018-01-02 18:57:17 +00004463 noteLongPartialWakeLockFinishInternal(name, historyName, uid);
Yangster-macafad8c62018-01-05 22:30:49 -08004464 StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
4465 workChain.getUids(), workChain.getTags(), name, historyName, 0);
Narayan Kamath96a92562018-01-02 18:57:17 +00004466 }
4467 }
4468 }
4469
4470 private void noteLongPartialWakeLockFinishInternal(String name, String historyName, int uid) {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004471 final long elapsedRealtime = mClocks.elapsedRealtime();
4472 final long uptime = mClocks.uptimeMillis();
4473 if (historyName == null) {
4474 historyName = name;
4475 }
4476 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
4477 0)) {
4478 return;
4479 }
4480 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
4481 historyName, uid);
4482 }
4483
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004484 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4485 if (mLastWakeupReason != null) {
4486 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004487 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004488 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Bookatz8c6571b2017-10-24 15:04:41 -07004489 StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason, deltaUptime * 1000);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004490 mLastWakeupReason = null;
4491 }
4492 }
4493
4494 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004495 final long elapsedRealtime = mClocks.elapsedRealtime();
4496 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004497 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004498 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004499 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004500 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4501 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004502 mHistoryCur.wakeReasonTag.uid = 0;
4503 mLastWakeupReason = reason;
4504 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004505 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004506 }
4507
Adam Lesinski72478f02015-06-17 15:39:43 -07004508 public boolean startAddingCpuLocked() {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004509 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
Adam Lesinski72478f02015-06-17 15:39:43 -07004510 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004511 }
4512
Adam Lesinski72478f02015-06-17 15:39:43 -07004513 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4514 int statSystemTime, int statIOWaitTime, int statIrqTime,
4515 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004516 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4517 + " user=" + statUserTime + " sys=" + statSystemTime
4518 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4519 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4520 mCurStepCpuUserTime += totalUTime;
4521 mCurStepCpuSystemTime += totalSTime;
4522 mCurStepStatUserTime += statUserTime;
4523 mCurStepStatSystemTime += statSystemTime;
4524 mCurStepStatIOWaitTime += statIOWaitTime;
4525 mCurStepStatIrqTime += statIrqTime;
4526 mCurStepStatSoftIrqTime += statSoftIrqTime;
4527 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004528 }
4529
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004530 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004531 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004532 Uid u = mUidStats.get(uid);
4533 if (u != null) {
4534 u.mPids.remove(pid);
4535 }
4536 }
4537
4538 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004539 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004540 Uid u = mUidStats.get(uid);
4541 if (u != null) {
4542 Uid.Pid p = u.mPids.get(pid);
4543 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004544 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004545 }
4546 }
4547 return 0;
4548 }
4549
Dianne Hackborn287952c2010-09-22 22:34:31 -07004550 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004551 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004552 Uid u = mUidStats.get(uid);
4553 if (u != null) {
4554 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4555 }
4556 }
4557
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004558 int mSensorNesting;
4559
4560 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004561 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004562 final long elapsedRealtime = mClocks.elapsedRealtime();
4563 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004564 if (mSensorNesting == 0) {
4565 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4566 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4567 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004568 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004569 }
4570 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004571 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004572 }
4573
4574 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004575 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004576 final long elapsedRealtime = mClocks.elapsedRealtime();
4577 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004578 mSensorNesting--;
4579 if (mSensorNesting == 0) {
4580 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4581 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4582 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004583 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004584 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004585 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004586 }
4587
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004588 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004589
Narayan Kamath32684dd2018-01-08 17:32:51 +00004590 public void noteGpsChangedLocked(WorkSource oldWs, WorkSource newWs) {
4591 for (int i = 0; i < newWs.size(); ++i) {
4592 noteStartGpsLocked(newWs.get(i), null);
4593 }
4594
4595 for (int i = 0; i < oldWs.size(); ++i) {
4596 noteStopGpsLocked((oldWs.get(i)), null);
4597 }
4598
4599 List<WorkChain>[] wcs = WorkSource.diffChains(oldWs, newWs);
4600 if (wcs != null) {
4601 if (wcs[0] != null) {
4602 final List<WorkChain> newChains = wcs[0];
4603 for (int i = 0; i < newChains.size(); ++i) {
4604 noteStartGpsLocked(-1, newChains.get(i));
4605 }
4606 }
4607
4608 if (wcs[1] != null) {
4609 final List<WorkChain> goneChains = wcs[1];
4610 for (int i = 0; i < goneChains.size(); ++i) {
4611 noteStopGpsLocked(-1, goneChains.get(i));
4612 }
4613 }
4614 }
4615 }
4616
4617 private void noteStartGpsLocked(int uid, WorkChain workChain) {
4618 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004619 final long elapsedRealtime = mClocks.elapsedRealtime();
4620 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004621 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004622 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004623 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4624 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004625 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004626 }
4627 mGpsNesting++;
Narayan Kamath32684dd2018-01-08 17:32:51 +00004628
4629 if (workChain == null) {
4630 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null, 1);
4631 } else {
4632 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
4633 workChain.getUids(), workChain.getTags(), 1);
4634 }
4635
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004636 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004638
Narayan Kamath32684dd2018-01-08 17:32:51 +00004639 private void noteStopGpsLocked(int uid, WorkChain workChain) {
4640 uid = getAttributionUid(uid, workChain);
Joe Onoratoabded112016-02-08 16:49:39 -08004641 final long elapsedRealtime = mClocks.elapsedRealtime();
4642 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004643 mGpsNesting--;
4644 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004645 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004646 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4647 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004648 addHistoryRecordLocked(elapsedRealtime, uptime);
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004649 stopAllGpsSignalQualityTimersLocked(-1);
4650 mGpsSignalQualityBin = -1;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004651 }
Narayan Kamath32684dd2018-01-08 17:32:51 +00004652
4653 if (workChain == null) {
4654 StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null, 0);
4655 } else {
4656 StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
4657 workChain.getTags(), 0);
4658 }
4659
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004660 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004661 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004662
Siddharth Ray78ccaf52017-12-23 16:16:21 -08004663 public void noteGpsSignalQualityLocked(int signalLevel) {
4664 if (mGpsNesting == 0) {
4665 return;
4666 }
4667 if (signalLevel < 0 || signalLevel >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
4668 stopAllGpsSignalQualityTimersLocked(-1);
4669 return;
4670 }
4671 final long elapsedRealtime = mClocks.elapsedRealtime();
4672 final long uptime = mClocks.uptimeMillis();
4673 if (mGpsSignalQualityBin != signalLevel) {
4674 if (mGpsSignalQualityBin >= 0) {
4675 mGpsSignalQualityTimer[mGpsSignalQualityBin].stopRunningLocked(elapsedRealtime);
4676 }
4677 if(!mGpsSignalQualityTimer[signalLevel].isRunningLocked()) {
4678 mGpsSignalQualityTimer[signalLevel].startRunningLocked(elapsedRealtime);
4679 }
4680 mHistoryCur.states2 = (mHistoryCur.states2&~HistoryItem.STATE2_GPS_SIGNAL_QUALITY_MASK)
4681 | (signalLevel << HistoryItem.STATE2_GPS_SIGNAL_QUALITY_SHIFT);
4682 addHistoryRecordLocked(elapsedRealtime, uptime);
4683 mGpsSignalQualityBin = signalLevel;
4684 }
4685 return;
4686 }
4687
Jeff Browne95c3cd2014-05-02 16:59:26 -07004688 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004689 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004690
4691 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4692 // original 4 are mapped to one of the originals.
4693 if (state > MAX_TRACKED_SCREEN_STATE) {
4694 switch (state) {
4695 case Display.STATE_VR:
4696 state = Display.STATE_ON;
4697 break;
4698 default:
4699 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4700 break;
4701 }
4702 }
4703
Jeff Browne95c3cd2014-05-02 16:59:26 -07004704 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004705 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004706 final int oldState = mScreenState;
4707 mScreenState = state;
4708 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4709 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004710
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004711 if (state != Display.STATE_UNKNOWN) {
4712 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004713 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4714 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4715 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004716 } else {
4717 Slog.wtf(TAG, "Unexpected screen state: " + state);
4718 }
4719 }
4720
Mike Mac2f518a2017-09-19 16:06:03 -07004721 final long elapsedRealtime = mClocks.elapsedRealtime();
4722 final long uptime = mClocks.uptimeMillis();
4723
4724 boolean updateHistory = false;
4725 if (isScreenDoze(state)) {
4726 mHistoryCur.states |= HistoryItem.STATE_SCREEN_DOZE_FLAG;
4727 mScreenDozeTimer.startRunningLocked(elapsedRealtime);
4728 updateHistory = true;
4729 } else if (isScreenDoze(oldState)) {
4730 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_DOZE_FLAG;
4731 mScreenDozeTimer.stopRunningLocked(elapsedRealtime);
4732 updateHistory = true;
4733 }
4734 if (isScreenOn(state)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004735 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4736 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4737 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004738 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4739 if (mScreenBrightnessBin >= 0) {
4740 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4741 }
Mike Mac2f518a2017-09-19 16:06:03 -07004742 updateHistory = true;
4743 } else if (isScreenOn(oldState)) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07004744 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4745 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4746 + Integer.toHexString(mHistoryCur.states));
Jeff Browne95c3cd2014-05-02 16:59:26 -07004747 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4748 if (mScreenBrightnessBin >= 0) {
4749 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4750 }
Mike Mac2f518a2017-09-19 16:06:03 -07004751 updateHistory = true;
4752 }
4753 if (updateHistory) {
4754 if (DEBUG_HISTORY) Slog.v(TAG, "Screen state to: "
4755 + Display.stateToString(state));
4756 addHistoryRecordLocked(elapsedRealtime, uptime);
4757 }
4758 if (isScreenOn(state)) {
4759 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
4760 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
4761 // Fake a wake lock, so we consider the device waked as long as the screen is on.
Narayan Kamath81822022017-12-08 11:56:01 +00004762 noteStartWakeLocked(-1, -1, null, "screen", null, WAKE_TYPE_PARTIAL, false,
Mike Mac2f518a2017-09-19 16:06:03 -07004763 elapsedRealtime, uptime);
4764 } else if (isScreenOn(oldState)) {
Narayan Kamath81822022017-12-08 11:56:01 +00004765 noteStopWakeLocked(-1, -1, null, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004766 elapsedRealtime, uptime);
Mike Mac2f518a2017-09-19 16:06:03 -07004767 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), state,
Joe Onoratoabded112016-02-08 16:49:39 -08004768 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Mike Mac2f518a2017-09-19 16:06:03 -07004769 }
4770 // Update discharge amounts.
4771 if (mOnBatteryInternal) {
4772 updateDischargeScreenLevelsLocked(oldState, state);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004773 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004774 }
4775 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004776
Dianne Hackborn617f8772009-03-31 15:04:46 -07004777 public void noteScreenBrightnessLocked(int brightness) {
4778 // Bin the brightness.
4779 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4780 if (bin < 0) bin = 0;
4781 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4782 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004783 final long elapsedRealtime = mClocks.elapsedRealtime();
4784 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004785 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4786 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004787 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4788 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004789 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004790 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004791 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004792 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004793 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004794 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004795 }
4796 mScreenBrightnessBin = bin;
4797 }
4798 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004799
Dianne Hackborn617f8772009-03-31 15:04:46 -07004800 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004801 if (mOnBatteryInternal) {
4802 uid = mapUid(uid);
4803 getUidStatsLocked(uid).noteUserActivityLocked(event);
4804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004805 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004806
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004807 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004808 final long elapsedRealtime = mClocks.elapsedRealtime();
4809 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004810 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4811 reason, reasonUid);
4812 }
4813
Jeff Browne95c3cd2014-05-02 16:59:26 -07004814 public void noteInteractiveLocked(boolean interactive) {
4815 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08004816 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004817 mInteractive = interactive;
4818 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
4819 if (interactive) {
4820 mInteractiveTimer.startRunningLocked(elapsedRealtime);
4821 } else {
4822 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
4823 }
4824 }
4825 }
4826
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004827 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004828 final long elapsedRealtime = mClocks.elapsedRealtime();
4829 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004830 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4831 extra, type);
4832 mNumConnectivityChange++;
4833 }
4834
Adam Lesinski5f056f62016-07-14 16:56:08 -07004835 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4836 final long uptimeMillis, int uid) {
4837 uid = mapUid(uid);
4838 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4839 uid);
4840 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4841 }
4842
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004843 /**
4844 * Updates the radio power state and returns true if an external stats collection should occur.
4845 */
4846 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004847 final long elapsedRealtime = mClocks.elapsedRealtime();
4848 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004849 if (mMobileRadioPowerState != powerState) {
4850 long realElapsedRealtimeMs;
4851 final boolean active =
4852 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4853 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4854 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004855 if (uid > 0) {
4856 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4857 }
4858
Adam Lesinski9acfd812016-04-19 18:29:50 -07004859 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004860 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4861 } else {
4862 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004863 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004864 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4865 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4866 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004867 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004868 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4869 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4870 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004871 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004872 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4873 }
4874 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4875 + Integer.toHexString(mHistoryCur.states));
4876 addHistoryRecordLocked(elapsedRealtime, uptime);
4877 mMobileRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08004878 StatsLog.write(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004879 if (active) {
4880 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4881 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4882 } else {
4883 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004884 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004885 // Tell the caller to collect radio network/power stats.
4886 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004887 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004888 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004889 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004890 }
4891
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004892 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004893 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004894 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4895 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4896 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004897 final long elapsedRealtime = mClocks.elapsedRealtime();
4898 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004899 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004900 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004901 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4902 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004903 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004904 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004905 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004906 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4907 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004908 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004909 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004910 }
4911 addHistoryRecordLocked(elapsedRealtime, uptime);
Bookatzc1a050a2017-10-10 15:49:28 -07004912 StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ? 1 : 0);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004913 }
4914 }
4915
Bookatzddccf0a2017-11-28 16:48:14 -08004916 public void noteDeviceIdleModeLocked(final int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004917 final long elapsedRealtime = mClocks.elapsedRealtime();
4918 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004919 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004920 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004921 // We don't go out of general idling mode until explicitly taken out of
4922 // device idle through going active or significant motion.
4923 nowIdling = true;
4924 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004925 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
4926 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
4927 // We don't go out of general light idling mode until explicitly taken out of
4928 // device idle through going active or significant motion.
4929 nowLightIdling = true;
4930 }
4931 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
4932 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
4933 activeReason, activeUid);
4934 }
Bookatzddccf0a2017-11-28 16:48:14 -08004935 if (mDeviceIdling != nowIdling || mDeviceLightIdling != nowLightIdling) {
4936 int statsmode;
4937 if (nowIdling) statsmode = DEVICE_IDLE_MODE_DEEP;
4938 else if (nowLightIdling) statsmode = DEVICE_IDLE_MODE_LIGHT;
4939 else statsmode = DEVICE_IDLE_MODE_OFF;
4940 StatsLog.write(StatsLog.DEVICE_IDLING_MODE_STATE_CHANGED, statsmode);
4941 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004942 if (mDeviceIdling != nowIdling) {
4943 mDeviceIdling = nowIdling;
4944 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
4945 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
4946 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004947 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004948 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
4949 } else {
4950 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
4951 }
4952 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004953 if (mDeviceLightIdling != nowLightIdling) {
4954 mDeviceLightIdling = nowLightIdling;
4955 if (nowLightIdling) {
4956 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004957 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004958 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004959 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004960 }
4961 if (mDeviceIdleMode != mode) {
4962 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
4963 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
4964 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
4965 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004966 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004967 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
4968 mLastIdleTimeStart = elapsedRealtime;
4969 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
4970 if (lastDuration > mLongestLightIdleTime) {
4971 mLongestLightIdleTime = lastDuration;
4972 }
4973 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004974 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004975 if (lastDuration > mLongestFullIdleTime) {
4976 mLongestFullIdleTime = lastDuration;
4977 }
4978 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
4979 }
4980 if (mode == DEVICE_IDLE_MODE_LIGHT) {
4981 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004982 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004983 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
4984 }
4985 mDeviceIdleMode = mode;
Bookatzddccf0a2017-11-28 16:48:14 -08004986 StatsLog.write(StatsLog.DEVICE_IDLE_MODE_STATE_CHANGED, mode);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004987 }
4988 }
4989
Dianne Hackborn3accca02013-09-20 09:32:11 -07004990 public void notePackageInstalledLocked(String pkgName, long versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08004991 final long elapsedRealtime = mClocks.elapsedRealtime();
4992 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3accca02013-09-20 09:32:11 -07004993 // XXX need to figure out what to do with long version codes.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004994 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
Dianne Hackborn3accca02013-09-20 09:32:11 -07004995 pkgName, (int)versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004996 PackageChange pc = new PackageChange();
4997 pc.mPackageName = pkgName;
4998 pc.mUpdate = true;
4999 pc.mVersionCode = versionCode;
5000 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005001 }
5002
5003 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08005004 final long elapsedRealtime = mClocks.elapsedRealtime();
5005 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005006 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
5007 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005008 PackageChange pc = new PackageChange();
5009 pc.mPackageName = pkgName;
5010 pc.mUpdate = true;
5011 addPackageChange(pc);
5012 }
5013
5014 private void addPackageChange(PackageChange pc) {
5015 if (mDailyPackageChanges == null) {
5016 mDailyPackageChanges = new ArrayList<>();
5017 }
5018 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005019 }
5020
Siddharth Ray78ccaf52017-12-23 16:16:21 -08005021 void stopAllGpsSignalQualityTimersLocked(int except) {
5022 final long elapsedRealtime = mClocks.elapsedRealtime();
5023 for (int i = 0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
5024 if (i == except) {
5025 continue;
5026 }
5027 while (mGpsSignalQualityTimer[i].isRunningLocked()) {
5028 mGpsSignalQualityTimer[i].stopRunningLocked(elapsedRealtime);
5029 }
5030 }
5031 }
5032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005033 public void notePhoneOnLocked() {
5034 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005035 final long elapsedRealtime = mClocks.elapsedRealtime();
5036 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005037 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005038 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
5039 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005040 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005041 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005042 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005043 }
5044 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005046 public void notePhoneOffLocked() {
5047 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005048 final long elapsedRealtime = mClocks.elapsedRealtime();
5049 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005050 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005051 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
5052 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005053 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005054 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005055 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005056 }
5057 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005058
Dianne Hackborn3251b902014-06-20 14:40:53 -07005059 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005060 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08005061 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005062 if (i == except) {
5063 continue;
5064 }
5065 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005066 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005067 }
5068 }
5069 }
5070
Dianne Hackborne4a59512010-12-07 11:08:07 -08005071 private int fixPhoneServiceState(int state, int signalBin) {
5072 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
5073 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5074 // to infer that we are scanning from other data.
5075 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08005076 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005077 state = ServiceState.STATE_IN_SERVICE;
5078 }
5079 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005080
Dianne Hackborne4a59512010-12-07 11:08:07 -08005081 return state;
5082 }
5083
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005084 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005085 boolean scanning = false;
5086 boolean newHistory = false;
5087
5088 mPhoneServiceStateRaw = state;
5089 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005090 mPhoneSignalStrengthBinRaw = strengthBin;
5091
Joe Onoratoabded112016-02-08 16:49:39 -08005092 final long elapsedRealtime = mClocks.elapsedRealtime();
5093 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005094
5095 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
5096 // In this case we will always be STATE_OUT_OF_SERVICE, so need
5097 // to infer that we are scanning from other data.
5098 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005099 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005100 state = ServiceState.STATE_IN_SERVICE;
5101 }
5102 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005103
5104 // If the phone is powered off, stop all timers.
5105 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005106 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005107
Dianne Hackborne4a59512010-12-07 11:08:07 -08005108 // If we are in service, make sure the correct signal string timer is running.
5109 } else if (state == ServiceState.STATE_IN_SERVICE) {
5110 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005111
5112 // If we're out of service, we are in the lowest signal strength
5113 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07005114 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005115 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005116 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07005117 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005118 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005119 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005120 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
5121 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005122 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005123 }
5124 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005125
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005126 if (!scanning) {
5127 // If we are no longer scanning, then stop the scanning timer.
5128 if (mPhoneSignalScanningTimer.isRunningLocked()) {
5129 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
5130 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
5131 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005132 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005133 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07005134 }
5135 }
5136
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005137 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005138 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
5139 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005140 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005141 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08005142 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005143 mPhoneServiceState = state;
5144 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08005145
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005146 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08005147 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005148 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005149 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005150 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005151 if (strengthBin >= 0) {
5152 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005153 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005154 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07005155 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
5156 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005157 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08005158 + Integer.toHexString(mHistoryCur.states));
5159 newHistory = true;
Bookatze5885242017-10-24 20:10:31 -07005160 StatsLog.write(StatsLog.PHONE_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005161 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005162 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005163 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005164 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08005165 }
5166
5167 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07005168 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08005169 }
5170 }
5171
5172 /**
5173 * Telephony stack updates the phone state.
5174 * @param state phone state from ServiceState.getState()
5175 */
5176 public void notePhoneStateLocked(int state, int simState) {
5177 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07005178 }
5179
Wink Savillee9b06d72009-05-18 21:47:50 -07005180 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07005181 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08005182 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08005183 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005184 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005185
Dianne Hackborn627bba72009-03-24 22:32:56 -07005186 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
5187 int bin = DATA_CONNECTION_NONE;
5188 if (hasData) {
5189 switch (dataType) {
5190 case TelephonyManager.NETWORK_TYPE_EDGE:
5191 bin = DATA_CONNECTION_EDGE;
5192 break;
5193 case TelephonyManager.NETWORK_TYPE_GPRS:
5194 bin = DATA_CONNECTION_GPRS;
5195 break;
5196 case TelephonyManager.NETWORK_TYPE_UMTS:
5197 bin = DATA_CONNECTION_UMTS;
5198 break;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005199 case TelephonyManager.NETWORK_TYPE_CDMA:
5200 bin = DATA_CONNECTION_CDMA;
5201 break;
5202 case TelephonyManager.NETWORK_TYPE_EVDO_0:
5203 bin = DATA_CONNECTION_EVDO_0;
5204 break;
5205 case TelephonyManager.NETWORK_TYPE_EVDO_A:
5206 bin = DATA_CONNECTION_EVDO_A;
5207 break;
5208 case TelephonyManager.NETWORK_TYPE_1xRTT:
5209 bin = DATA_CONNECTION_1xRTT;
5210 break;
5211 case TelephonyManager.NETWORK_TYPE_HSDPA:
5212 bin = DATA_CONNECTION_HSDPA;
5213 break;
5214 case TelephonyManager.NETWORK_TYPE_HSUPA:
5215 bin = DATA_CONNECTION_HSUPA;
5216 break;
5217 case TelephonyManager.NETWORK_TYPE_HSPA:
5218 bin = DATA_CONNECTION_HSPA;
5219 break;
5220 case TelephonyManager.NETWORK_TYPE_IDEN:
5221 bin = DATA_CONNECTION_IDEN;
5222 break;
5223 case TelephonyManager.NETWORK_TYPE_EVDO_B:
5224 bin = DATA_CONNECTION_EVDO_B;
5225 break;
Robert Greenwalt962a9902010-11-02 11:10:25 -07005226 case TelephonyManager.NETWORK_TYPE_LTE:
5227 bin = DATA_CONNECTION_LTE;
5228 break;
5229 case TelephonyManager.NETWORK_TYPE_EHRPD:
5230 bin = DATA_CONNECTION_EHRPD;
5231 break;
Patrick Tjinb71703c2013-11-06 09:27:03 -08005232 case TelephonyManager.NETWORK_TYPE_HSPAP:
5233 bin = DATA_CONNECTION_HSPAP;
5234 break;
Dianne Hackborn627bba72009-03-24 22:32:56 -07005235 default:
5236 bin = DATA_CONNECTION_OTHER;
5237 break;
5238 }
5239 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07005240 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005241 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005242 final long elapsedRealtime = mClocks.elapsedRealtime();
5243 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005244 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
5245 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005246 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
5247 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005248 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005249 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005250 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005251 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005252 }
5253 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005254 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005255 }
5256 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005257
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005258 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07005259 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08005260 final long elapsedRealtime = mClocks.elapsedRealtime();
5261 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005262 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005263 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
5264 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005265 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005266 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005267 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005268 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005269 }
5270 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005271
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005272 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08005273 final long elapsedRealtime = mClocks.elapsedRealtime();
5274 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07005275 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07005276 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005277 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
5278 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005279 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005280 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005281 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005282 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07005283 }
5284 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005285
5286 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005287 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005288 final long elapsedRealtime = mClocks.elapsedRealtime();
5289 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005290 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005291 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005292 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
5293 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005294 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005295 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005296 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005297 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005298 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005299 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005300
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005301 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005302 if (mAudioOnNesting == 0) {
5303 return;
5304 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005305 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005306 final long elapsedRealtime = mClocks.elapsedRealtime();
5307 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005308 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005309 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005310 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5311 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005312 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005313 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005314 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005315 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005316 }
5317
5318 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005319 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005320 final long elapsedRealtime = mClocks.elapsedRealtime();
5321 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005322 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005323 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005324 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
5325 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005326 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005327 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005328 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005329 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005330 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005331 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005332
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005333 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005334 if (mVideoOnNesting == 0) {
5335 return;
5336 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08005337 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005338 final long elapsedRealtime = mClocks.elapsedRealtime();
5339 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005340 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005341 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005342 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5343 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005344 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005345 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005346 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005347 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005348 }
5349
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005350 public void noteResetAudioLocked() {
5351 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005352 final long elapsedRealtime = mClocks.elapsedRealtime();
5353 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005354 mAudioOnNesting = 0;
5355 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
5356 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
5357 + Integer.toHexString(mHistoryCur.states));
5358 addHistoryRecordLocked(elapsedRealtime, uptime);
5359 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
5360 for (int i=0; i<mUidStats.size(); i++) {
5361 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5362 uid.noteResetAudioLocked(elapsedRealtime);
5363 }
5364 }
5365 }
5366
5367 public void noteResetVideoLocked() {
5368 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005369 final long elapsedRealtime = mClocks.elapsedRealtime();
5370 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07005371 mAudioOnNesting = 0;
5372 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
5373 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
5374 + Integer.toHexString(mHistoryCur.states));
5375 addHistoryRecordLocked(elapsedRealtime, uptime);
5376 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
5377 for (int i=0; i<mUidStats.size(); i++) {
5378 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5379 uid.noteResetVideoLocked(elapsedRealtime);
5380 }
5381 }
5382 }
5383
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005384 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005385 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005386 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005387 }
5388
5389 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005390 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005391 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005392 }
5393
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005394 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005395 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005396 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
5397 }
5398
5399 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005400 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005401 getUidStatsLocked(uid).noteVibratorOffLocked();
5402 }
5403
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005404 public void noteFlashlightOnLocked(int uid) {
5405 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005406 final long elapsedRealtime = mClocks.elapsedRealtime();
5407 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005408 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005409 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
5410 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005411 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005412 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005413 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
5414 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005415 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
5416 }
5417
5418 public void noteFlashlightOffLocked(int uid) {
5419 if (mFlashlightOnNesting == 0) {
5420 return;
5421 }
5422 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005423 final long elapsedRealtime = mClocks.elapsedRealtime();
5424 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005425 if (--mFlashlightOnNesting == 0) {
5426 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5427 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
5428 + Integer.toHexString(mHistoryCur.states2));
5429 addHistoryRecordLocked(elapsedRealtime, uptime);
5430 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
5431 }
5432 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
5433 }
5434
5435 public void noteCameraOnLocked(int uid) {
5436 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005437 final long elapsedRealtime = mClocks.elapsedRealtime();
5438 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005439 if (mCameraOnNesting++ == 0) {
5440 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
5441 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
5442 + Integer.toHexString(mHistoryCur.states2));
5443 addHistoryRecordLocked(elapsedRealtime, uptime);
5444 mCameraOnTimer.startRunningLocked(elapsedRealtime);
5445 }
5446 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
5447 }
5448
5449 public void noteCameraOffLocked(int uid) {
5450 if (mCameraOnNesting == 0) {
5451 return;
5452 }
5453 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005454 final long elapsedRealtime = mClocks.elapsedRealtime();
5455 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005456 if (--mCameraOnNesting == 0) {
5457 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5458 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5459 + Integer.toHexString(mHistoryCur.states2));
5460 addHistoryRecordLocked(elapsedRealtime, uptime);
5461 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
5462 }
5463 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
5464 }
5465
5466 public void noteResetCameraLocked() {
5467 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005468 final long elapsedRealtime = mClocks.elapsedRealtime();
5469 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005470 mCameraOnNesting = 0;
5471 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
5472 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
5473 + Integer.toHexString(mHistoryCur.states2));
5474 addHistoryRecordLocked(elapsedRealtime, uptime);
5475 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
5476 for (int i=0; i<mUidStats.size(); i++) {
5477 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5478 uid.noteResetCameraLocked(elapsedRealtime);
5479 }
5480 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005481 }
5482
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005483 public void noteResetFlashlightLocked() {
5484 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08005485 final long elapsedRealtime = mClocks.elapsedRealtime();
5486 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005487 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005488 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
5489 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005490 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005491 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005492 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
5493 for (int i=0; i<mUidStats.size(); i++) {
5494 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5495 uid.noteResetFlashlightLocked(elapsedRealtime);
5496 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005497 }
5498 }
5499
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005500 private void noteBluetoothScanStartedLocked(WorkChain workChain, int uid,
5501 boolean isUnoptimized) {
5502 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005503 final long elapsedRealtime = mClocks.elapsedRealtime();
5504 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005505 if (mBluetoothScanNesting == 0) {
5506 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5507 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
5508 + Integer.toHexString(mHistoryCur.states2));
5509 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005510 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005511 }
5512 mBluetoothScanNesting++;
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005513
Yangster-macafad8c62018-01-05 22:30:49 -08005514 if (workChain != null) {
5515 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
5516 workChain.getUids(), workChain.getTags(), 1);
5517 if (isUnoptimized) {
5518 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
5519 workChain.getUids(), workChain.getTags(), 1);
5520 }
5521 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005522 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null, 1);
Yangster-macafad8c62018-01-05 22:30:49 -08005523 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005524 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
5525 1);
Yangster-macafad8c62018-01-05 22:30:49 -08005526 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005527 }
5528
Bookatzb1f04f32017-05-19 13:57:32 -07005529 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005530 if (workChain != null) {
5531 getUidStatsLocked(uid).addBluetoothWorkChain(workChain, isUnoptimized);
5532 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005533 }
5534
Bookatzb1f04f32017-05-19 13:57:32 -07005535 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005536 final int N = ws.size();
5537 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005538 noteBluetoothScanStartedLocked(null, ws.get(i), isUnoptimized);
5539 }
5540
5541 final List<WorkChain> workChains = ws.getWorkChains();
5542 if (workChains != null) {
5543 for (int i = 0; i < workChains.size(); ++i) {
5544 noteBluetoothScanStartedLocked(workChains.get(i), -1, isUnoptimized);
5545 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005546 }
5547 }
5548
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005549 private void noteBluetoothScanStoppedLocked(WorkChain workChain, int uid,
5550 boolean isUnoptimized) {
5551 uid = getAttributionUid(uid, workChain);
Bookatz867c0d72017-03-07 18:23:42 -08005552 final long elapsedRealtime = mClocks.elapsedRealtime();
5553 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005554 mBluetoothScanNesting--;
5555 if (mBluetoothScanNesting == 0) {
5556 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5557 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
5558 + Integer.toHexString(mHistoryCur.states2));
5559 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07005560 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005561 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005562
Yangster-macafad8c62018-01-05 22:30:49 -08005563 if (workChain != null) {
5564 StatsLog.write(
5565 StatsLog.BLE_SCAN_STATE_CHANGED, workChain.getUids(), workChain.getTags(), 0);
5566 if (isUnoptimized) {
5567 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
5568 workChain.getUids(), workChain.getTags(), 0);
5569 }
5570 } else {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005571 StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null, 0);
Yangster-macafad8c62018-01-05 22:30:49 -08005572 if (isUnoptimized) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08005573 StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
5574 0);
Yangster-macafad8c62018-01-05 22:30:49 -08005575 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005576 }
5577
Bookatz94c5a312017-07-11 16:49:17 -07005578 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005579 if (workChain != null) {
5580 getUidStatsLocked(uid).removeBluetoothWorkChain(workChain, isUnoptimized);
5581 }
5582 }
5583
5584 private int getAttributionUid(int uid, WorkChain workChain) {
5585 if (workChain != null) {
5586 return mapUid(workChain.getAttributionUid());
5587 }
5588
5589 return mapUid(uid);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005590 }
5591
Bookatz94c5a312017-07-11 16:49:17 -07005592 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005593 final int N = ws.size();
5594 for (int i = 0; i < N; i++) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005595 noteBluetoothScanStoppedLocked(null, ws.get(i), isUnoptimized);
5596 }
5597
5598 final List<WorkChain> workChains = ws.getWorkChains();
5599 if (workChains != null) {
5600 for (int i = 0; i < workChains.size(); ++i) {
5601 noteBluetoothScanStoppedLocked(workChains.get(i), -1, isUnoptimized);
5602 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005603 }
5604 }
5605
5606 public void noteResetBluetoothScanLocked() {
5607 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08005608 final long elapsedRealtime = mClocks.elapsedRealtime();
5609 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005610 mBluetoothScanNesting = 0;
5611 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
5612 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
5613 + Integer.toHexString(mHistoryCur.states2));
5614 addHistoryRecordLocked(elapsedRealtime, uptime);
5615 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005616
5617
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005618 for (int i=0; i<mUidStats.size(); i++) {
5619 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
5620 uid.noteResetBluetoothScanLocked(elapsedRealtime);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005621
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005622 List<WorkChain> allWorkChains = uid.getAllBluetoothWorkChains();
5623 if (allWorkChains != null) {
5624 for (int j = 0; j < allWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005625 StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005626 allWorkChains.get(j).getUids(),
5627 allWorkChains.get(j).getTags(), 0);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005628 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005629 allWorkChains.clear();
5630 }
5631
5632 List<WorkChain> unoptimizedWorkChains = uid.getUnoptimizedBluetoothWorkChains();
5633 if (unoptimizedWorkChains != null) {
5634 for (int j = 0; j < unoptimizedWorkChains.size(); ++j) {
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005635 StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
Yangster-macafad8c62018-01-05 22:30:49 -08005636 unoptimizedWorkChains.get(j).getUids(),
5637 unoptimizedWorkChains.get(j).getTags(), 0);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005638 }
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005639 unoptimizedWorkChains.clear();
5640 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005641 }
5642 }
5643 }
5644
Bookatz4ebc0642017-05-11 12:21:19 -07005645 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07005646 final int N = ws.size();
5647 for (int i = 0; i < N; i++) {
5648 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07005649 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005650 StatsLog.write_non_chained(StatsLog.BLE_SCAN_RESULT_RECEIVED, ws.get(i), ws.getName(i),
5651 numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005652 }
5653
5654 final List<WorkChain> workChains = ws.getWorkChains();
5655 if (workChains != null) {
5656 for (int i = 0; i < workChains.size(); ++i) {
5657 final WorkChain wc = workChains.get(i);
5658 int uid = mapUid(wc.getAttributionUid());
5659 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Yangster-macafad8c62018-01-05 22:30:49 -08005660 StatsLog.write(StatsLog.BLE_SCAN_RESULT_RECEIVED,
5661 wc.getUids(), wc.getTags(), numNewResults);
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00005662 }
Bookatz956f36bf2017-04-28 09:48:17 -07005663 }
5664 }
5665
Adam Lesinski5f056f62016-07-14 16:56:08 -07005666 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
5667 final long uptimeMillis, int uid) {
5668 uid = mapUid(uid);
5669 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
5670 uid);
5671 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
5672 }
5673
5674 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005675 final long elapsedRealtime = mClocks.elapsedRealtime();
5676 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005677 if (mWifiRadioPowerState != powerState) {
5678 final boolean active =
5679 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5680 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5681 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005682 if (uid > 0) {
5683 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5684 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005685 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005686 mWifiActiveTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005687 } else {
5688 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
Siddharth Rayb50a6842017-12-14 15:15:28 -08005689 mWifiActiveTimer.stopRunningLocked(
5690 timestampNs / (1000 * 1000));
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005691 }
5692 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5693 + Integer.toHexString(mHistoryCur.states));
5694 addHistoryRecordLocked(elapsedRealtime, uptime);
5695 mWifiRadioPowerState = powerState;
Bookatzddccf0a2017-11-28 16:48:14 -08005696 StatsLog.write(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, powerState);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005697 }
5698 }
5699
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005700 public void noteWifiRunningLocked(WorkSource ws) {
5701 if (!mGlobalWifiRunning) {
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 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005705 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5706 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005707 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005708 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005709 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005710 int N = ws.size();
5711 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005712 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005713 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005714 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005715
5716 List<WorkChain> workChains = ws.getWorkChains();
5717 if (workChains != null) {
5718 for (int i = 0; i < workChains.size(); ++i) {
5719 int uid = mapUid(workChains.get(i).getAttributionUid());
5720 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5721 }
5722 }
5723
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005724 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005725 } else {
5726 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005727 }
5728 }
5729
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005730 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5731 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005732 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005733 int N = oldWs.size();
5734 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005735 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005736 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005737 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005738
5739 List<WorkChain> workChains = oldWs.getWorkChains();
5740 if (workChains != null) {
5741 for (int i = 0; i < workChains.size(); ++i) {
5742 int uid = mapUid(workChains.get(i).getAttributionUid());
5743 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5744 }
5745 }
5746
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005747 N = newWs.size();
5748 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005749 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005750 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005751 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005752
5753 workChains = newWs.getWorkChains();
5754 if (workChains != null) {
5755 for (int i = 0; i < workChains.size(); ++i) {
5756 int uid = mapUid(workChains.get(i).getAttributionUid());
5757 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
5758 }
5759 }
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005760 } else {
5761 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5762 }
5763 }
5764
5765 public void noteWifiStoppedLocked(WorkSource ws) {
5766 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005767 final long elapsedRealtime = mClocks.elapsedRealtime();
5768 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005769 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005770 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5771 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005772 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005773 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005774 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005775 int N = ws.size();
5776 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005777 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005778 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005779 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00005780
5781 List<WorkChain> workChains = ws.getWorkChains();
5782 if (workChains != null) {
5783 for (int i = 0; i < workChains.size(); ++i) {
5784 int uid = mapUid(workChains.get(i).getAttributionUid());
5785 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
5786 }
5787 }
5788
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005789 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005790 } else {
5791 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005792 }
5793 }
5794
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005795 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5796 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5797 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005798 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005799 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005800 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005801 }
5802 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005803 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005804 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005805 }
5806 }
5807
Dianne Hackborn3251b902014-06-20 14:40:53 -07005808 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5809 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5810 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005811 final long elapsedRealtime = mClocks.elapsedRealtime();
5812 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005813 if (mWifiSupplState >= 0) {
5814 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5815 }
5816 mWifiSupplState = supplState;
5817 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5818 mHistoryCur.states2 =
5819 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5820 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5821 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5822 + Integer.toHexString(mHistoryCur.states2));
5823 addHistoryRecordLocked(elapsedRealtime, uptime);
5824 }
5825 }
5826
5827 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005828 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005829 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5830 if (i == except) {
5831 continue;
5832 }
5833 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5834 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5835 }
5836 }
5837 }
5838
5839 public void noteWifiRssiChangedLocked(int newRssi) {
5840 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5841 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5842 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005843 final long elapsedRealtime = mClocks.elapsedRealtime();
5844 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005845 if (mWifiSignalStrengthBin >= 0) {
5846 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5847 elapsedRealtime);
5848 }
5849 if (strengthBin >= 0) {
5850 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5851 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Bookatze5885242017-10-24 20:10:31 -07005852 StatsLog.write(StatsLog.WIFI_SIGNAL_STRENGTH_CHANGED, strengthBin);
Dianne Hackborn3251b902014-06-20 14:40:53 -07005853 }
5854 mHistoryCur.states2 =
5855 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5856 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5857 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5858 + Integer.toHexString(mHistoryCur.states2));
5859 addHistoryRecordLocked(elapsedRealtime, uptime);
5860 } else {
5861 stopAllWifiSignalStrengthTimersLocked(-1);
5862 }
5863 mWifiSignalStrengthBin = strengthBin;
5864 }
5865 }
5866
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005867 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005868
The Android Open Source Project10592532009-03-18 17:39:46 -07005869 public void noteFullWifiLockAcquiredLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005870 final long elapsedRealtime = mClocks.elapsedRealtime();
5871 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005872 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005873 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005874 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5875 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005876 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005877 }
5878 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005879 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005880 }
5881
5882 public void noteFullWifiLockReleasedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005883 final long elapsedRealtime = mClocks.elapsedRealtime();
5884 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005885 mWifiFullLockNesting--;
5886 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005887 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005888 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
5889 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005890 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005891 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005892 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005893 }
5894
Nick Pelly6ccaa542012-06-15 15:22:47 -07005895 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005896
Nick Pelly6ccaa542012-06-15 15:22:47 -07005897 public void noteWifiScanStartedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005898 final long elapsedRealtime = mClocks.elapsedRealtime();
5899 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005900 if (mWifiScanNesting == 0) {
5901 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
5902 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005903 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005904 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005905 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07005906 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005907 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005908 }
5909
Nick Pelly6ccaa542012-06-15 15:22:47 -07005910 public void noteWifiScanStoppedLocked(int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005911 final long elapsedRealtime = mClocks.elapsedRealtime();
5912 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005913 mWifiScanNesting--;
5914 if (mWifiScanNesting == 0) {
5915 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
5916 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005917 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005918 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005919 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005920 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005921 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005922
Robert Greenwalta029ea12013-09-25 16:38:12 -07005923 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005924 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005925 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005926 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005927 }
5928
5929 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005930 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005931 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005932 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005933 }
5934
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005935 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005936
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005937 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005938 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005939 final long elapsedRealtime = mClocks.elapsedRealtime();
5940 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005941 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005942 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005943 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
5944 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005945 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08005946
5947 // Start Wifi Multicast overall timer
5948 if (!mWifiMulticastWakelockTimer.isRunningLocked()) {
5949 if (DEBUG_HISTORY) Slog.v(TAG, "WiFi Multicast Overall Timer Started");
5950 mWifiMulticastWakelockTimer.startRunningLocked(elapsedRealtime);
5951 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005952 }
5953 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005954 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005955 }
5956
5957 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005958 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005959 final long elapsedRealtime = mClocks.elapsedRealtime();
5960 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005961 mWifiMulticastNesting--;
5962 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005963 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005964 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
5965 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005966 addHistoryRecordLocked(elapsedRealtime, uptime);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08005967
5968 // Stop Wifi Multicast overall timer
5969 if (mWifiMulticastWakelockTimer.isRunningLocked()) {
5970 if (DEBUG_HISTORY) Slog.v(TAG, "Multicast Overall Timer Stopped");
5971 mWifiMulticastWakelockTimer.stopRunningLocked(elapsedRealtime);
5972 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005973 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005974 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005975 }
5976
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005977 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
5978 int N = ws.size();
5979 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00005980 final int uid = mapUid(ws.get(i));
5981 noteFullWifiLockAcquiredLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08005982 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i), 1);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005983 }
5984
5985 final List<WorkChain> workChains = ws.getWorkChains();
5986 if (workChains != null) {
5987 for (int i = 0; i < workChains.size(); ++i) {
5988 final WorkChain workChain = workChains.get(i);
5989 final int uid = mapUid(workChain.getAttributionUid());
5990 noteFullWifiLockAcquiredLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08005991 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
5992 workChain.getUids(), workChain.getTags(), 1);
Narayan Kamath728c8a02017-12-28 15:48:07 +00005993 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005994 }
5995 }
5996
5997 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
5998 int N = ws.size();
5999 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006000 final int uid = mapUid(ws.get(i));
6001 noteFullWifiLockReleasedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006002 StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i), 0);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006003 }
6004
6005 final List<WorkChain> workChains = ws.getWorkChains();
6006 if (workChains != null) {
6007 for (int i = 0; i < workChains.size(); ++i) {
6008 final WorkChain workChain = workChains.get(i);
6009 final int uid = mapUid(workChain.getAttributionUid());
6010 noteFullWifiLockReleasedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006011 StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
6012 workChain.getUids(), workChain.getTags(), 0);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006013 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006014 }
6015 }
6016
Nick Pelly6ccaa542012-06-15 15:22:47 -07006017 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006018 int N = ws.size();
6019 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006020 final int uid = mapUid(ws.get(i));
6021 noteWifiScanStartedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006022 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
6023 1);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006024 }
6025
6026 final List<WorkChain> workChains = ws.getWorkChains();
6027 if (workChains != null) {
6028 for (int i = 0; i < workChains.size(); ++i) {
6029 final WorkChain workChain = workChains.get(i);
6030 final int uid = mapUid(workChain.getAttributionUid());
6031 noteWifiScanStartedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006032 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
6033 workChain.getTags(), 1);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006034 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006035 }
6036 }
6037
Nick Pelly6ccaa542012-06-15 15:22:47 -07006038 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006039 int N = ws.size();
6040 for (int i=0; i<N; i++) {
Narayan Kamath728c8a02017-12-28 15:48:07 +00006041 final int uid = mapUid(ws.get(i));
6042 noteWifiScanStoppedLocked(uid);
Yangster-mac2f5daec2018-01-16 10:23:15 -08006043 StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
6044 0);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006045 }
6046
6047 final List<WorkChain> workChains = ws.getWorkChains();
6048 if (workChains != null) {
6049 for (int i = 0; i < workChains.size(); ++i) {
6050 final WorkChain workChain = workChains.get(i);
6051 final int uid = mapUid(workChain.getAttributionUid());
6052 noteWifiScanStoppedLocked(uid);
Yangster-macafad8c62018-01-05 22:30:49 -08006053 StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
6054 workChain.getUids(), workChain.getTags(), 0);
Narayan Kamath728c8a02017-12-28 15:48:07 +00006055 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07006056 }
6057 }
6058
Robert Greenwalta029ea12013-09-25 16:38:12 -07006059 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
6060 int N = ws.size();
6061 for (int i=0; i<N; i++) {
6062 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
6063 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006064
6065 final List<WorkChain> workChains = ws.getWorkChains();
6066 if (workChains != null) {
6067 for (int i = 0; i < workChains.size(); ++i) {
6068 noteWifiBatchedScanStartedLocked(workChains.get(i).getAttributionUid(), csph);
6069 }
6070 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006071 }
6072
6073 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
6074 int N = ws.size();
6075 for (int i=0; i<N; i++) {
6076 noteWifiBatchedScanStoppedLocked(ws.get(i));
6077 }
Narayan Kamath728c8a02017-12-28 15:48:07 +00006078
6079 final List<WorkChain> workChains = ws.getWorkChains();
6080 if (workChains != null) {
6081 for (int i = 0; i < workChains.size(); ++i) {
6082 noteWifiBatchedScanStoppedLocked(workChains.get(i).getAttributionUid());
6083 }
6084 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006085 }
6086
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08006087 private static String[] includeInStringArray(String[] array, String str) {
6088 if (ArrayUtils.indexOf(array, str) >= 0) {
6089 return array;
6090 }
6091 String[] newArray = new String[array.length+1];
6092 System.arraycopy(array, 0, newArray, 0, array.length);
6093 newArray[array.length] = str;
6094 return newArray;
6095 }
6096
6097 private static String[] excludeFromStringArray(String[] array, String str) {
6098 int index = ArrayUtils.indexOf(array, str);
6099 if (index >= 0) {
6100 String[] newArray = new String[array.length-1];
6101 if (index > 0) {
6102 System.arraycopy(array, 0, newArray, 0, index);
6103 }
6104 if (index < array.length-1) {
6105 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
6106 }
6107 return newArray;
6108 }
6109 return array;
6110 }
6111
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006112 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07006113 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006114
Adam Lesinski14ae39a2017-05-26 11:50:40 -07006115 synchronized (mModemNetworkLock) {
6116 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
6117 mModemIfaces = includeInStringArray(mModemIfaces, iface);
6118 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
6119 } else {
6120 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
6121 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
6122 }
6123 }
6124
6125 synchronized (mWifiNetworkLock) {
6126 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
6127 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
6128 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
6129 } else {
6130 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
6131 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
6132 }
6133 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07006134 }
6135
David Chenc8a43242017-10-17 16:23:28 -07006136 public String[] getWifiIfaces() {
6137 synchronized (mWifiNetworkLock) {
6138 return mWifiIfaces;
6139 }
6140 }
6141
6142 public String[] getMobileIfaces() {
6143 synchronized (mModemNetworkLock) {
6144 return mModemIfaces;
6145 }
6146 }
6147
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006148 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
6149 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006151
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006152 @Override public int getScreenOnCount(int which) {
6153 return mScreenOnTimer.getCountLocked(which);
6154 }
6155
Mike Mac2f518a2017-09-19 16:06:03 -07006156 @Override public long getScreenDozeTime(long elapsedRealtimeUs, int which) {
6157 return mScreenDozeTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6158 }
6159
6160 @Override public int getScreenDozeCount(int which) {
6161 return mScreenDozeTimer.getCountLocked(which);
6162 }
6163
Dianne Hackborn617f8772009-03-31 15:04:46 -07006164 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006165 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006166 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006167 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006168 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006169
Kweku Adams87b19ec2017-10-09 12:40:03 -07006170 @Override public Timer getScreenBrightnessTimer(int brightnessBin) {
6171 return mScreenBrightnessTimer[brightnessBin];
6172 }
6173
Jeff Browne95c3cd2014-05-02 16:59:26 -07006174 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
6175 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006176 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006177
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006178 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
6179 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006180 }
6181
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006182 @Override public int getPowerSaveModeEnabledCount(int which) {
6183 return mPowerSaveModeEnabledTimer.getCountLocked(which);
6184 }
6185
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006186 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
6187 int which) {
6188 switch (mode) {
6189 case DEVICE_IDLE_MODE_LIGHT:
6190 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006191 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006192 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6193 }
6194 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07006195 }
6196
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006197 @Override public int getDeviceIdleModeCount(int mode, int which) {
6198 switch (mode) {
6199 case DEVICE_IDLE_MODE_LIGHT:
6200 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006201 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006202 return mDeviceIdleModeFullTimer.getCountLocked(which);
6203 }
6204 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07006205 }
6206
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006207 @Override public long getLongestDeviceIdleModeTime(int mode) {
6208 switch (mode) {
6209 case DEVICE_IDLE_MODE_LIGHT:
6210 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006211 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006212 return mLongestFullIdleTime;
6213 }
6214 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006215 }
6216
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006217 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
6218 switch (mode) {
6219 case DEVICE_IDLE_MODE_LIGHT:
6220 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006221 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006222 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6223 }
6224 return 0;
6225 }
6226
6227 @Override public int getDeviceIdlingCount(int mode, int which) {
6228 switch (mode) {
6229 case DEVICE_IDLE_MODE_LIGHT:
6230 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07006231 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07006232 return mDeviceIdlingTimer.getCountLocked(which);
6233 }
6234 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07006235 }
6236
Dianne Hackborn1e01d162014-12-04 17:46:42 -08006237 @Override public int getNumConnectivityChange(int which) {
6238 int val = mNumConnectivityChange;
6239 if (which == STATS_CURRENT) {
6240 val -= mLoadedNumConnectivityChange;
6241 } else if (which == STATS_SINCE_UNPLUGGED) {
6242 val -= mUnpluggedNumConnectivityChange;
6243 }
6244 return val;
6245 }
6246
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006247 @Override public long getGpsSignalQualityTime(int strengthBin,
6248 long elapsedRealtimeUs, int which) {
6249 if (strengthBin < 0 || strengthBin >= GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS) {
6250 return 0;
6251 }
6252 return mGpsSignalQualityTimer[strengthBin].getTotalTimeLocked(
6253 elapsedRealtimeUs, which);
6254 }
6255
6256 @Override public long getGpsBatteryDrainMaMs() {
Siddharth Ray0ed2e952018-01-22 11:32:14 -08006257 final double opVolt = mPowerProfile.getAveragePower(
6258 PowerProfile.POWER_GPS_OPERATING_VOLTAGE) / 1000.0;
6259 if (opVolt == 0) {
6260 return 0;
6261 }
6262 double energyUsedMaMs = 0.0;
6263 final int which = STATS_SINCE_CHARGED;
6264 final long rawRealtime = SystemClock.elapsedRealtime() * 1000;
6265 for(int i=0; i < GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
6266 energyUsedMaMs
6267 += mPowerProfile.getAveragePower(PowerProfile.POWER_GPS_SIGNAL_QUALITY_BASED, i)
6268 * (getGpsSignalQualityTime(i, rawRealtime, which) / 1000);
6269 }
6270 return (long) energyUsedMaMs;
Siddharth Ray78ccaf52017-12-23 16:16:21 -08006271 }
6272
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006273 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
6274 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006276
Dianne Hackborn77b987f2014-02-26 16:20:52 -08006277 @Override public int getPhoneOnCount(int which) {
6278 return mPhoneOnTimer.getCountLocked(which);
6279 }
6280
Dianne Hackborn627bba72009-03-24 22:32:56 -07006281 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006282 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006283 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006284 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006285 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07006286
6287 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006288 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07006289 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006290 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07006291 }
6292
Kweku Adams87b19ec2017-10-09 12:40:03 -07006293 @Override public Timer getPhoneSignalScanningTimer() {
6294 return mPhoneSignalScanningTimer;
6295 }
6296
Catherine Liufb900812012-07-17 14:12:56 -05006297 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
6298 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006299 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006300
Kweku Adams87b19ec2017-10-09 12:40:03 -07006301 @Override public Timer getPhoneSignalStrengthTimer(int strengthBin) {
6302 return mPhoneSignalStrengthsTimer[strengthBin];
6303 }
6304
Dianne Hackborn627bba72009-03-24 22:32:56 -07006305 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006306 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006307 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006308 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07006309 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006310
Dianne Hackborn617f8772009-03-31 15:04:46 -07006311 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07006312 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006313 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006314
Kweku Adams87b19ec2017-10-09 12:40:03 -07006315 @Override public Timer getPhoneDataConnectionTimer(int dataType) {
6316 return mPhoneDataConnectionsTimer[dataType];
6317 }
6318
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006319 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
6320 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08006321 }
6322
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006323 @Override public int getMobileRadioActiveCount(int which) {
6324 return mMobileRadioActiveTimer.getCountLocked(which);
6325 }
6326
Dianne Hackborna1bd7922014-03-21 11:07:11 -07006327 @Override public long getMobileRadioActiveAdjustedTime(int which) {
6328 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
6329 }
6330
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006331 @Override public long getMobileRadioActiveUnknownTime(int which) {
6332 return mMobileRadioActiveUnknownTime.getCountLocked(which);
6333 }
6334
6335 @Override public int getMobileRadioActiveUnknownCount(int which) {
6336 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
6337 }
6338
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08006339 @Override public long getWifiMulticastWakelockTime(
6340 long elapsedRealtimeUs, int which) {
6341 return mWifiMulticastWakelockTimer.getTotalTimeLocked(
6342 elapsedRealtimeUs, which);
6343 }
6344
6345 @Override public int getWifiMulticastWakelockCount(int which) {
6346 return mWifiMulticastWakelockTimer.getCountLocked(which);
6347 }
6348
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006349 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
6350 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006351 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006352
Siddharth Rayb50a6842017-12-14 15:15:28 -08006353 @Override public long getWifiActiveTime(long elapsedRealtimeUs, int which) {
6354 return mWifiActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6355 }
6356
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006357 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
6358 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07006359 }
6360
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006361 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006362 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006363 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006364 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08006365 }
6366
6367 @Override public int getWifiStateCount(int wifiState, int which) {
6368 return mWifiStateTimer[wifiState].getCountLocked(which);
6369 }
6370
Kweku Adams87b19ec2017-10-09 12:40:03 -07006371 @Override public Timer getWifiStateTimer(int wifiState) {
6372 return mWifiStateTimer[wifiState];
6373 }
6374
Dianne Hackborn3251b902014-06-20 14:40:53 -07006375 @Override public long getWifiSupplStateTime(int state,
6376 long elapsedRealtimeUs, int which) {
6377 return mWifiSupplStateTimer[state].getTotalTimeLocked(
6378 elapsedRealtimeUs, which);
6379 }
6380
6381 @Override public int getWifiSupplStateCount(int state, int which) {
6382 return mWifiSupplStateTimer[state].getCountLocked(which);
6383 }
6384
Kweku Adams87b19ec2017-10-09 12:40:03 -07006385 @Override public Timer getWifiSupplStateTimer(int state) {
6386 return mWifiSupplStateTimer[state];
6387 }
6388
Dianne Hackborn3251b902014-06-20 14:40:53 -07006389 @Override public long getWifiSignalStrengthTime(int strengthBin,
6390 long elapsedRealtimeUs, int which) {
6391 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
6392 elapsedRealtimeUs, which);
6393 }
6394
6395 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
6396 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
6397 }
6398
Kweku Adams87b19ec2017-10-09 12:40:03 -07006399 @Override public Timer getWifiSignalStrengthTimer(int strengthBin) {
6400 return mWifiSignalStrengthsTimer[strengthBin];
6401 }
6402
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006403 @Override
6404 public ControllerActivityCounter getBluetoothControllerActivity() {
6405 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006406 }
6407
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006408 @Override
6409 public ControllerActivityCounter getWifiControllerActivity() {
6410 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07006411 }
6412
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006413 @Override
6414 public ControllerActivityCounter getModemControllerActivity() {
6415 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07006416 }
6417
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006418 @Override
6419 public boolean hasBluetoothActivityReporting() {
6420 return mHasBluetoothReporting;
6421 }
6422
6423 @Override
6424 public boolean hasWifiActivityReporting() {
6425 return mHasWifiReporting;
6426 }
6427
6428 @Override
6429 public boolean hasModemActivityReporting() {
6430 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07006431 }
6432
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006433 @Override
6434 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006435 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6436 }
6437
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006438 @Override
6439 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07006440 return mFlashlightOnTimer.getCountLocked(which);
6441 }
6442
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006443 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07006444 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
6445 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6446 }
6447
6448 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006449 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
6450 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
6451 }
6452
6453 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006454 public long getNetworkActivityBytes(int type, int which) {
6455 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
6456 return mNetworkByteActivityCounters[type].getCountLocked(which);
6457 } else {
6458 return 0;
6459 }
6460 }
6461
6462 @Override
6463 public long getNetworkActivityPackets(int type, int which) {
6464 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
6465 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006466 } else {
6467 return 0;
6468 }
6469 }
6470
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006471 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07006472 final long currentTime = System.currentTimeMillis();
6473 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08006474 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
6475 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07006476 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08006477 return mStartClockTime;
6478 }
6479
Dianne Hackborncd0e3352014-08-07 17:08:09 -07006480 @Override public String getStartPlatformVersion() {
6481 return mStartPlatformVersion;
6482 }
6483
6484 @Override public String getEndPlatformVersion() {
6485 return mEndPlatformVersion;
6486 }
6487
6488 @Override public int getParcelVersion() {
6489 return VERSION;
6490 }
6491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 @Override public boolean getIsOnBattery() {
6493 return mOnBattery;
6494 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
6497 return mUidStats;
6498 }
6499
Adam Lesinski5f056f62016-07-14 16:56:08 -07006500 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
6501 if (timer != null) {
6502 timer.detach();
6503 }
6504 }
6505
6506 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
6507 boolean detachIfReset) {
6508 if (timer != null) {
6509 return timer.reset(detachIfReset);
6510 }
6511 return true;
6512 }
6513
Bookatz867c0d72017-03-07 18:23:42 -08006514 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
6515 if (timer != null) {
6516 return timer.reset(detachIfReset);
6517 }
6518 return true;
6519 }
6520
Adam Lesinski5f056f62016-07-14 16:56:08 -07006521 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
6522 if (counter != null) {
6523 counter.detach();
6524 }
6525 }
6526
6527 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
6528 boolean detachIfReset) {
6529 if (counter != null) {
6530 counter.reset(detachIfReset);
6531 }
6532 }
6533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 /**
6535 * The statistics associated with a particular uid.
6536 */
Joe Onoratoabded112016-02-08 16:49:39 -08006537 public static class Uid extends BatteryStats.Uid {
6538 /**
6539 * BatteryStatsImpl that we are associated with.
6540 */
6541 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006544
Bookatz867c0d72017-03-07 18:23:42 -08006545 /** TimeBase for when uid is in background and device is on battery. */
6546 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6547 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07006548 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
6549 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08006550
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006551 boolean mWifiRunning;
6552 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006553
The Android Open Source Project10592532009-03-18 17:39:46 -07006554 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07006555 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006556
Nick Pelly6ccaa542012-06-15 15:22:47 -07006557 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08006558 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006559
Dianne Hackborn61659e52014-07-09 16:13:01 -07006560 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07006561 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6562 StopwatchTimer[] mWifiBatchedScanTimer;
6563
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006564 boolean mWifiMulticastEnabled;
6565 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006566
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006567 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006568 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006569 StopwatchTimer mFlashlightTurnedOnTimer;
6570 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006571 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006572 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07006573 /** Total time spent by the uid holding any partial wakelocks. */
6574 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006575 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07006576 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07006577 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07006578 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006579
Dianne Hackborna8d10942015-11-19 17:55:19 -08006580 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07006581 StopwatchTimer[] mProcessStateTimer;
6582
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006583 boolean mInForegroundService = false;
6584
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006585 BatchTimer mVibratorOnTimer;
6586
Dianne Hackborn617f8772009-03-31 15:04:46 -07006587 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006588
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006589 LongSamplingCounter[] mNetworkByteActivityCounters;
6590 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006591 LongSamplingCounter mMobileRadioActiveTime;
6592 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07006595 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
6596 */
6597 private LongSamplingCounter mMobileRadioApWakeupCount;
6598
6599 /**
6600 * How many times this UID woke up the Application Processor due to a Wifi packet.
6601 */
6602 private LongSamplingCounter mWifiRadioApWakeupCount;
6603
6604 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07006605 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006606 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006607 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006608 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006609
6610 /**
6611 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006612 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07006613 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006614 private ControllerActivityCounterImpl mBluetoothControllerActivity;
6615
6616 /**
6617 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
6618 * Can be null if the UID has had no such activity.
6619 */
6620 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006621
6622 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006623 * The CPU times we had at the last history details update.
6624 */
6625 long mLastStepUserTime;
6626 long mLastStepSystemTime;
6627 long mCurStepUserTime;
6628 long mCurStepSystemTime;
6629
Joe Onoratoabded112016-02-08 16:49:39 -08006630 LongSamplingCounter mUserCpuTime;
6631 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07006632 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Mike Ma3d422c32017-10-25 11:08:57 -07006633 LongSamplingCounter mCpuActiveTimeMs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006634
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006635 LongSamplingCounterArray mCpuFreqTimeMs;
6636 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
Mike Ma3d422c32017-10-25 11:08:57 -07006637 LongSamplingCounterArray mCpuClusterTimesMs;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006638
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006639 LongSamplingCounterArray[] mProcStateTimeMs;
6640 LongSamplingCounterArray[] mProcStateScreenOffTimeMs;
6641
6642 IntArray mChildUids;
6643
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006644 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 * The statistics we have collected for this uid's wake locks.
6646 */
Joe Onoratoabded112016-02-08 16:49:39 -08006647 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648
6649 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006650 * The statistics we have collected for this uid's syncs.
6651 */
Bookatz2bffb5b2017-04-13 11:59:33 -07006652 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006653
6654 /**
6655 * The statistics we have collected for this uid's jobs.
6656 */
Bookatzaa4594a2017-03-24 12:39:56 -07006657 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006658
6659 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006660 * Count of the jobs that have completed and the reasons why they completed.
6661 */
6662 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
6663
6664 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 * The statistics we have collected for this uid's sensor activations.
6666 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006667 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668
6669 /**
6670 * The statistics we have collected for this uid's processes.
6671 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006672 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673
6674 /**
6675 * The statistics we have collected for this uid's processes.
6676 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006677 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006678
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006679 /**
6680 * The transient wake stats we have collected for this uid's pids.
6681 */
Adam Lesinskie08af192015-03-25 16:42:59 -07006682 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006683
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00006684 /**
6685 * The list of WorkChains associated with active bluetooth scans.
6686 *
6687 * NOTE: This is a hack and it only needs to exist because there's a "reset" API that is
6688 * supposed to stop and log all WorkChains that were currently active.
6689 */
6690 ArrayList<WorkChain> mAllBluetoothChains = null;
6691 ArrayList<WorkChain> mUnoptimizedBluetoothChains = null;
6692
Joe Onoratoabded112016-02-08 16:49:39 -08006693 public Uid(BatteryStatsImpl bsi, int uid) {
6694 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08006696
Bookatz867c0d72017-03-07 18:23:42 -08006697 mOnBatteryBackgroundTimeBase = new TimeBase();
6698 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6699 mBsi.mClocks.elapsedRealtime() * 1000);
6700
Bookatzc8c44962017-05-11 12:12:54 -07006701 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
6702 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
6703 mBsi.mClocks.elapsedRealtime() * 1000);
6704
Joe Onoratoabded112016-02-08 16:49:39 -08006705 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6706 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -07006707 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6708 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006709
Dianne Hackborn657153b2016-07-29 14:54:14 -07006710 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08006711 @Override public Wakelock instantiateObject() {
6712 return new Wakelock(mBsi, Uid.this);
6713 }
6714 };
Bookatz2bffb5b2017-04-13 11:59:33 -07006715 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6716 @Override public DualTimer instantiateObject() {
6717 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
6718 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006719 }
6720 };
Bookatzaa4594a2017-03-24 12:39:56 -07006721 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
6722 @Override public DualTimer instantiateObject() {
6723 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
6724 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08006725 }
6726 };
6727
6728 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
6729 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
6730 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
6731 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08006732 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
6733 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006734 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08006735 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
6736 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006737 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 }
6739
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006740 @VisibleForTesting
6741 public void setProcessStateForTest(int procState) {
6742 mProcessState = procState;
6743 }
6744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006746 public long[] getCpuFreqTimes(int which) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006747 return nullIfAllZeros(mCpuFreqTimeMs, which);
6748 }
6749
6750 @Override
6751 public long[] getScreenOffCpuFreqTimes(int which) {
6752 return nullIfAllZeros(mScreenOffCpuFreqTimeMs, which);
6753 }
6754
6755 @Override
Mike Ma3d422c32017-10-25 11:08:57 -07006756 public long getCpuActiveTime() {
6757 return mCpuActiveTimeMs.getCountLocked(STATS_SINCE_CHARGED);
6758 }
6759
6760 @Override
6761 public long[] getCpuClusterTimes() {
6762 return nullIfAllZeros(mCpuClusterTimesMs, STATS_SINCE_CHARGED);
6763 }
6764
6765
6766 @Override
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006767 public long[] getCpuFreqTimes(int which, int procState) {
6768 if (which < 0 || which >= NUM_PROCESS_STATE) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006769 return null;
6770 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006771 if (mProcStateTimeMs == null) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006772 return null;
6773 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006774 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6775 mProcStateTimeMs = null;
6776 return null;
6777 }
6778 return nullIfAllZeros(mProcStateTimeMs[procState], which);
6779 }
6780
6781 @Override
6782 public long[] getScreenOffCpuFreqTimes(int which, int procState) {
6783 if (which < 0 || which >= NUM_PROCESS_STATE) {
6784 return null;
6785 }
6786 if (mProcStateScreenOffTimeMs == null) {
6787 return null;
6788 }
6789 if (!mBsi.mPerProcStateCpuTimesAvailable) {
6790 mProcStateScreenOffTimeMs = null;
6791 return null;
6792 }
6793 return nullIfAllZeros(mProcStateScreenOffTimeMs[procState], which);
6794 }
6795
6796 public void addIsolatedUid(int isolatedUid) {
6797 if (mChildUids == null) {
6798 mChildUids = new IntArray();
6799 } else if (mChildUids.indexOf(isolatedUid) >= 0) {
6800 return;
6801 }
6802 mChildUids.add(isolatedUid);
6803 }
6804
6805 public void removeIsolatedUid(int isolatedUid) {
6806 final int idx = mChildUids == null ? -1 : mChildUids.indexOf(isolatedUid);
6807 if (idx < 0) {
6808 return;
6809 }
6810 mChildUids.remove(idx);
6811 }
6812
6813 private long[] nullIfAllZeros(LongSamplingCounterArray cpuTimesMs, int which) {
6814 if (cpuTimesMs == null) {
6815 return null;
6816 }
6817 final long[] counts = cpuTimesMs.getCountsLocked(which);
6818 if (counts == null) {
6819 return null;
6820 }
6821 // Return counts only if at least one of the elements is non-zero.
6822 for (int i = counts.length - 1; i >= 0; --i) {
6823 if (counts[i] != 0) {
6824 return counts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006825 }
6826 }
6827 return null;
6828 }
6829
Sudheer Shankae544d162017-12-28 17:06:20 -08006830 private void addProcStateTimesMs(int procState, long[] cpuTimesMs, boolean onBattery) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006831 if (mProcStateTimeMs == null) {
6832 mProcStateTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006833 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006834 if (mProcStateTimeMs[procState] == null
6835 || mProcStateTimeMs[procState].getSize() != cpuTimesMs.length) {
6836 mProcStateTimeMs[procState] = new LongSamplingCounterArray(
6837 mBsi.mOnBatteryTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006838 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006839 mProcStateTimeMs[procState].addCountLocked(cpuTimesMs, onBattery);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006840 }
6841
Sudheer Shankae544d162017-12-28 17:06:20 -08006842 private void addProcStateScreenOffTimesMs(int procState, long[] cpuTimesMs,
6843 boolean onBatteryScreenOff) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006844 if (mProcStateScreenOffTimeMs == null) {
6845 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[NUM_PROCESS_STATE];
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006846 }
Sudheer Shankab2f83c12017-11-13 19:25:01 -08006847 if (mProcStateScreenOffTimeMs[procState] == null
6848 || mProcStateScreenOffTimeMs[procState].getSize() != cpuTimesMs.length) {
6849 mProcStateScreenOffTimeMs[procState] = new LongSamplingCounterArray(
6850 mBsi.mOnBatteryScreenOffTimeBase);
6851 }
Sudheer Shankae544d162017-12-28 17:06:20 -08006852 mProcStateScreenOffTimeMs[procState].addCountLocked(cpuTimesMs, onBatteryScreenOff);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006853 }
6854
6855 @Override
Bookatzc8c44962017-05-11 12:12:54 -07006856 public Timer getAggregatedPartialWakelockTimer() {
6857 return mAggregatedPartialWakelockTimer;
6858 }
6859
6860 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006861 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006862 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 }
6864
6865 @Override
Ahmed ElArabawyddd09692017-10-30 17:58:29 -07006866 public Timer getMulticastWakelockStats() {
6867 return mWifiMulticastTimer;
6868 }
6869
6870 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006871 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006872 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006873 }
6874
6875 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006876 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006877 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006878 }
6879
6880 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006881 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
6882 return mJobCompletions;
6883 }
6884
6885 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07006886 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006887 return mSensorStats;
6888 }
6889
6890 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006891 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006892 return mProcessStats;
6893 }
6894
6895 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07006896 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006897 return mPackageStats;
6898 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006899
6900 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006901 public int getUid() {
6902 return mUid;
6903 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07006904
6905 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006906 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006907 if (!mWifiRunning) {
6908 mWifiRunning = true;
6909 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006910 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
6911 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006912 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006913 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006914 }
6915 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006916
Dianne Hackborn617f8772009-03-31 15:04:46 -07006917 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006918 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006919 if (mWifiRunning) {
6920 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006921 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006922 }
6923 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006924
Dianne Hackborn617f8772009-03-31 15:04:46 -07006925 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006926 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006927 if (!mFullWifiLockOut) {
6928 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006929 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006930 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
6931 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006932 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006933 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006934 }
6935 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006936
The Android Open Source Project10592532009-03-18 17:39:46 -07006937 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006938 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07006939 if (mFullWifiLockOut) {
6940 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006941 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006942 }
6943 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006944
The Android Open Source Project10592532009-03-18 17:39:46 -07006945 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006946 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006947 if (!mWifiScanStarted) {
6948 mWifiScanStarted = true;
6949 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006950 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
6951 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
6952 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006953 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006954 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006955 }
6956 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006957
The Android Open Source Project10592532009-03-18 17:39:46 -07006958 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006959 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006960 if (mWifiScanStarted) {
6961 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006962 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07006963 }
6964 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006965
6966 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006967 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006968 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07006969 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006970 csph = csph >> 3;
6971 bin++;
6972 }
6973
6974 if (mWifiBatchedScanBinStarted == bin) return;
6975
6976 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
6977 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006978 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006979 }
6980 mWifiBatchedScanBinStarted = bin;
6981 if (mWifiBatchedScanTimer[bin] == null) {
6982 makeWifiBatchedScanBin(bin, null);
6983 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006984 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006985 }
6986
6987 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006988 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006989 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
6990 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006991 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006992 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6993 }
6994 }
6995
6996 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006997 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006998 if (!mWifiMulticastEnabled) {
6999 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007000 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007001 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7002 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007003 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007004 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007005 StatsLog.write_non_chained(
7006 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null, 1);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007007 }
7008 }
7009
7010 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007011 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007012 if (mWifiMulticastEnabled) {
7013 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007014 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Tej Singh4503e102018-01-04 14:35:01 -08007015 StatsLog.write_non_chained(
7016 StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null, 0);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007017 }
7018 }
7019
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007020 @Override
7021 public ControllerActivityCounter getWifiControllerActivity() {
7022 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07007023 }
7024
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007025 @Override
7026 public ControllerActivityCounter getBluetoothControllerActivity() {
7027 return mBluetoothControllerActivity;
7028 }
7029
7030 @Override
7031 public ControllerActivityCounter getModemControllerActivity() {
7032 return mModemControllerActivity;
7033 }
7034
7035 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
7036 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007037 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007038 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08007039 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007040 return mWifiControllerActivity;
7041 }
7042
7043 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
7044 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007045 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007046 NUM_BT_TX_LEVELS);
7047 }
7048 return mBluetoothControllerActivity;
7049 }
7050
7051 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
7052 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007053 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007054 ModemActivityInfo.TX_POWER_LEVELS);
7055 }
7056 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08007057 }
7058
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007059 public StopwatchTimer createAudioTurnedOnTimerLocked() {
7060 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007061 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7062 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007063 }
7064 return mAudioTurnedOnTimer;
7065 }
7066
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007067 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007068 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007069 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null, 1);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007070 }
7071
7072 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
7073 if (mAudioTurnedOnTimer != null) {
7074 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007075 if (!mAudioTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007076 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07007077 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007078 }
7079 }
7080
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007081 public void noteResetAudioLocked(long elapsedRealtimeMs) {
7082 if (mAudioTurnedOnTimer != null) {
7083 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007084 StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null, 0);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007085 }
7086 }
7087
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007088 public StopwatchTimer createVideoTurnedOnTimerLocked() {
7089 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007090 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7091 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007092 }
7093 return mVideoTurnedOnTimer;
7094 }
7095
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007096 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007097 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007098 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null, 1);
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007099 }
7100
7101 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
7102 if (mVideoTurnedOnTimer != null) {
7103 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007104 if (!mVideoTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007105 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(),
7106 null, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07007107 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007108 }
7109 }
7110
Dianne Hackborn10eaa852014-07-22 22:54:55 -07007111 public void noteResetVideoLocked(long elapsedRealtimeMs) {
7112 if (mVideoTurnedOnTimer != null) {
7113 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007114 StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
7115 0);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007116 }
7117 }
7118
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007119 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
7120 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007121 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7122 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007123 }
7124 return mFlashlightTurnedOnTimer;
7125 }
7126
7127 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
7128 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007129 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,1);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007130 }
7131
7132 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
7133 if (mFlashlightTurnedOnTimer != null) {
7134 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007135 if (!mFlashlightTurnedOnTimer.isRunningLocked()) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08007136 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
7137 0);
Bookatzc1a050a2017-10-10 15:49:28 -07007138 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007139 }
7140 }
7141
7142 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
7143 if (mFlashlightTurnedOnTimer != null) {
7144 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007145 StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null, 0);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007146 }
7147 }
7148
7149 public StopwatchTimer createCameraTurnedOnTimerLocked() {
7150 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007151 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7152 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007153 }
7154 return mCameraTurnedOnTimer;
7155 }
7156
7157 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
7158 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007159 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null, 1);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007160 }
7161
7162 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
7163 if (mCameraTurnedOnTimer != null) {
7164 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07007165 if (!mCameraTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08007166 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07007167 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007168 }
7169 }
7170
7171 public void noteResetCameraLocked(long elapsedRealtimeMs) {
7172 if (mCameraTurnedOnTimer != null) {
7173 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08007174 StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null, 0);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007175 }
7176 }
7177
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007178 public StopwatchTimer createForegroundActivityTimerLocked() {
7179 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007180 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7181 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007182 }
7183 return mForegroundActivityTimer;
7184 }
7185
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007186 public StopwatchTimer createForegroundServiceTimerLocked() {
7187 if (mForegroundServiceTimer == null) {
7188 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7189 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
7190 }
7191 return mForegroundServiceTimer;
7192 }
7193
Bookatzc8c44962017-05-11 12:12:54 -07007194 public DualTimer createAggregatedPartialWakelockTimerLocked() {
7195 if (mAggregatedPartialWakelockTimer == null) {
7196 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7197 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7198 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
7199 }
7200 return mAggregatedPartialWakelockTimer;
7201 }
7202
Bookatz867c0d72017-03-07 18:23:42 -08007203 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007204 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007205 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7206 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7207 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007208 }
7209 return mBluetoothScanTimer;
7210 }
7211
Bookatzb1f04f32017-05-19 13:57:32 -07007212 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
7213 if (mBluetoothUnoptimizedScanTimer == null) {
7214 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7215 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7216 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
7217 }
7218 return mBluetoothUnoptimizedScanTimer;
7219 }
7220
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007221 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs,
7222 boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007223 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07007224 if (isUnoptimized) {
7225 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
7226 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007227 }
7228
Bookatz94c5a312017-07-11 16:49:17 -07007229 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007230 if (mBluetoothScanTimer != null) {
7231 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
7232 }
Bookatz94c5a312017-07-11 16:49:17 -07007233 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07007234 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
7235 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007236 }
7237
Narayan Kamath0ebc96c2017-12-29 13:32:38 +00007238 public void addBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7239 if (mAllBluetoothChains == null) {
7240 mAllBluetoothChains = new ArrayList<WorkChain>(4);
7241 }
7242
7243 if (isUnoptimized && mUnoptimizedBluetoothChains == null) {
7244 mUnoptimizedBluetoothChains = new ArrayList<WorkChain>(4);
7245 }
7246
7247 mAllBluetoothChains.add(workChain);
7248 if (isUnoptimized) {
7249 mUnoptimizedBluetoothChains.add(workChain);
7250 }
7251 }
7252
7253 public void removeBluetoothWorkChain(WorkChain workChain, boolean isUnoptimized) {
7254 if (mAllBluetoothChains != null) {
7255 mAllBluetoothChains.remove(workChain);
7256 }
7257
7258 if (isUnoptimized && mUnoptimizedBluetoothChains != null) {
7259 mUnoptimizedBluetoothChains.remove(workChain);
7260 }
7261 }
7262
7263 public List<WorkChain> getAllBluetoothWorkChains() {
7264 return mAllBluetoothChains;
7265 }
7266
7267 public List<WorkChain> getUnoptimizedBluetoothWorkChains() {
7268 return mUnoptimizedBluetoothChains;
7269 }
7270
7271
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007272 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
7273 if (mBluetoothScanTimer != null) {
7274 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7275 }
Bookatzb1f04f32017-05-19 13:57:32 -07007276 if (mBluetoothUnoptimizedScanTimer != null) {
7277 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
7278 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007279 }
7280
Bookatz956f36bf2017-04-28 09:48:17 -07007281 public Counter createBluetoothScanResultCounterLocked() {
7282 if (mBluetoothScanResultCounter == null) {
7283 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
7284 }
7285 return mBluetoothScanResultCounter;
7286 }
7287
Bookatzb1f04f32017-05-19 13:57:32 -07007288 public Counter createBluetoothScanResultBgCounterLocked() {
7289 if (mBluetoothScanResultBgCounter == null) {
7290 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
7291 }
7292 return mBluetoothScanResultBgCounter;
7293 }
7294
Bookatz4ebc0642017-05-11 12:21:19 -07007295 public void noteBluetoothScanResultsLocked(int numNewResults) {
7296 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07007297 // Uses background timebase, so the count will only be incremented if uid in background.
7298 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07007299 }
7300
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007301 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007302 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007303 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007304 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007305 }
7306
7307 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007308 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007309 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007310 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007311 }
7312 }
7313
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007314 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
7315 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
7316 }
7317
7318 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
7319 if (mForegroundServiceTimer != null) {
7320 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
7321 }
7322 }
7323
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007324 public BatchTimer createVibratorOnTimerLocked() {
7325 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007326 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7327 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007328 }
7329 return mVibratorOnTimer;
7330 }
7331
7332 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08007333 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007334 }
7335
7336 public void noteVibratorOffLocked() {
7337 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007338 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007339 }
7340 }
7341
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007342 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007343 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007344 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007345 return 0;
7346 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007347 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007348 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007349
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007350 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007351 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007352 if (mFullWifiLockTimer == null) {
7353 return 0;
7354 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007355 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007356 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007357
7358 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007359 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007360 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007361 return 0;
7362 }
Bookatzaa4594a2017-03-24 12:39:56 -07007363 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07007364 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007365
7366 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007367 public int getWifiScanCount(int which) {
7368 if (mWifiScanTimer == null) {
7369 return 0;
7370 }
Bookatzaa4594a2017-03-24 12:39:56 -07007371 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08007372 }
7373
7374 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007375 public Timer getWifiScanTimer() {
7376 return mWifiScanTimer;
7377 }
7378
7379 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007380 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07007381 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007382 return 0;
7383 }
7384 return mWifiScanTimer.getSubTimer().getCountLocked(which);
7385 }
7386
7387 @Override
7388 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
7389 if (mWifiScanTimer == null) {
7390 return 0;
7391 }
7392 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07007393 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08007394 }
7395
7396 @Override
7397 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007398 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08007399 return 0;
7400 }
7401 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
7402 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07007403 }
7404
7405 @Override
Kweku Adams103351f2017-10-16 14:39:34 -07007406 public Timer getWifiScanBackgroundTimer() {
7407 if (mWifiScanTimer == null) {
7408 return null;
7409 }
7410 return mWifiScanTimer.getSubTimer();
7411 }
7412
7413 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007414 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07007415 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7416 if (mWifiBatchedScanTimer[csphBin] == null) {
7417 return 0;
7418 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007419 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007420 }
7421
7422 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07007423 public int getWifiBatchedScanCount(int csphBin, int which) {
7424 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
7425 if (mWifiBatchedScanTimer[csphBin] == null) {
7426 return 0;
7427 }
7428 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
7429 }
7430
7431 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007432 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007433 if (mWifiMulticastTimer == null) {
7434 return 0;
7435 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007436 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07007437 }
7438
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007439 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007440 public Timer getAudioTurnedOnTimer() {
7441 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007442 }
7443
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007444 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007445 public Timer getVideoTurnedOnTimer() {
7446 return mVideoTurnedOnTimer;
7447 }
7448
7449 @Override
7450 public Timer getFlashlightTurnedOnTimer() {
7451 return mFlashlightTurnedOnTimer;
7452 }
7453
7454 @Override
7455 public Timer getCameraTurnedOnTimer() {
7456 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007457 }
7458
Dianne Hackborn617f8772009-03-31 15:04:46 -07007459 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007460 public Timer getForegroundActivityTimer() {
7461 return mForegroundActivityTimer;
7462 }
7463
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007464 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007465 public Timer getForegroundServiceTimer() {
7466 return mForegroundServiceTimer;
7467 }
7468
7469 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007470 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07007471 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08007472 }
7473
7474 @Override
7475 public Timer getBluetoothScanBackgroundTimer() {
7476 if (mBluetoothScanTimer == null) {
7477 return null;
7478 }
7479 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007480 }
7481
Bookatz956f36bf2017-04-28 09:48:17 -07007482 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07007483 public Timer getBluetoothUnoptimizedScanTimer() {
7484 return mBluetoothUnoptimizedScanTimer;
7485 }
7486
7487 @Override
7488 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
7489 if (mBluetoothUnoptimizedScanTimer == null) {
7490 return null;
7491 }
7492 return mBluetoothUnoptimizedScanTimer.getSubTimer();
7493 }
7494
7495 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07007496 public Counter getBluetoothScanResultCounter() {
7497 return mBluetoothScanResultCounter;
7498 }
7499
Bookatzb1f04f32017-05-19 13:57:32 -07007500 @Override
7501 public Counter getBluetoothScanResultBgCounter() {
7502 return mBluetoothScanResultBgCounter;
7503 }
7504
Dianne Hackborn61659e52014-07-09 16:13:01 -07007505 void makeProcessState(int i, Parcel in) {
7506 if (i < 0 || i >= NUM_PROCESS_STATE) return;
7507
7508 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007509 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7510 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007511 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007512 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
7513 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007514 }
7515 }
7516
7517 @Override
7518 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
7519 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
7520 if (mProcessStateTimer[state] == null) {
7521 return 0;
7522 }
7523 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
7524 }
7525
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007526 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08007527 public Timer getProcessStateTimer(int state) {
7528 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
7529 return mProcessStateTimer[state];
7530 }
7531
7532 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007533 public Timer getVibratorOnTimer() {
7534 return mVibratorOnTimer;
7535 }
7536
7537 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07007538 public void noteUserActivityLocked(int type) {
7539 if (mUserActivityCounters == null) {
7540 initUserActivityLocked();
7541 }
Jeff Browndf693de2012-07-27 12:03:38 -07007542 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
7543 mUserActivityCounters[type].stepAtomic();
7544 } else {
7545 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
7546 new Throwable());
7547 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07007548 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007549
Dianne Hackborn617f8772009-03-31 15:04:46 -07007550 @Override
7551 public boolean hasUserActivity() {
7552 return mUserActivityCounters != null;
7553 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007554
Dianne Hackborn617f8772009-03-31 15:04:46 -07007555 @Override
7556 public int getUserActivityCount(int type, int which) {
7557 if (mUserActivityCounters == null) {
7558 return 0;
7559 }
Evan Millarc64edde2009-04-18 12:26:32 -07007560 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007561 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007562
Robert Greenwalta029ea12013-09-25 16:38:12 -07007563 void makeWifiBatchedScanBin(int i, Parcel in) {
7564 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
7565
Joe Onoratoabded112016-02-08 16:49:39 -08007566 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007567 if (collected == null) {
7568 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007569 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007570 }
7571 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08007572 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7573 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007574 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08007575 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
7576 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007577 }
7578 }
7579
7580
Dianne Hackborn617f8772009-03-31 15:04:46 -07007581 void initUserActivityLocked() {
7582 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7583 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007584 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007585 }
7586 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007587
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007588 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
7589 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007590 initNetworkActivityLocked();
7591 }
7592 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007593 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
7594 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007595 } else {
7596 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
7597 new Throwable());
7598 }
7599 }
7600
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007601 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
7602 if (mNetworkByteActivityCounters == null) {
7603 initNetworkActivityLocked();
7604 }
7605 mMobileRadioActiveTime.addCountLocked(batteryUptime);
7606 mMobileRadioActiveCount.addCountLocked(1);
7607 }
7608
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007609 @Override
7610 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007611 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007612 }
7613
7614 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007615 public long getNetworkActivityBytes(int type, int which) {
7616 if (mNetworkByteActivityCounters != null && type >= 0
7617 && type < mNetworkByteActivityCounters.length) {
7618 return mNetworkByteActivityCounters[type].getCountLocked(which);
7619 } else {
7620 return 0;
7621 }
7622 }
7623
7624 @Override
7625 public long getNetworkActivityPackets(int type, int which) {
7626 if (mNetworkPacketActivityCounters != null && type >= 0
7627 && type < mNetworkPacketActivityCounters.length) {
7628 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007629 } else {
7630 return 0;
7631 }
7632 }
7633
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007634 @Override
7635 public long getMobileRadioActiveTime(int which) {
7636 return mMobileRadioActiveTime != null
7637 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
7638 }
7639
7640 @Override
7641 public int getMobileRadioActiveCount(int which) {
7642 return mMobileRadioActiveCount != null
7643 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
7644 }
7645
Adam Lesinskie08af192015-03-25 16:42:59 -07007646 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007647 public long getUserCpuTimeUs(int which) {
7648 return mUserCpuTime.getCountLocked(which);
7649 }
7650
7651 @Override
7652 public long getSystemCpuTimeUs(int which) {
7653 return mSystemCpuTime.getCountLocked(which);
7654 }
7655
7656 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07007657 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007658 if (mCpuClusterSpeedTimesUs != null) {
7659 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
7660 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
7661 if (cpuSpeedTimesUs != null) {
7662 if (step >= 0 && step < cpuSpeedTimesUs.length) {
7663 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07007664 if (c != null) {
7665 return c.getCountLocked(which);
7666 }
7667 }
7668 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007669 }
7670 }
7671 return 0;
7672 }
7673
Adam Lesinski5f056f62016-07-14 16:56:08 -07007674 public void noteMobileRadioApWakeupLocked() {
7675 if (mMobileRadioApWakeupCount == null) {
7676 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7677 }
7678 mMobileRadioApWakeupCount.addCountLocked(1);
7679 }
7680
7681 @Override
7682 public long getMobileRadioApWakeupCount(int which) {
7683 if (mMobileRadioApWakeupCount != null) {
7684 return mMobileRadioApWakeupCount.getCountLocked(which);
7685 }
7686 return 0;
7687 }
7688
7689 public void noteWifiRadioApWakeupLocked() {
7690 if (mWifiRadioApWakeupCount == null) {
7691 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7692 }
7693 mWifiRadioApWakeupCount.addCountLocked(1);
7694 }
7695
7696 @Override
7697 public long getWifiRadioApWakeupCount(int which) {
7698 if (mWifiRadioApWakeupCount != null) {
7699 return mWifiRadioApWakeupCount.getCountLocked(which);
7700 }
7701 return 0;
7702 }
7703
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007704 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007705 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7706 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007707 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007708 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7709 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007710 }
Joe Onoratoabded112016-02-08 16:49:39 -08007711 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
7712 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007713 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07007714
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007715 /**
7716 * Clear all stats for this uid. Returns true if the uid is completely
7717 * inactive so can be dropped.
7718 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07007719 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07007720 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007721 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007722
Bookatz993a0be2017-07-21 09:03:23 -07007723 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
7724 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
7725
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007726 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007727 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007728 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007729 }
7730 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007731 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007732 active |= mFullWifiLockOut;
7733 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007734 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007735 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07007736 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007737 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007738 if (mWifiBatchedScanTimer != null) {
7739 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7740 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007741 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007742 }
7743 }
7744 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
7745 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007746 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007747 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007748 active |= mWifiMulticastEnabled;
7749 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007750
7751 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
7752 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
7753 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
7754 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
7755 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007756 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07007757 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07007758 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07007759 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07007760 if (mBluetoothScanResultCounter != null) {
7761 mBluetoothScanResultCounter.reset(false);
7762 }
Bookatzb1f04f32017-05-19 13:57:32 -07007763 if (mBluetoothScanResultBgCounter != null) {
7764 mBluetoothScanResultBgCounter.reset(false);
7765 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007766
Dianne Hackborn61659e52014-07-09 16:13:01 -07007767 if (mProcessStateTimer != null) {
7768 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7769 if (mProcessStateTimer[i] != null) {
7770 active |= !mProcessStateTimer[i].reset(false);
7771 }
7772 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007773 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007774 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007775 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007776 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007777 mVibratorOnTimer.detach();
7778 mVibratorOnTimer = null;
7779 } else {
7780 active = true;
7781 }
7782 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007783
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007784 if (mUserActivityCounters != null) {
7785 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7786 mUserActivityCounters[i].reset(false);
7787 }
7788 }
7789
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007790 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007791 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007792 mNetworkByteActivityCounters[i].reset(false);
7793 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007794 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007795 mMobileRadioActiveTime.reset(false);
7796 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007797 }
7798
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007799 if (mWifiControllerActivity != null) {
7800 mWifiControllerActivity.reset(false);
7801 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007802
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007803 if (mBluetoothControllerActivity != null) {
7804 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007805 }
7806
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07007807 if (mModemControllerActivity != null) {
7808 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07007809 }
7810
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007811 mUserCpuTime.reset(false);
7812 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07007813
Sudheer Shankaaf857412017-07-21 00:14:24 -07007814 if (mCpuClusterSpeedTimesUs != null) {
7815 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007816 if (speeds != null) {
7817 for (LongSamplingCounter speed : speeds) {
7818 if (speed != null) {
7819 speed.reset(false);
7820 }
7821 }
7822 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007823 }
7824 }
7825
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007826 if (mCpuFreqTimeMs != null) {
7827 mCpuFreqTimeMs.reset(false);
7828 }
7829 if (mScreenOffCpuFreqTimeMs != null) {
7830 mScreenOffCpuFreqTimeMs.reset(false);
7831 }
7832
Mike Ma3d422c32017-10-25 11:08:57 -07007833 mCpuActiveTimeMs.reset(false);
7834 mCpuClusterTimesMs.reset(false);
7835
Sudheer Shankab2f83c12017-11-13 19:25:01 -08007836 if (mProcStateTimeMs != null) {
7837 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
7838 if (counters != null) {
7839 counters.reset(false);
7840 }
7841 }
7842 }
7843 if (mProcStateScreenOffTimeMs != null) {
7844 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
7845 if (counters != null) {
7846 counters.reset(false);
7847 }
7848 }
7849 }
7850
Adam Lesinski5f056f62016-07-14 16:56:08 -07007851 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
7852 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
7853
Dianne Hackbornd953c532014-08-16 18:17:38 -07007854 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7855 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
7856 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007857 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007858 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07007859 } else {
7860 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007861 }
7862 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007863 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07007864 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007865 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07007866 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007867 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007868 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007869 timer.detach();
7870 } else {
7871 active = true;
7872 }
7873 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007874 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07007875 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007876 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07007877 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007878 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007879 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007880 timer.detach();
7881 } else {
7882 active = true;
7883 }
7884 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07007885 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007886 mJobCompletions.clear();
Dianne Hackborn61659e52014-07-09 16:13:01 -07007887 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
7888 Sensor s = mSensorStats.valueAt(ise);
7889 if (s.reset()) {
7890 mSensorStats.removeAt(ise);
7891 } else {
7892 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007893 }
7894 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07007895 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
7896 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08007897 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007898 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007899 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007900 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007901 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007902 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007903 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007904 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08007905 } else {
7906 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007907 }
7908 }
7909 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007910 if (mPackageStats.size() > 0) {
7911 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
7912 while (it.hasNext()) {
7913 Map.Entry<String, Pkg> pkgEntry = it.next();
7914 Pkg p = pkgEntry.getValue();
7915 p.detach();
7916 if (p.mServiceStats.size() > 0) {
7917 Iterator<Map.Entry<String, Pkg.Serv>> it2
7918 = p.mServiceStats.entrySet().iterator();
7919 while (it2.hasNext()) {
7920 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
7921 servEntry.getValue().detach();
7922 }
7923 }
7924 }
7925 mPackageStats.clear();
7926 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007927
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08007928 mLastStepUserTime = mLastStepSystemTime = 0;
7929 mCurStepUserTime = mCurStepSystemTime = 0;
7930
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007931 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007932 if (mWifiRunningTimer != null) {
7933 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007934 }
7935 if (mFullWifiLockTimer != null) {
7936 mFullWifiLockTimer.detach();
7937 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007938 if (mWifiScanTimer != null) {
7939 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007940 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007941 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7942 if (mWifiBatchedScanTimer[i] != null) {
7943 mWifiBatchedScanTimer[i].detach();
7944 }
7945 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007946 if (mWifiMulticastTimer != null) {
7947 mWifiMulticastTimer.detach();
7948 }
7949 if (mAudioTurnedOnTimer != null) {
7950 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007951 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007952 }
7953 if (mVideoTurnedOnTimer != null) {
7954 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007955 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007956 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007957 if (mFlashlightTurnedOnTimer != null) {
7958 mFlashlightTurnedOnTimer.detach();
7959 mFlashlightTurnedOnTimer = null;
7960 }
7961 if (mCameraTurnedOnTimer != null) {
7962 mCameraTurnedOnTimer.detach();
7963 mCameraTurnedOnTimer = null;
7964 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007965 if (mForegroundActivityTimer != null) {
7966 mForegroundActivityTimer.detach();
7967 mForegroundActivityTimer = null;
7968 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007969 if (mForegroundServiceTimer != null) {
7970 mForegroundServiceTimer.detach();
7971 mForegroundServiceTimer = null;
7972 }
Bookatzc8c44962017-05-11 12:12:54 -07007973 if (mAggregatedPartialWakelockTimer != null) {
7974 mAggregatedPartialWakelockTimer.detach();
7975 mAggregatedPartialWakelockTimer = null;
7976 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007977 if (mBluetoothScanTimer != null) {
7978 mBluetoothScanTimer.detach();
7979 mBluetoothScanTimer = null;
7980 }
Bookatzb1f04f32017-05-19 13:57:32 -07007981 if (mBluetoothUnoptimizedScanTimer != null) {
7982 mBluetoothUnoptimizedScanTimer.detach();
7983 mBluetoothUnoptimizedScanTimer = null;
7984 }
Bookatz956f36bf2017-04-28 09:48:17 -07007985 if (mBluetoothScanResultCounter != null) {
7986 mBluetoothScanResultCounter.detach();
7987 mBluetoothScanResultCounter = null;
7988 }
Bookatzb1f04f32017-05-19 13:57:32 -07007989 if (mBluetoothScanResultBgCounter != null) {
7990 mBluetoothScanResultBgCounter.detach();
7991 mBluetoothScanResultBgCounter = null;
7992 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007993 if (mUserActivityCounters != null) {
7994 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7995 mUserActivityCounters[i].detach();
7996 }
7997 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007998 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007999 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008000 mNetworkByteActivityCounters[i].detach();
8001 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008002 }
8003 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008004
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008005 if (mWifiControllerActivity != null) {
8006 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07008007 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008008
8009 if (mBluetoothControllerActivity != null) {
8010 mBluetoothControllerActivity.detach();
8011 }
8012
8013 if (mModemControllerActivity != null) {
8014 mModemControllerActivity.detach();
8015 }
8016
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008017 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008018
8019 mUserCpuTime.detach();
8020 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07008021
Sudheer Shankaaf857412017-07-21 00:14:24 -07008022 if (mCpuClusterSpeedTimesUs != null) {
8023 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008024 if (cpuSpeeds != null) {
8025 for (LongSamplingCounter c : cpuSpeeds) {
8026 if (c != null) {
8027 c.detach();
8028 }
8029 }
8030 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008031 }
8032 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008033
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008034 if (mCpuFreqTimeMs != null) {
8035 mCpuFreqTimeMs.detach();
8036 }
8037 if (mScreenOffCpuFreqTimeMs != null) {
8038 mScreenOffCpuFreqTimeMs.detach();
8039 }
Mike Ma3d422c32017-10-25 11:08:57 -07008040 mCpuActiveTimeMs.detach();
8041 mCpuClusterTimesMs.detach();
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008042
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008043 if (mProcStateTimeMs != null) {
8044 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8045 if (counters != null) {
8046 counters.detach();
8047 }
8048 }
8049 }
8050 if (mProcStateScreenOffTimeMs != null) {
8051 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8052 if (counters != null) {
8053 counters.detach();
8054 }
8055 }
8056 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008057 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
8058 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008059 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008060
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008061 return !active;
8062 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008063
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008064 void writeJobCompletionsToParcelLocked(Parcel out) {
8065 int NJC = mJobCompletions.size();
8066 out.writeInt(NJC);
8067 for (int ijc=0; ijc<NJC; ijc++) {
8068 out.writeString(mJobCompletions.keyAt(ijc));
8069 SparseIntArray types = mJobCompletions.valueAt(ijc);
8070 int NT = types.size();
8071 out.writeInt(NT);
8072 for (int it=0; it<NT; it++) {
8073 out.writeInt(types.keyAt(it));
8074 out.writeInt(types.valueAt(it));
8075 }
8076 }
8077 }
8078
Bookatz867c0d72017-03-07 18:23:42 -08008079 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
8080 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07008081 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08008082
Dianne Hackbornd953c532014-08-16 18:17:38 -07008083 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
8084 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07008085 out.writeInt(NW);
8086 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008087 out.writeString(wakeStats.keyAt(iw));
8088 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008089 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008090 }
8091
Bookatz2bffb5b2017-04-13 11:59:33 -07008092 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008093 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008094 out.writeInt(NS);
8095 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008096 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07008097 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008098 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8099 }
8100
Bookatzaa4594a2017-03-24 12:39:56 -07008101 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008102 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008103 out.writeInt(NJ);
8104 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008105 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07008106 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008107 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
8108 }
8109
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008110 writeJobCompletionsToParcelLocked(out);
8111
Dianne Hackborn61659e52014-07-09 16:13:01 -07008112 int NSE = mSensorStats.size();
8113 out.writeInt(NSE);
8114 for (int ise=0; ise<NSE; ise++) {
8115 out.writeInt(mSensorStats.keyAt(ise));
8116 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008117 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118 }
8119
Dianne Hackborn61659e52014-07-09 16:13:01 -07008120 int NP = mProcessStats.size();
8121 out.writeInt(NP);
8122 for (int ip=0; ip<NP; ip++) {
8123 out.writeString(mProcessStats.keyAt(ip));
8124 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008125 proc.writeToParcelLocked(out);
8126 }
8127
8128 out.writeInt(mPackageStats.size());
8129 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
8130 out.writeString(pkgEntry.getKey());
8131 Uid.Pkg pkg = pkgEntry.getValue();
8132 pkg.writeToParcelLocked(out);
8133 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008134
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008135 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008136 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008137 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008138 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008139 out.writeInt(0);
8140 }
8141 if (mFullWifiLockTimer != null) {
8142 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008143 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008144 } else {
8145 out.writeInt(0);
8146 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008147 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008148 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008149 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008150 } else {
8151 out.writeInt(0);
8152 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008153 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8154 if (mWifiBatchedScanTimer[i] != null) {
8155 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008156 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07008157 } else {
8158 out.writeInt(0);
8159 }
8160 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008161 if (mWifiMulticastTimer != null) {
8162 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008163 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008164 } else {
8165 out.writeInt(0);
8166 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008167
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008168 if (mAudioTurnedOnTimer != null) {
8169 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008170 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008171 } else {
8172 out.writeInt(0);
8173 }
8174 if (mVideoTurnedOnTimer != null) {
8175 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008176 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008177 } else {
8178 out.writeInt(0);
8179 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008180 if (mFlashlightTurnedOnTimer != null) {
8181 out.writeInt(1);
8182 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8183 } else {
8184 out.writeInt(0);
8185 }
8186 if (mCameraTurnedOnTimer != null) {
8187 out.writeInt(1);
8188 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
8189 } else {
8190 out.writeInt(0);
8191 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008192 if (mForegroundActivityTimer != null) {
8193 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008194 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008195 } else {
8196 out.writeInt(0);
8197 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008198 if (mForegroundServiceTimer != null) {
8199 out.writeInt(1);
8200 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
8201 } else {
8202 out.writeInt(0);
8203 }
Bookatzc8c44962017-05-11 12:12:54 -07008204 if (mAggregatedPartialWakelockTimer != null) {
8205 out.writeInt(1);
8206 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
8207 } else {
8208 out.writeInt(0);
8209 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008210 if (mBluetoothScanTimer != null) {
8211 out.writeInt(1);
8212 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
8213 } else {
8214 out.writeInt(0);
8215 }
Bookatzb1f04f32017-05-19 13:57:32 -07008216 if (mBluetoothUnoptimizedScanTimer != null) {
8217 out.writeInt(1);
8218 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
8219 } else {
8220 out.writeInt(0);
8221 }
Bookatz956f36bf2017-04-28 09:48:17 -07008222 if (mBluetoothScanResultCounter != null) {
8223 out.writeInt(1);
8224 mBluetoothScanResultCounter.writeToParcel(out);
8225 } else {
8226 out.writeInt(0);
8227 }
Bookatzb1f04f32017-05-19 13:57:32 -07008228 if (mBluetoothScanResultBgCounter != null) {
8229 out.writeInt(1);
8230 mBluetoothScanResultBgCounter.writeToParcel(out);
8231 } else {
8232 out.writeInt(0);
8233 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008234 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8235 if (mProcessStateTimer[i] != null) {
8236 out.writeInt(1);
8237 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
8238 } else {
8239 out.writeInt(0);
8240 }
8241 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008242 if (mVibratorOnTimer != null) {
8243 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008244 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008245 } else {
8246 out.writeInt(0);
8247 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008248 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008249 out.writeInt(1);
8250 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
8251 mUserActivityCounters[i].writeToParcel(out);
8252 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008253 } else {
8254 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008255 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008256 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008257 out.writeInt(1);
8258 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008259 mNetworkByteActivityCounters[i].writeToParcel(out);
8260 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008261 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08008262 mMobileRadioActiveTime.writeToParcel(out);
8263 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008264 } else {
8265 out.writeInt(0);
8266 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008267
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008268 if (mWifiControllerActivity != null) {
8269 out.writeInt(1);
8270 mWifiControllerActivity.writeToParcel(out, 0);
8271 } else {
8272 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008273 }
8274
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008275 if (mBluetoothControllerActivity != null) {
8276 out.writeInt(1);
8277 mBluetoothControllerActivity.writeToParcel(out, 0);
8278 } else {
8279 out.writeInt(0);
8280 }
8281
8282 if (mModemControllerActivity != null) {
8283 out.writeInt(1);
8284 mModemControllerActivity.writeToParcel(out, 0);
8285 } else {
8286 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07008287 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008288
8289 mUserCpuTime.writeToParcel(out);
8290 mSystemCpuTime.writeToParcel(out);
8291
Sudheer Shankaaf857412017-07-21 00:14:24 -07008292 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008293 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07008294 out.writeInt(mCpuClusterSpeedTimesUs.length);
8295 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008296 if (cpuSpeeds != null) {
8297 out.writeInt(1);
8298 out.writeInt(cpuSpeeds.length);
8299 for (LongSamplingCounter c : cpuSpeeds) {
8300 if (c != null) {
8301 out.writeInt(1);
8302 c.writeToParcel(out);
8303 } else {
8304 out.writeInt(0);
8305 }
8306 }
8307 } else {
8308 out.writeInt(0);
8309 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008310 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008311 } else {
8312 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008313 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008314
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008315 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
8316 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Mike Ma3d422c32017-10-25 11:08:57 -07008317
8318 mCpuActiveTimeMs.writeToParcel(out);
8319 mCpuClusterTimesMs.writeToParcel(out);
8320
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008321 if (mProcStateTimeMs != null) {
8322 out.writeInt(mProcStateTimeMs.length);
8323 for (LongSamplingCounterArray counters : mProcStateTimeMs) {
8324 LongSamplingCounterArray.writeToParcel(out, counters);
8325 }
8326 } else {
8327 out.writeInt(0);
8328 }
8329 if (mProcStateScreenOffTimeMs != null) {
8330 out.writeInt(mProcStateScreenOffTimeMs.length);
8331 for (LongSamplingCounterArray counters : mProcStateScreenOffTimeMs) {
8332 LongSamplingCounterArray.writeToParcel(out, counters);
8333 }
8334 } else {
8335 out.writeInt(0);
8336 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008337
Adam Lesinski5f056f62016-07-14 16:56:08 -07008338 if (mMobileRadioApWakeupCount != null) {
8339 out.writeInt(1);
8340 mMobileRadioApWakeupCount.writeToParcel(out);
8341 } else {
8342 out.writeInt(0);
8343 }
8344
8345 if (mWifiRadioApWakeupCount != null) {
8346 out.writeInt(1);
8347 mWifiRadioApWakeupCount.writeToParcel(out);
8348 } else {
8349 out.writeInt(0);
8350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008351 }
8352
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008353 void readJobCompletionsFromParcelLocked(Parcel in) {
8354 int numJobCompletions = in.readInt();
8355 mJobCompletions.clear();
8356 for (int j = 0; j < numJobCompletions; j++) {
8357 String jobName = in.readString();
8358 int numTypes = in.readInt();
8359 if (numTypes > 0) {
8360 SparseIntArray types = new SparseIntArray();
8361 for (int k = 0; k < numTypes; k++) {
8362 int type = in.readInt();
8363 int count = in.readInt();
8364 types.put(type, count);
8365 }
8366 mJobCompletions.put(jobName, types);
8367 }
8368 }
8369 }
8370
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008371 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08008372 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07008373 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08008374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008375 int numWakelocks = in.readInt();
8376 mWakelockStats.clear();
8377 for (int j = 0; j < numWakelocks; j++) {
8378 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008379 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07008380 wakelock.readFromParcelLocked(
8381 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008382 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008383 }
8384
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008385 int numSyncs = in.readInt();
8386 mSyncStats.clear();
8387 for (int j = 0; j < numSyncs; j++) {
8388 String syncName = in.readString();
8389 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008390 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
8391 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008392 }
8393 }
8394
8395 int numJobs = in.readInt();
8396 mJobStats.clear();
8397 for (int j = 0; j < numJobs; j++) {
8398 String jobName = in.readString();
8399 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07008400 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
8401 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008402 }
8403 }
8404
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008405 readJobCompletionsFromParcelLocked(in);
8406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008407 int numSensors = in.readInt();
8408 mSensorStats.clear();
8409 for (int k = 0; k < numSensors; k++) {
8410 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008411 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08008412 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8413 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008414 mSensorStats.put(sensorNumber, sensor);
8415 }
8416
8417 int numProcs = in.readInt();
8418 mProcessStats.clear();
8419 for (int k = 0; k < numProcs; k++) {
8420 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008421 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008422 proc.readFromParcelLocked(in);
8423 mProcessStats.put(processName, proc);
8424 }
8425
8426 int numPkgs = in.readInt();
8427 mPackageStats.clear();
8428 for (int l = 0; l < numPkgs; l++) {
8429 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008430 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008431 pkg.readFromParcelLocked(in);
8432 mPackageStats.put(packageName, pkg);
8433 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008434
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008435 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008436 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008437 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
8438 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008439 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07008440 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008441 }
8442 mFullWifiLockOut = false;
8443 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008444 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
8445 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008446 } else {
8447 mFullWifiLockTimer = null;
8448 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07008449 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008450 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008451 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
8452 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
8453 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008454 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07008455 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008456 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07008457 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
8458 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
8459 if (in.readInt() != 0) {
8460 makeWifiBatchedScanBin(i, in);
8461 } else {
8462 mWifiBatchedScanTimer[i] = null;
8463 }
8464 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008465 mWifiMulticastEnabled = false;
8466 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008467 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
8468 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008469 } else {
8470 mWifiMulticastTimer = null;
8471 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008472 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008473 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
8474 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008475 } else {
8476 mAudioTurnedOnTimer = null;
8477 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008478 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008479 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
8480 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008481 } else {
8482 mVideoTurnedOnTimer = null;
8483 }
8484 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008485 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8486 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008487 } else {
8488 mFlashlightTurnedOnTimer = null;
8489 }
8490 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008491 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
8492 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07008493 } else {
8494 mCameraTurnedOnTimer = null;
8495 }
8496 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008497 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8498 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008499 } else {
8500 mForegroundActivityTimer = null;
8501 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008502 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008503 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
8504 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
8505 } else {
8506 mForegroundServiceTimer = null;
8507 }
8508 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07008509 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
8510 AGGREGATED_WAKE_TYPE_PARTIAL, null,
8511 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
8512 in);
8513 } else {
8514 mAggregatedPartialWakelockTimer = null;
8515 }
8516 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08008517 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
8518 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
8519 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08008520 } else {
8521 mBluetoothScanTimer = null;
8522 }
Bookatz956f36bf2017-04-28 09:48:17 -07008523 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07008524 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
8525 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
8526 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
8527 } else {
8528 mBluetoothUnoptimizedScanTimer = null;
8529 }
8530 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07008531 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
8532 } else {
8533 mBluetoothScanResultCounter = null;
8534 }
Bookatzb1f04f32017-05-19 13:57:32 -07008535 if (in.readInt() != 0) {
8536 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
8537 } else {
8538 mBluetoothScanResultBgCounter = null;
8539 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008540 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008541 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
8542 if (in.readInt() != 0) {
8543 makeProcessState(i, in);
8544 } else {
8545 mProcessStateTimer[i] = null;
8546 }
8547 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008548 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008549 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
8550 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08008551 } else {
8552 mVibratorOnTimer = null;
8553 }
8554 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07008555 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
8556 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008557 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008558 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008559 } else {
8560 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07008561 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008562 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008563 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
8564 mNetworkPacketActivityCounters
8565 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008566 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008567 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008568 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008569 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08008570 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008571 }
Joe Onoratoabded112016-02-08 16:49:39 -08008572 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8573 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008574 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08008575 mNetworkByteActivityCounters = null;
8576 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008577 }
Adam Lesinskie08af192015-03-25 16:42:59 -07008578
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008579 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008580 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008581 NUM_WIFI_TX_LEVELS, in);
8582 } else {
8583 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008584 }
8585
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008586 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008587 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008588 NUM_BT_TX_LEVELS, in);
8589 } else {
8590 mBluetoothControllerActivity = null;
8591 }
8592
8593 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08008594 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008595 ModemActivityInfo.TX_POWER_LEVELS, in);
8596 } else {
8597 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07008598 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008599
Joe Onoratoabded112016-02-08 16:49:39 -08008600 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8601 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008602
Adam Lesinski6832f392015-09-05 18:05:40 -07008603 if (in.readInt() != 0) {
8604 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008605 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008606 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008607 }
Adam Lesinski6832f392015-09-05 18:05:40 -07008608
Sudheer Shankaaf857412017-07-21 00:14:24 -07008609 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07008610 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
8611 if (in.readInt() != 0) {
8612 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08008613 if (mBsi.mPowerProfile != null &&
8614 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07008615 throw new ParcelFormatException("Incompatible number of cpu speeds");
8616 }
8617
8618 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07008619 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07008620 for (int speed = 0; speed < numSpeeds; speed++) {
8621 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008622 cpuSpeeds[speed] = new LongSamplingCounter(
8623 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07008624 }
8625 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07008626 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008627 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07008628 }
8629 }
8630 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07008631 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07008632 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07008633
Sudheer Shanka59f5c002017-05-15 10:57:15 -07008634 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
8635 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
8636 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008637
Mike Ma3d422c32017-10-25 11:08:57 -07008638 mCpuActiveTimeMs = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8639 mCpuClusterTimesMs = new LongSamplingCounterArray(mBsi.mOnBatteryTimeBase, in);
8640
Sudheer Shankab2f83c12017-11-13 19:25:01 -08008641 int length = in.readInt();
8642 if (length == NUM_PROCESS_STATE) {
8643 mProcStateTimeMs = new LongSamplingCounterArray[length];
8644 for (int procState = 0; procState < length; ++procState) {
8645 mProcStateTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8646 in, mBsi.mOnBatteryTimeBase);
8647 }
8648 } else {
8649 mProcStateTimeMs = null;
8650 }
8651 length = in.readInt();
8652 if (length == NUM_PROCESS_STATE) {
8653 mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
8654 for (int procState = 0; procState < length; ++procState) {
8655 mProcStateScreenOffTimeMs[procState] = LongSamplingCounterArray.readFromParcel(
8656 in, mBsi.mOnBatteryScreenOffTimeBase);
8657 }
8658 } else {
8659 mProcStateScreenOffTimeMs = null;
8660 }
8661
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008662 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07008663 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8664 } else {
8665 mMobileRadioApWakeupCount = null;
8666 }
8667
8668 if (in.readInt() != 0) {
8669 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
8670 } else {
8671 mWifiRadioApWakeupCount = null;
8672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008673 }
8674
8675 /**
8676 * The statistics associated with a particular wake lock.
8677 */
Joe Onoratoabded112016-02-08 16:49:39 -08008678 public static class Wakelock extends BatteryStats.Uid.Wakelock {
8679 /**
8680 * BatteryStatsImpl that we are associated with.
8681 */
8682 protected BatteryStatsImpl mBsi;
8683
8684 /**
8685 * BatteryStatsImpl that we are associated with.
8686 */
8687 protected Uid mUid;
8688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008689 /**
8690 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07008691 * 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 -08008692 */
Bookatz5b5ec322017-05-26 09:40:38 -07008693 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008694
8695 /**
8696 * How long (in ms) this uid has been keeping the device fully awake.
8697 */
Evan Millarc64edde2009-04-18 12:26:32 -07008698 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699
8700 /**
8701 * How long (in ms) this uid has had a window keeping the device awake.
8702 */
Evan Millarc64edde2009-04-18 12:26:32 -07008703 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008704
8705 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008706 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07008707 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008708 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008709
Joe Onoratoabded112016-02-08 16:49:39 -08008710 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
8711 mBsi = bsi;
8712 mUid = uid;
8713 }
8714
Adam Lesinski9425fe22015-06-19 12:02:13 -07008715 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8717 * proper timer pool from the given BatteryStatsImpl object.
8718 *
8719 * @param in the Parcel to be read from.
8720 * return a new Timer, or null.
8721 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07008722 private StopwatchTimer readStopwatchTimerFromParcel(int type,
8723 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008724 if (in.readInt() == 0) {
8725 return null;
8726 }
8727
Joe Onoratoabded112016-02-08 16:49:39 -08008728 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008729 }
8730
Joe Onorato92fd23f2016-07-25 11:18:42 -07008731 /**
8732 * Reads a possibly null Timer from a Parcel. The timer is associated with the
8733 * proper timer pool from the given BatteryStatsImpl object.
8734 *
8735 * @param in the Parcel to be read from.
8736 * return a new Timer, or null.
8737 */
Bookatz5b5ec322017-05-26 09:40:38 -07008738 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
8739 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07008740 if (in.readInt() == 0) {
8741 return null;
8742 }
8743
Bookatz5b5ec322017-05-26 09:40:38 -07008744 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008745 }
8746
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008747 boolean reset() {
8748 boolean wlactive = false;
8749 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008750 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008751 }
8752 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008753 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008754 }
8755 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008756 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008757 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008758 if (mTimerDraw != null) {
8759 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008760 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008761 if (!wlactive) {
8762 if (mTimerFull != null) {
8763 mTimerFull.detach();
8764 mTimerFull = null;
8765 }
8766 if (mTimerPartial != null) {
8767 mTimerPartial.detach();
8768 mTimerPartial = null;
8769 }
8770 if (mTimerWindow != null) {
8771 mTimerWindow.detach();
8772 mTimerWindow = null;
8773 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008774 if (mTimerDraw != null) {
8775 mTimerDraw.detach();
8776 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07008777 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008778 }
8779 return !wlactive;
8780 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008781
Bookatz5b5ec322017-05-26 09:40:38 -07008782 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
8783 TimeBase screenOffBgTimeBase, Parcel in) {
8784 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
8785 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07008786 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
8787 mBsi.mFullTimers, timeBase, in);
8788 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
8789 mBsi.mWindowTimers, timeBase, in);
8790 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
8791 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008792 }
8793
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008794 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
8795 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
8796 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
8797 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008798 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 }
8800
8801 @Override
8802 public Timer getWakeTime(int type) {
8803 switch (type) {
8804 case WAKE_TYPE_FULL: return mTimerFull;
8805 case WAKE_TYPE_PARTIAL: return mTimerPartial;
8806 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07008807 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008808 default: throw new IllegalArgumentException("type = " + type);
8809 }
8810 }
8811 }
8812
Joe Onoratoabded112016-02-08 16:49:39 -08008813 public static class Sensor extends BatteryStats.Uid.Sensor {
8814 /**
8815 * BatteryStatsImpl that we are associated with.
8816 */
8817 protected BatteryStatsImpl mBsi;
8818
8819 /**
Bookatz867c0d72017-03-07 18:23:42 -08008820 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08008821 */
8822 protected Uid mUid;
8823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008824 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08008825 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008826
Joe Onoratoabded112016-02-08 16:49:39 -08008827 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
8828 mBsi = bsi;
8829 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008830 mHandle = handle;
8831 }
8832
Bookatz867c0d72017-03-07 18:23:42 -08008833 private DualTimer readTimersFromParcel(
8834 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008835 if (in.readInt() == 0) {
8836 return null;
8837 }
8838
Joe Onoratoabded112016-02-08 16:49:39 -08008839 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008840 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07008841 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08008842 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008843 }
Bookatz867c0d72017-03-07 18:23:42 -08008844 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008845 }
8846
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008847 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008848 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008849 mTimer = null;
8850 return true;
8851 }
8852 return false;
8853 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008854
Bookatz867c0d72017-03-07 18:23:42 -08008855 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
8856 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008857 }
8858
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008859 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07008860 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008861 }
8862
8863 @Override
8864 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07008865 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008867
8868 @Override
Bookatz867c0d72017-03-07 18:23:42 -08008869 public Timer getSensorBackgroundTime() {
8870 if (mTimer == null) {
8871 return null;
8872 }
8873 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08008874 }
8875
8876 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008877 public int getHandle() {
8878 return mHandle;
8879 }
8880 }
8881
8882 /**
8883 * The statistics associated with a particular process.
8884 */
Joe Onoratoabded112016-02-08 16:49:39 -08008885 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
8886 /**
8887 * BatteryStatsImpl that we are associated with.
8888 */
8889 protected BatteryStatsImpl mBsi;
8890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008891 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008892 * The name of this process.
8893 */
8894 final String mName;
8895
8896 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08008897 * Remains true until removed from the stats.
8898 */
8899 boolean mActive = true;
8900
8901 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008902 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008903 */
8904 long mUserTime;
8905
8906 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008907 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008908 */
8909 long mSystemTime;
8910
8911 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07008912 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008913 */
8914 long mForegroundTime;
8915
8916 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008917 * Number of times the process has been started.
8918 */
8919 int mStarts;
8920
8921 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008922 * Number of times the process has crashed.
8923 */
8924 int mNumCrashes;
8925
8926 /**
8927 * Number of times the process has had an ANR.
8928 */
8929 int mNumAnrs;
8930
8931 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 * The amount of user time loaded from a previous save.
8933 */
8934 long mLoadedUserTime;
8935
8936 /**
8937 * The amount of system time loaded from a previous save.
8938 */
8939 long mLoadedSystemTime;
8940
8941 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008942 * The amount of foreground time loaded from a previous save.
8943 */
8944 long mLoadedForegroundTime;
8945
8946 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008947 * The number of times the process has started from a previous save.
8948 */
8949 int mLoadedStarts;
8950
8951 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008952 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008953 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008954 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955
8956 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008957 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008958 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008959 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008960
8961 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008962 * The amount of user time when last unplugged.
8963 */
8964 long mUnpluggedUserTime;
8965
8966 /**
8967 * The amount of system time when last unplugged.
8968 */
8969 long mUnpluggedSystemTime;
8970
8971 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008972 * The amount of foreground time since unplugged.
8973 */
8974 long mUnpluggedForegroundTime;
8975
Jeff Sharkey3e013e82013-04-25 14:48:19 -07008976 /**
8977 * The number of times the process has started before unplugged.
8978 */
8979 int mUnpluggedStarts;
8980
Dianne Hackborn61659e52014-07-09 16:13:01 -07008981 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008982 * Number of times the process has crashed before unplugged.
8983 */
8984 int mUnpluggedNumCrashes;
8985
8986 /**
8987 * Number of times the process has had an ANR before unplugged.
8988 */
8989 int mUnpluggedNumAnrs;
8990
Dianne Hackborn287952c2010-09-22 22:34:31 -07008991 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008992
Joe Onoratoabded112016-02-08 16:49:39 -08008993 public Proc(BatteryStatsImpl bsi, String name) {
8994 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008995 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08008996 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008997 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07008998
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008999 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009000 mUnpluggedUserTime = mUserTime;
9001 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009002 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07009003 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009004 mUnpluggedNumCrashes = mNumCrashes;
9005 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009006 }
9007
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009008 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009009 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009010
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009011 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009012 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08009013 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009014 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009015
Dianne Hackborn287952c2010-09-22 22:34:31 -07009016 public int countExcessivePowers() {
9017 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009018 }
9019
Dianne Hackborn287952c2010-09-22 22:34:31 -07009020 public ExcessivePower getExcessivePower(int i) {
9021 if (mExcessivePower != null) {
9022 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009023 }
9024 return null;
9025 }
9026
Dianne Hackborn287952c2010-09-22 22:34:31 -07009027 public void addExcessiveCpu(long overTime, long usedTime) {
9028 if (mExcessivePower == null) {
9029 mExcessivePower = new ArrayList<ExcessivePower>();
9030 }
9031 ExcessivePower ew = new ExcessivePower();
9032 ew.type = ExcessivePower.TYPE_CPU;
9033 ew.overTime = overTime;
9034 ew.usedTime = usedTime;
9035 mExcessivePower.add(ew);
9036 }
9037
9038 void writeExcessivePowerToParcelLocked(Parcel out) {
9039 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009040 out.writeInt(0);
9041 return;
9042 }
9043
Dianne Hackborn287952c2010-09-22 22:34:31 -07009044 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009045 out.writeInt(N);
9046 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009047 ExcessivePower ew = mExcessivePower.get(i);
9048 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009049 out.writeLong(ew.overTime);
9050 out.writeLong(ew.usedTime);
9051 }
9052 }
9053
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009054 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009055 final int N = in.readInt();
9056 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009057 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009058 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009059 }
9060
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009061 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009062 throw new ParcelFormatException(
9063 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08009064 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009065
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07009066 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009067 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009068 ExcessivePower ew = new ExcessivePower();
9069 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009070 ew.overTime = in.readLong();
9071 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009072 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009073 }
9074 }
9075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009076 void writeToParcelLocked(Parcel out) {
9077 out.writeLong(mUserTime);
9078 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009079 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009080 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009081 out.writeInt(mNumCrashes);
9082 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009083 out.writeLong(mLoadedUserTime);
9084 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009085 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009086 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009087 out.writeInt(mLoadedNumCrashes);
9088 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009089 out.writeLong(mUnpluggedUserTime);
9090 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009091 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009093 out.writeInt(mUnpluggedNumCrashes);
9094 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009095 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096 }
9097
9098 void readFromParcelLocked(Parcel in) {
9099 mUserTime = in.readLong();
9100 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009101 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009102 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009103 mNumCrashes = in.readInt();
9104 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009105 mLoadedUserTime = in.readLong();
9106 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009107 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009109 mLoadedNumCrashes = in.readInt();
9110 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009111 mUnpluggedUserTime = in.readLong();
9112 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009113 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009114 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009115 mUnpluggedNumCrashes = in.readInt();
9116 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009117 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009118 }
9119
Adam Lesinski06af1fa2015-05-05 17:35:35 -07009120 public void addCpuTimeLocked(int utime, int stime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009121 mUserTime += utime;
9122 mSystemTime += stime;
9123 }
9124
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009125 public void addForegroundTimeLocked(long ttime) {
9126 mForegroundTime += ttime;
9127 }
9128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 public void incStartsLocked() {
9130 mStarts++;
9131 }
9132
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009133 public void incNumCrashesLocked() {
9134 mNumCrashes++;
9135 }
9136
9137 public void incNumAnrsLocked() {
9138 mNumAnrs++;
9139 }
9140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009141 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009142 public boolean isActive() {
9143 return mActive;
9144 }
9145
9146 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009148 long val = mUserTime;
9149 if (which == STATS_CURRENT) {
9150 val -= mLoadedUserTime;
9151 } else if (which == STATS_SINCE_UNPLUGGED) {
9152 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009153 }
9154 return val;
9155 }
9156
9157 @Override
9158 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009159 long val = mSystemTime;
9160 if (which == STATS_CURRENT) {
9161 val -= mLoadedSystemTime;
9162 } else if (which == STATS_SINCE_UNPLUGGED) {
9163 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009164 }
9165 return val;
9166 }
9167
9168 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009169 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009170 long val = mForegroundTime;
9171 if (which == STATS_CURRENT) {
9172 val -= mLoadedForegroundTime;
9173 } else if (which == STATS_SINCE_UNPLUGGED) {
9174 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07009175 }
9176 return val;
9177 }
9178
9179 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009180 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009181 int val = mStarts;
9182 if (which == STATS_CURRENT) {
9183 val -= mLoadedStarts;
9184 } else if (which == STATS_SINCE_UNPLUGGED) {
9185 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009186 }
9187 return val;
9188 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07009189
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009190 @Override
9191 public int getNumCrashes(int which) {
9192 int val = mNumCrashes;
9193 if (which == STATS_CURRENT) {
9194 val -= mLoadedNumCrashes;
9195 } else if (which == STATS_SINCE_UNPLUGGED) {
9196 val -= mUnpluggedNumCrashes;
9197 }
9198 return val;
9199 }
9200
9201 @Override
9202 public int getNumAnrs(int which) {
9203 int val = mNumAnrs;
9204 if (which == STATS_CURRENT) {
9205 val -= mLoadedNumAnrs;
9206 } else if (which == STATS_SINCE_UNPLUGGED) {
9207 val -= mUnpluggedNumAnrs;
9208 }
9209 return val;
9210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009211 }
9212
9213 /**
9214 * The statistics associated with a particular package.
9215 */
Joe Onoratoabded112016-02-08 16:49:39 -08009216 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
9217 /**
9218 * BatteryStatsImpl that we are associated with.
9219 */
9220 protected BatteryStatsImpl mBsi;
9221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009222 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009223 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07009224 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009225 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009226 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009227
9228 /**
9229 * The statics we have collected for this package's services.
9230 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009231 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009232
Joe Onoratoabded112016-02-08 16:49:39 -08009233 public Pkg(BatteryStatsImpl bsi) {
9234 mBsi = bsi;
9235 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009236 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009237
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009238 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009239 }
9240
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009241 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009242 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009243
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009244 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08009245 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009246 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009248 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009249 int numWA = in.readInt();
9250 mWakeupAlarms.clear();
9251 for (int i=0; i<numWA; i++) {
9252 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07009253 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009255
9256 int numServs = in.readInt();
9257 mServiceStats.clear();
9258 for (int m = 0; m < numServs; m++) {
9259 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08009260 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009261 mServiceStats.put(serviceName, serv);
9262
9263 serv.readFromParcelLocked(in);
9264 }
9265 }
9266
9267 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009268 int numWA = mWakeupAlarms.size();
9269 out.writeInt(numWA);
9270 for (int i=0; i<numWA; i++) {
9271 out.writeString(mWakeupAlarms.keyAt(i));
9272 mWakeupAlarms.valueAt(i).writeToParcel(out);
9273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009274
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009275 final int NS = mServiceStats.size();
9276 out.writeInt(NS);
9277 for (int i=0; i<NS; i++) {
9278 out.writeString(mServiceStats.keyAt(i));
9279 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009280 serv.writeToParcelLocked(out);
9281 }
9282 }
9283
9284 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009285 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
9286 return mWakeupAlarms;
9287 }
9288
9289 public void noteWakeupAlarmLocked(String tag) {
9290 Counter c = mWakeupAlarms.get(tag);
9291 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07009292 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009293 mWakeupAlarms.put(tag, c);
9294 }
9295 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009296 }
9297
9298 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07009299 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
9300 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009301 }
9302
9303 /**
9304 * The statistics associated with a particular service.
9305 */
Joe Onoratoabded112016-02-08 16:49:39 -08009306 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
9307 /**
9308 * BatteryStatsImpl that we are associated with.
9309 */
9310 protected BatteryStatsImpl mBsi;
9311
9312 /**
9313 * The android package in which this service resides.
9314 */
9315 protected Pkg mPkg;
9316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 /**
9318 * Total time (ms in battery uptime) the service has been left started.
9319 */
Joe Onoratoabded112016-02-08 16:49:39 -08009320 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009321
9322 /**
9323 * If service has been started and not yet stopped, this is
9324 * when it was started.
9325 */
Joe Onoratoabded112016-02-08 16:49:39 -08009326 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009327
9328 /**
9329 * True if we are currently running.
9330 */
Joe Onoratoabded112016-02-08 16:49:39 -08009331 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009332
9333 /**
9334 * Total number of times startService() has been called.
9335 */
Joe Onoratoabded112016-02-08 16:49:39 -08009336 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009337
9338 /**
9339 * Total time (ms in battery uptime) the service has been left launched.
9340 */
Joe Onoratoabded112016-02-08 16:49:39 -08009341 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009342
9343 /**
9344 * If service has been launched and not yet exited, this is
9345 * when it was launched (ms in battery uptime).
9346 */
Joe Onoratoabded112016-02-08 16:49:39 -08009347 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009348
9349 /**
9350 * True if we are currently launched.
9351 */
Joe Onoratoabded112016-02-08 16:49:39 -08009352 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353
9354 /**
9355 * Total number times the service has been launched.
9356 */
Joe Onoratoabded112016-02-08 16:49:39 -08009357 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009358
9359 /**
9360 * The amount of time spent started loaded from a previous save
9361 * (ms in battery uptime).
9362 */
Joe Onoratoabded112016-02-08 16:49:39 -08009363 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009364
9365 /**
9366 * The number of starts loaded from a previous save.
9367 */
Joe Onoratoabded112016-02-08 16:49:39 -08009368 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009369
9370 /**
9371 * The number of launches loaded from a previous save.
9372 */
Joe Onoratoabded112016-02-08 16:49:39 -08009373 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009374
9375 /**
9376 * The amount of time spent started as of the last run (ms
9377 * in battery uptime).
9378 */
Joe Onoratoabded112016-02-08 16:49:39 -08009379 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009380
9381 /**
9382 * The number of starts as of the last run.
9383 */
Joe Onoratoabded112016-02-08 16:49:39 -08009384 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009385
9386 /**
9387 * The number of launches as of the last run.
9388 */
Joe Onoratoabded112016-02-08 16:49:39 -08009389 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009390
9391 /**
9392 * The amount of time spent started when last unplugged (ms
9393 * in battery uptime).
9394 */
Joe Onoratoabded112016-02-08 16:49:39 -08009395 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009396
9397 /**
9398 * The number of starts when last unplugged.
9399 */
Joe Onoratoabded112016-02-08 16:49:39 -08009400 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401
9402 /**
9403 * The number of launches when last unplugged.
9404 */
Joe Onoratoabded112016-02-08 16:49:39 -08009405 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009406
Joe Onoratoabded112016-02-08 16:49:39 -08009407 /**
9408 * Construct a Serv. Also adds it to the on-battery time base as a listener.
9409 */
9410 public Serv(BatteryStatsImpl bsi) {
9411 mBsi = bsi;
9412 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009413 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009414
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009415 public void onTimeStarted(long elapsedRealtime, long baseUptime,
9416 long baseRealtime) {
9417 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009418 mUnpluggedStarts = mStarts;
9419 mUnpluggedLaunches = mLaunches;
9420 }
9421
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009422 public void onTimeStopped(long elapsedRealtime, long baseUptime,
9423 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009424 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009425
Joe Onoratoabded112016-02-08 16:49:39 -08009426 /**
9427 * Remove this Serv as a listener from the time base.
9428 */
9429 public void detach() {
9430 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009431 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009432
Joe Onoratoabded112016-02-08 16:49:39 -08009433 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 mStartTime = in.readLong();
9435 mRunningSince = in.readLong();
9436 mRunning = in.readInt() != 0;
9437 mStarts = in.readInt();
9438 mLaunchedTime = in.readLong();
9439 mLaunchedSince = in.readLong();
9440 mLaunched = in.readInt() != 0;
9441 mLaunches = in.readInt();
9442 mLoadedStartTime = in.readLong();
9443 mLoadedStarts = in.readInt();
9444 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07009445 mLastStartTime = 0;
9446 mLastStarts = 0;
9447 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009448 mUnpluggedStartTime = in.readLong();
9449 mUnpluggedStarts = in.readInt();
9450 mUnpluggedLaunches = in.readInt();
9451 }
9452
Joe Onoratoabded112016-02-08 16:49:39 -08009453 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009454 out.writeLong(mStartTime);
9455 out.writeLong(mRunningSince);
9456 out.writeInt(mRunning ? 1 : 0);
9457 out.writeInt(mStarts);
9458 out.writeLong(mLaunchedTime);
9459 out.writeLong(mLaunchedSince);
9460 out.writeInt(mLaunched ? 1 : 0);
9461 out.writeInt(mLaunches);
9462 out.writeLong(mLoadedStartTime);
9463 out.writeInt(mLoadedStarts);
9464 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009465 out.writeLong(mUnpluggedStartTime);
9466 out.writeInt(mUnpluggedStarts);
9467 out.writeInt(mUnpluggedLaunches);
9468 }
9469
Joe Onoratoabded112016-02-08 16:49:39 -08009470 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009471 if (!mLaunched) return mLaunchedTime;
9472 return mLaunchedTime + batteryUptime - mLaunchedSince;
9473 }
9474
Joe Onoratoabded112016-02-08 16:49:39 -08009475 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476 if (!mRunning) return mStartTime;
9477 return mStartTime + batteryUptime - mRunningSince;
9478 }
9479
9480 public void startLaunchedLocked() {
9481 if (!mLaunched) {
9482 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08009483 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009484 mLaunched = true;
9485 }
9486 }
9487
9488 public void stopLaunchedLocked() {
9489 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08009490 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009491 if (time > 0) {
9492 mLaunchedTime += time;
9493 } else {
9494 mLaunches--;
9495 }
9496 mLaunched = false;
9497 }
9498 }
9499
9500 public void startRunningLocked() {
9501 if (!mRunning) {
9502 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08009503 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009504 mRunning = true;
9505 }
9506 }
9507
9508 public void stopRunningLocked() {
9509 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08009510 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009511 if (time > 0) {
9512 mStartTime += time;
9513 } else {
9514 mStarts--;
9515 }
9516 mRunning = false;
9517 }
9518 }
9519
9520 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009521 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009522 }
9523
9524 @Override
9525 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009526 int val = mLaunches;
9527 if (which == STATS_CURRENT) {
9528 val -= mLoadedLaunches;
9529 } else if (which == STATS_SINCE_UNPLUGGED) {
9530 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009532 return val;
9533 }
9534
9535 @Override
9536 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009537 long val = getStartTimeToNowLocked(now);
9538 if (which == STATS_CURRENT) {
9539 val -= mLoadedStartTime;
9540 } else if (which == STATS_SINCE_UNPLUGGED) {
9541 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009543 return val;
9544 }
9545
9546 @Override
9547 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07009548 int val = mStarts;
9549 if (which == STATS_CURRENT) {
9550 val -= mLoadedStarts;
9551 } else if (which == STATS_SINCE_UNPLUGGED) {
9552 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009553 }
9554
9555 return val;
9556 }
9557 }
9558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009559 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08009560 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009561 }
9562 }
9563
9564 /**
9565 * Retrieve the statistics object for a particular process, creating
9566 * if needed.
9567 */
9568 public Proc getProcessStatsLocked(String name) {
9569 Proc ps = mProcessStats.get(name);
9570 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009571 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009572 mProcessStats.put(name, ps);
9573 }
9574
9575 return ps;
9576 }
9577
Dianne Hackborna8d10942015-11-19 17:55:19 -08009578 public void updateUidProcessStateLocked(int procState) {
9579 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009580 // Make special note of Foreground Services
9581 final boolean userAwareService =
9582 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009583 uidRunningState = BatteryStats.mapToInternalProcessState(procState);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009584
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009585 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
9586 return;
9587 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08009588
Bookatz867c0d72017-03-07 18:23:42 -08009589 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009590 if (mProcessState != uidRunningState) {
9591 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08009592
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009593 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9594 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009595
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009596 if (mBsi.trackPerProcStateCpuTimes()) {
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009597 if (mBsi.mPendingUids.size() == 0) {
Sudheer Shankae544d162017-12-28 17:06:20 -08009598 mBsi.mExternalSync.scheduleReadProcStateCpuTimes(
9599 mBsi.mOnBatteryTimeBase.isRunning(),
9600 mBsi.mOnBatteryScreenOffTimeBase.isRunning());
Sudheer Shankab2f83c12017-11-13 19:25:01 -08009601 }
9602 if (mBsi.mPendingUids.indexOfKey(mUid) < 0
9603 || ArrayUtils.contains(CRITICAL_PROC_STATES, mProcessState)) {
9604 mBsi.mPendingUids.put(mUid, mProcessState);
9605 }
9606 } else {
9607 mBsi.mPendingUids.clear();
9608 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07009609 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009610 mProcessState = uidRunningState;
9611 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
9612 if (mProcessStateTimer[uidRunningState] == null) {
9613 makeProcessState(uidRunningState, null);
9614 }
9615 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
9616 }
9617
9618 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
9619 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009620 }
Bookatz867c0d72017-03-07 18:23:42 -08009621
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07009622 if (userAwareService != mInForegroundService) {
9623 if (userAwareService) {
9624 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
9625 } else {
9626 noteForegroundServicePausedLocked(elapsedRealtimeMs);
9627 }
9628 mInForegroundService = userAwareService;
9629 }
Bookatz867c0d72017-03-07 18:23:42 -08009630 }
9631
Bookatzc8c44962017-05-11 12:12:54 -07009632 /** Whether to consider Uid to be in the background for background timebase purposes. */
9633 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08009634 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
9635 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07009636 return mProcessState >= PROCESS_STATE_BACKGROUND;
9637 }
9638
9639 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
9640 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
9641 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
9642 }
9643
9644 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
9645 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
9646 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07009647 }
9648
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009649 public SparseArray<? extends Pid> getPidStats() {
9650 return mPids;
9651 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009652
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009653 public Pid getPidStatsLocked(int pid) {
9654 Pid p = mPids.get(pid);
9655 if (p == null) {
9656 p = new Pid();
9657 mPids.put(pid, p);
9658 }
9659 return p;
9660 }
9661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009662 /**
9663 * Retrieve the statistics object for a particular service, creating
9664 * if needed.
9665 */
9666 public Pkg getPackageStatsLocked(String name) {
9667 Pkg ps = mPackageStats.get(name);
9668 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08009669 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009670 mPackageStats.put(name, ps);
9671 }
9672
9673 return ps;
9674 }
9675
9676 /**
9677 * Retrieve the statistics object for a particular service, creating
9678 * if needed.
9679 */
9680 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
9681 Pkg ps = getPackageStatsLocked(pkg);
9682 Pkg.Serv ss = ps.mServiceStats.get(serv);
9683 if (ss == null) {
9684 ss = ps.newServiceStatsLocked();
9685 ps.mServiceStats.put(serv, ss);
9686 }
9687
9688 return ss;
9689 }
9690
Dianne Hackbornd953c532014-08-16 18:17:38 -07009691 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009692 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009693 timer.readSummaryFromParcelLocked(in);
9694 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009695 }
9696
Dianne Hackbornd953c532014-08-16 18:17:38 -07009697 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07009698 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07009699 timer.readSummaryFromParcelLocked(in);
9700 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009701 }
9702
Dianne Hackbornd953c532014-08-16 18:17:38 -07009703 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08009704 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009705 mWakelockStats.add(wlName, wl);
9706 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009707 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009708 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07009709 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009710 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07009711 }
9712 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009713 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009714 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07009715 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07009716 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07009717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009718 }
9719
Bookatz867c0d72017-03-07 18:23:42 -08009720 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009721 Sensor se = mSensorStats.get(sensor);
9722 if (se == null) {
9723 if (!create) {
9724 return null;
9725 }
Joe Onoratoabded112016-02-08 16:49:39 -08009726 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009727 mSensorStats.put(sensor, se);
9728 }
Bookatz867c0d72017-03-07 18:23:42 -08009729 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009730 if (t != null) {
9731 return t;
9732 }
Joe Onoratoabded112016-02-08 16:49:39 -08009733 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009734 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07009735 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08009736 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009737 }
Bookatz867c0d72017-03-07 18:23:42 -08009738 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
9739 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009740 se.mTimer = t;
9741 return t;
9742 }
9743
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009744 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009745 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009746 if (t != null) {
9747 t.startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08009748 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name, 1);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009749 }
9750 }
9751
9752 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07009753 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009754 if (t != null) {
9755 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009756 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08009757 StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07009758 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009759 }
9760 }
9761
9762 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07009763 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009764 if (t != null) {
9765 t.startRunningLocked(elapsedRealtimeMs);
Yangster-mac2f5daec2018-01-16 10:23:15 -08009766 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
9767 name, 1);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009768 }
9769 }
9770
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009771 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07009772 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009773 if (t != null) {
9774 t.stopRunningLocked(elapsedRealtimeMs);
Bookatzc1a050a2017-10-10 15:49:28 -07009775 if (!t.isRunningLocked()) { // only tell statsd if truly stopped
Yangster-mac2f5daec2018-01-16 10:23:15 -08009776 StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
9777 name, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07009778 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009779 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07009780 if (mBsi.mOnBatteryTimeBase.isRunning()) {
9781 SparseIntArray types = mJobCompletions.get(name);
9782 if (types == null) {
9783 types = new SparseIntArray();
9784 mJobCompletions.put(name, types);
9785 }
9786 int last = types.get(stopReason, 0);
9787 types.put(stopReason, last + 1);
9788 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07009789 }
9790
Bookatz5b5ec322017-05-26 09:40:38 -07009791 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
9792 if (wl == null) {
9793 return null;
9794 }
9795 switch (type) {
9796 case WAKE_TYPE_PARTIAL: {
9797 DualTimer t = wl.mTimerPartial;
9798 if (t == null) {
9799 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
9800 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
9801 mOnBatteryScreenOffBackgroundTimeBase);
9802 wl.mTimerPartial = t;
9803 }
9804 return t;
9805 }
9806 case WAKE_TYPE_FULL: {
9807 StopwatchTimer t = wl.mTimerFull;
9808 if (t == null) {
9809 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
9810 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
9811 wl.mTimerFull = t;
9812 }
9813 return t;
9814 }
9815 case WAKE_TYPE_WINDOW: {
9816 StopwatchTimer t = wl.mTimerWindow;
9817 if (t == null) {
9818 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
9819 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
9820 wl.mTimerWindow = t;
9821 }
9822 return t;
9823 }
9824 case WAKE_TYPE_DRAW: {
9825 StopwatchTimer t = wl.mTimerDraw;
9826 if (t == null) {
9827 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
9828 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
9829 wl.mTimerDraw = t;
9830 }
9831 return t;
9832 }
9833 default:
9834 throw new IllegalArgumentException("type=" + type);
9835 }
9836 }
9837
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009838 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009839 Wakelock wl = mWakelockStats.startObject(name);
9840 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07009841 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009842 }
Bookatzc8c44962017-05-11 12:12:54 -07009843 if (type == WAKE_TYPE_PARTIAL) {
9844 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
9845 if (pid >= 0) {
9846 Pid p = getPidStatsLocked(pid);
9847 if (p.mWakeNesting++ == 0) {
9848 p.mWakeStartMs = elapsedRealtimeMs;
9849 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -07009850 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009852 }
9853
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009854 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07009855 Wakelock wl = mWakelockStats.stopObject(name);
9856 if (wl != null) {
Bookatzd6746242017-10-24 18:39:35 -07009857 StopwatchTimer wlt = getWakelockTimerLocked(wl, type);
9858 wlt.stopRunningLocked(elapsedRealtimeMs);
9859 if (!wlt.isRunningLocked()) { // only tell statsd if truly stopped
Bookatzd6746242017-10-24 18:39:35 -07009860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009861 }
Bookatzc8c44962017-05-11 12:12:54 -07009862 if (type == WAKE_TYPE_PARTIAL) {
9863 if (mAggregatedPartialWakelockTimer != null) {
9864 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
9865 }
9866 if (pid >= 0) {
9867 Pid p = mPids.get(pid);
9868 if (p != null && p.mWakeNesting > 0) {
9869 if (p.mWakeNesting-- == 1) {
9870 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
9871 p.mWakeStartMs = 0;
9872 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08009873 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009874 }
9875 }
9876 }
9877
Dianne Hackborn287952c2010-09-22 22:34:31 -07009878 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
9879 Proc p = getProcessStatsLocked(proc);
9880 if (p != null) {
9881 p.addExcessiveCpu(overTime, usedTime);
9882 }
9883 }
9884
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009885 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009886 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -08009887 t.startRunningLocked(elapsedRealtimeMs);
Narayan Kamath32684dd2018-01-08 17:32:51 +00009888 if (sensor != Sensor.GPS) {
Yangster-mac2f5daec2018-01-16 10:23:15 -08009889 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null, sensor,
9890 1);
Bookatzc1a050a2017-10-10 15:49:28 -07009891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009892 }
9893
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009894 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009895 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -08009896 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009897 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009898 t.stopRunningLocked(elapsedRealtimeMs);
Narayan Kamath32684dd2018-01-08 17:32:51 +00009899 if (sensor != Sensor.GPS) {
9900 StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null,
9901 sensor, 0);
Bookatzc1a050a2017-10-10 15:49:28 -07009902 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009904 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009905
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009906 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009907 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009908 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009909
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009910 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08009911 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009912 }
9913
9914 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08009915 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009916 }
9917 }
9918
Sudheer Shanka9b735c52017-05-09 18:26:18 -07009919 public long[] getCpuFreqs() {
9920 return mCpuFreqs;
9921 }
9922
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009923 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
9924 UserInfoProvider userInfoProvider) {
9925 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07009926 }
9927
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07009928 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
9929 PlatformIdleStateCallback cb,
9930 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -08009931 init(clocks);
9932
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009933 if (systemDir != null) {
9934 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
9935 new File(systemDir, "batterystats.bin.tmp"));
9936 } else {
9937 mFile = null;
9938 }
9939 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009940 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -08009941 mHandler = new MyHandler(handler.getLooper());
Sudheer Shanka5c19b892018-01-05 17:25:46 -08009942 mConstants = new Constants(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009943 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -08009944 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -07009945 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07009946 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009947 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009948 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009949 }
Joe Onoratoabded112016-02-08 16:49:39 -08009950 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
9951 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
9952 mOnBatteryTimeBase);
9953 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
9954 mOnBatteryTimeBase);
9955 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
9956 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
9957 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
9958 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
9959 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
9960 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
9961 mOnBatteryTimeBase);
9962 }
9963 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
9964 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009965 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009966 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009967 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07009968 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009969 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009970 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
9971 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009972 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009973 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
9974 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
9975 NUM_BT_TX_LEVELS);
9976 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
9977 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -08009978 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
9979 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
9980 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009981 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009982 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
9983 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -08009984 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null,
9985 WIFI_AGGREGATE_MULTICAST_ENABLED, null, mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08009986 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
9987 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08009988 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08009989 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -07009990 mOnBatteryTimeBase);
9991 }
Joe Onoratoabded112016-02-08 16:49:39 -08009992 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9993 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
9994 mOnBatteryTimeBase);
9995 }
9996 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9997 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
9998 mOnBatteryTimeBase);
9999 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080010000 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null, mOnBatteryTimeBase);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010001 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10002 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i, null,
10003 mOnBatteryTimeBase);
10004 }
Joe Onoratoabded112016-02-08 16:49:39 -080010005 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
10006 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
10007 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
10008 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
10009 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010010 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
Mike Mac2f518a2017-09-19 16:06:03 -070010011 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Mike Ma15313c92017-11-15 17:58:21 -080010012 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
10013 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010014 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010015 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -080010016 long uptime = mClocks.uptimeMillis() * 1000;
10017 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010018 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070010019 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -070010020 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010021 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010022 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -070010023 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010024 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010025 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010026 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010027 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010028 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010029 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010030 }
10031
10032 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -080010033 this(new SystemClocks(), p);
10034 }
10035
10036 public BatteryStatsImpl(Clocks clocks, Parcel p) {
10037 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070010038 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010039 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010040 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010041 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010042 mExternalSync = null;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080010043 mConstants = new Constants(mHandler);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010044 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010045 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -070010046 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010047 }
10048
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010049 public void setPowerProfileLocked(PowerProfile profile) {
10050 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -070010051
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010052 // We need to initialize the KernelCpuSpeedReaders to read from
10053 // the first cpu of each core. Once we have the PowerProfile, we have access to this
10054 // information.
10055 final int numClusters = mPowerProfile.getNumCpuClusters();
10056 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
10057 int firstCpuOfCluster = 0;
10058 for (int i = 0; i < numClusters; i++) {
10059 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
10060 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
10061 numSpeedSteps);
10062 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
10063 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010064
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010065 if (mEstimatedBatteryCapacity == -1) {
10066 // Initialize the estimated battery capacity to a known preset one.
10067 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -070010068 }
10069 }
10070
Dianne Hackborn0d903a82010-09-07 23:51:03 -070010071 public void setCallback(BatteryCallback cb) {
10072 mCallback = cb;
10073 }
10074
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010075 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -070010076 if (mPhoneSignalScanningTimer != null) {
10077 mPhoneSignalScanningTimer.setTimeout(timeout);
10078 }
10079 }
10080
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070010081 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
10082 mExternalSync = sync;
10083 }
10084
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010085 public void updateDailyDeadlineLocked() {
10086 // Get the current time.
10087 long currentTime = mDailyStartTime = System.currentTimeMillis();
10088 Calendar calDeadline = Calendar.getInstance();
10089 calDeadline.setTimeInMillis(currentTime);
10090
10091 // Move time up to the next day, ranging from 1am to 3pm.
10092 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
10093 calDeadline.set(Calendar.MILLISECOND, 0);
10094 calDeadline.set(Calendar.SECOND, 0);
10095 calDeadline.set(Calendar.MINUTE, 0);
10096 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
10097 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
10098 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
10099 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
10100 }
10101
10102 public void recordDailyStatsIfNeededLocked(boolean settled) {
10103 long currentTime = System.currentTimeMillis();
10104 if (currentTime >= mNextMaxDailyDeadline) {
10105 recordDailyStatsLocked();
10106 } else if (settled && currentTime >= mNextMinDailyDeadline) {
10107 recordDailyStatsLocked();
10108 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
10109 recordDailyStatsLocked();
10110 }
10111 }
10112
10113 public void recordDailyStatsLocked() {
10114 DailyItem item = new DailyItem();
10115 item.mStartTime = mDailyStartTime;
10116 item.mEndTime = System.currentTimeMillis();
10117 boolean hasData = false;
10118 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
10119 hasData = true;
10120 item.mDischargeSteps = new LevelStepTracker(
10121 mDailyDischargeStepTracker.mNumStepDurations,
10122 mDailyDischargeStepTracker.mStepDurations);
10123 }
10124 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
10125 hasData = true;
10126 item.mChargeSteps = new LevelStepTracker(
10127 mDailyChargeStepTracker.mNumStepDurations,
10128 mDailyChargeStepTracker.mStepDurations);
10129 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010130 if (mDailyPackageChanges != null) {
10131 hasData = true;
10132 item.mPackageChanges = mDailyPackageChanges;
10133 mDailyPackageChanges = null;
10134 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010135 mDailyDischargeStepTracker.init();
10136 mDailyChargeStepTracker.init();
10137 updateDailyDeadlineLocked();
10138
10139 if (hasData) {
10140 mDailyItems.add(item);
10141 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
10142 mDailyItems.remove(0);
10143 }
10144 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
10145 try {
10146 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010147 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010148 writeDailyItemsLocked(out);
10149 BackgroundThread.getHandler().post(new Runnable() {
10150 @Override
10151 public void run() {
10152 synchronized (mCheckinFile) {
10153 FileOutputStream stream = null;
10154 try {
10155 stream = mDailyFile.startWrite();
10156 memStream.writeTo(stream);
10157 stream.flush();
10158 FileUtils.sync(stream);
10159 stream.close();
10160 mDailyFile.finishWrite(stream);
10161 } catch (IOException e) {
10162 Slog.w("BatteryStats",
10163 "Error writing battery daily items", e);
10164 mDailyFile.failWrite(stream);
10165 }
10166 }
10167 }
10168 });
10169 } catch (IOException e) {
10170 }
10171 }
10172 }
10173
10174 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
10175 StringBuilder sb = new StringBuilder(64);
10176 out.startDocument(null, true);
10177 out.startTag(null, "daily-items");
10178 for (int i=0; i<mDailyItems.size(); i++) {
10179 final DailyItem dit = mDailyItems.get(i);
10180 out.startTag(null, "item");
10181 out.attribute(null, "start", Long.toString(dit.mStartTime));
10182 out.attribute(null, "end", Long.toString(dit.mEndTime));
10183 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
10184 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010185 if (dit.mPackageChanges != null) {
10186 for (int j=0; j<dit.mPackageChanges.size(); j++) {
10187 PackageChange pc = dit.mPackageChanges.get(j);
10188 if (pc.mUpdate) {
10189 out.startTag(null, "upd");
10190 out.attribute(null, "pkg", pc.mPackageName);
Dianne Hackborn3accca02013-09-20 09:32:11 -070010191 out.attribute(null, "ver", Long.toString(pc.mVersionCode));
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010192 out.endTag(null, "upd");
10193 } else {
10194 out.startTag(null, "rem");
10195 out.attribute(null, "pkg", pc.mPackageName);
10196 out.endTag(null, "rem");
10197 }
10198 }
10199 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010200 out.endTag(null, "item");
10201 }
10202 out.endTag(null, "daily-items");
10203 out.endDocument();
10204 }
10205
10206 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
10207 StringBuilder tmpBuilder) throws IOException {
10208 if (steps != null) {
10209 out.startTag(null, tag);
10210 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
10211 for (int i=0; i<steps.mNumStepDurations; i++) {
10212 out.startTag(null, "s");
10213 tmpBuilder.setLength(0);
10214 steps.encodeEntryAt(i, tmpBuilder);
10215 out.attribute(null, "v", tmpBuilder.toString());
10216 out.endTag(null, "s");
10217 }
10218 out.endTag(null, tag);
10219 }
10220 }
10221
10222 public void readDailyStatsLocked() {
10223 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
10224 mDailyItems.clear();
10225 FileInputStream stream;
10226 try {
10227 stream = mDailyFile.openRead();
10228 } catch (FileNotFoundException e) {
10229 return;
10230 }
10231 try {
10232 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010010233 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010234 readDailyItemsLocked(parser);
10235 } catch (XmlPullParserException e) {
10236 } finally {
10237 try {
10238 stream.close();
10239 } catch (IOException e) {
10240 }
10241 }
10242 }
10243
10244 private void readDailyItemsLocked(XmlPullParser parser) {
10245 try {
10246 int type;
10247 while ((type = parser.next()) != XmlPullParser.START_TAG
10248 && type != XmlPullParser.END_DOCUMENT) {
10249 ;
10250 }
10251
10252 if (type != XmlPullParser.START_TAG) {
10253 throw new IllegalStateException("no start tag found");
10254 }
10255
10256 int outerDepth = parser.getDepth();
10257 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10258 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10259 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10260 continue;
10261 }
10262
10263 String tagName = parser.getName();
10264 if (tagName.equals("item")) {
10265 readDailyItemTagLocked(parser);
10266 } else {
10267 Slog.w(TAG, "Unknown element under <daily-items>: "
10268 + parser.getName());
10269 XmlUtils.skipCurrentTag(parser);
10270 }
10271 }
10272
10273 } catch (IllegalStateException e) {
10274 Slog.w(TAG, "Failed parsing daily " + e);
10275 } catch (NullPointerException e) {
10276 Slog.w(TAG, "Failed parsing daily " + e);
10277 } catch (NumberFormatException e) {
10278 Slog.w(TAG, "Failed parsing daily " + e);
10279 } catch (XmlPullParserException e) {
10280 Slog.w(TAG, "Failed parsing daily " + e);
10281 } catch (IOException e) {
10282 Slog.w(TAG, "Failed parsing daily " + e);
10283 } catch (IndexOutOfBoundsException e) {
10284 Slog.w(TAG, "Failed parsing daily " + e);
10285 }
10286 }
10287
10288 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
10289 XmlPullParserException, IOException {
10290 DailyItem dit = new DailyItem();
10291 String attr = parser.getAttributeValue(null, "start");
10292 if (attr != null) {
10293 dit.mStartTime = Long.parseLong(attr);
10294 }
10295 attr = parser.getAttributeValue(null, "end");
10296 if (attr != null) {
10297 dit.mEndTime = Long.parseLong(attr);
10298 }
10299 int outerDepth = parser.getDepth();
10300 int type;
10301 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10302 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10303 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10304 continue;
10305 }
10306
10307 String tagName = parser.getName();
10308 if (tagName.equals("dis")) {
10309 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
10310 } else if (tagName.equals("chg")) {
10311 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010312 } else if (tagName.equals("upd")) {
10313 if (dit.mPackageChanges == null) {
10314 dit.mPackageChanges = new ArrayList<>();
10315 }
10316 PackageChange pc = new PackageChange();
10317 pc.mUpdate = true;
10318 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10319 String verStr = parser.getAttributeValue(null, "ver");
Dianne Hackborn3accca02013-09-20 09:32:11 -070010320 pc.mVersionCode = verStr != null ? Long.parseLong(verStr) : 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010321 dit.mPackageChanges.add(pc);
10322 XmlUtils.skipCurrentTag(parser);
10323 } else if (tagName.equals("rem")) {
10324 if (dit.mPackageChanges == null) {
10325 dit.mPackageChanges = new ArrayList<>();
10326 }
10327 PackageChange pc = new PackageChange();
10328 pc.mUpdate = false;
10329 pc.mPackageName = parser.getAttributeValue(null, "pkg");
10330 dit.mPackageChanges.add(pc);
10331 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010332 } else {
10333 Slog.w(TAG, "Unknown element under <item>: "
10334 + parser.getName());
10335 XmlUtils.skipCurrentTag(parser);
10336 }
10337 }
10338 mDailyItems.add(dit);
10339 }
10340
10341 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
10342 String tag)
10343 throws NumberFormatException, XmlPullParserException, IOException {
10344 final String numAttr = parser.getAttributeValue(null, "n");
10345 if (numAttr == null) {
10346 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
10347 XmlUtils.skipCurrentTag(parser);
10348 return;
10349 }
10350 final int num = Integer.parseInt(numAttr);
10351 LevelStepTracker steps = new LevelStepTracker(num);
10352 if (isCharge) {
10353 dit.mChargeSteps = steps;
10354 } else {
10355 dit.mDischargeSteps = steps;
10356 }
10357 int i = 0;
10358 int outerDepth = parser.getDepth();
10359 int type;
10360 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
10361 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
10362 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
10363 continue;
10364 }
10365
10366 String tagName = parser.getName();
10367 if ("s".equals(tagName)) {
10368 if (i < num) {
10369 String valueAttr = parser.getAttributeValue(null, "v");
10370 if (valueAttr != null) {
10371 steps.decodeEntryAt(i, valueAttr);
10372 i++;
10373 }
10374 }
10375 } else {
10376 Slog.w(TAG, "Unknown element under <" + tag + ">: "
10377 + parser.getName());
10378 XmlUtils.skipCurrentTag(parser);
10379 }
10380 }
10381 steps.mNumStepDurations = i;
10382 }
10383
10384 @Override
10385 public DailyItem getDailyItemLocked(int daysAgo) {
10386 int index = mDailyItems.size()-1-daysAgo;
10387 return index >= 0 ? mDailyItems.get(index) : null;
10388 }
10389
10390 @Override
10391 public long getCurrentDailyStartTime() {
10392 return mDailyStartTime;
10393 }
10394
10395 @Override
10396 public long getNextMinDailyDeadline() {
10397 return mNextMinDailyDeadline;
10398 }
10399
10400 @Override
10401 public long getNextMaxDailyDeadline() {
10402 return mNextMaxDailyDeadline;
10403 }
10404
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010405 @Override
10406 public boolean startIteratingOldHistoryLocked() {
10407 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10408 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010409 if ((mHistoryIterator = mHistory) == null) {
10410 return false;
10411 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010412 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010413 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010414 mReadOverflow = false;
10415 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010416 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010417 }
10418
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010419 @Override
10420 public boolean getNextOldHistoryLocked(HistoryItem out) {
10421 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
10422 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010423 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010424 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010425 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010426 HistoryItem cur = mHistoryIterator;
10427 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010428 if (!mReadOverflow && !end) {
10429 Slog.w(TAG, "Old history ends before new history!");
10430 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010431 return false;
10432 }
10433 out.setTo(cur);
10434 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010435 if (!mReadOverflow) {
10436 if (end) {
10437 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010438 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -070010439 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010440 pw.println("Histories differ!");
10441 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010442 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010443 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010444 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
10445 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -070010446 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010447 }
10448 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070010449 return true;
10450 }
10451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010452 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010453 public void finishIteratingOldHistoryLocked() {
10454 mIteratingHistory = false;
10455 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010456 mHistoryIterator = null;
10457 }
10458
10459 public int getHistoryTotalSize() {
10460 return MAX_HISTORY_BUFFER;
10461 }
10462
10463 public int getHistoryUsedSize() {
10464 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010465 }
10466
10467 @Override
10468 public boolean startIteratingHistoryLocked() {
10469 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
10470 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010471 if (mHistoryBuffer.dataSize() <= 0) {
10472 return false;
10473 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010474 mHistoryBuffer.setDataPosition(0);
10475 mReadOverflow = false;
10476 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010477 mReadHistoryStrings = new String[mHistoryTagPool.size()];
10478 mReadHistoryUids = new int[mHistoryTagPool.size()];
10479 mReadHistoryChars = 0;
10480 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
10481 final HistoryTag tag = ent.getKey();
10482 final int idx = ent.getValue();
10483 mReadHistoryStrings[idx] = tag.string;
10484 mReadHistoryUids[idx] = tag.uid;
10485 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080010486 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010487 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010488 }
10489
10490 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -080010491 public int getHistoryStringPoolSize() {
10492 return mReadHistoryStrings.length;
10493 }
10494
10495 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010496 public int getHistoryStringPoolBytes() {
10497 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
10498 // Each string character is 2 bytes.
10499 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
10500 }
10501
10502 @Override
10503 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080010504 return mReadHistoryStrings[index];
10505 }
10506
10507 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080010508 public int getHistoryTagPoolUid(int index) {
10509 return mReadHistoryUids[index];
10510 }
10511
10512 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010513 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -070010514 final int pos = mHistoryBuffer.dataPosition();
10515 if (pos == 0) {
10516 out.clear();
10517 }
10518 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010519 if (end) {
10520 return false;
10521 }
10522
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010523 final long lastRealtime = out.time;
10524 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010525 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -070010526 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
10527 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -070010528 out.currentTime = lastWalltime + (out.time - lastRealtime);
10529 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070010530 return true;
10531 }
10532
10533 @Override
10534 public void finishIteratingHistoryLocked() {
10535 mIteratingHistory = false;
10536 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -080010537 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010538 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010539
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010540 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010541 public long getHistoryBaseTime() {
10542 return mHistoryBaseTime;
10543 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010544
Dianne Hackbornb5e31652010-09-07 12:13:55 -070010545 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010546 public int getStartCount() {
10547 return mStartCount;
10548 }
10549
10550 public boolean isOnBattery() {
10551 return mOnBattery;
10552 }
10553
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010554 public boolean isCharging() {
10555 return mCharging;
10556 }
10557
Mike Mac2f518a2017-09-19 16:06:03 -070010558 public boolean isScreenOn(int state) {
Chris Phoenix10a4a642017-09-25 13:21:00 -070010559 return state == Display.STATE_ON || state == Display.STATE_VR
10560 || state == Display.STATE_ON_SUSPEND;
Mike Mac2f518a2017-09-19 16:06:03 -070010561 }
10562
10563 public boolean isScreenOff(int state) {
10564 return state == Display.STATE_OFF;
10565 }
10566
10567 public boolean isScreenDoze(int state) {
10568 return state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070010569 }
10570
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010571 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080010572 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010573 mOnBatteryTimeBase.init(uptime, realtime);
10574 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -070010575 mRealtime = 0;
10576 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010577 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -070010578 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010579 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010580
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010581 void initDischarge() {
10582 mLowDischargeAmountSinceCharge = 0;
10583 mHighDischargeAmountSinceCharge = 0;
10584 mDischargeAmountScreenOn = 0;
10585 mDischargeAmountScreenOnSinceCharge = 0;
10586 mDischargeAmountScreenOff = 0;
10587 mDischargeAmountScreenOffSinceCharge = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010588 mDischargeAmountScreenDoze = 0;
10589 mDischargeAmountScreenDozeSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010590 mDischargeStepTracker.init();
10591 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010592 mDischargeScreenOffCounter.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010593 mDischargeScreenDozeCounter.reset(false);
Mike Ma15313c92017-11-15 17:58:21 -080010594 mDischargeLightDozeCounter.reset(false);
10595 mDischargeDeepDozeCounter.reset(false);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010596 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010597 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010598
10599 public void resetAllStatsCmdLocked() {
10600 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -080010601 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010602 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -080010603 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010604 long realtime = mSecRealtime * 1000;
10605 mDischargeStartLevel = mHistoryCur.batteryLevel;
10606 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -070010607 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010608 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
10609 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010610 mOnBatteryTimeBase.reset(uptime, realtime);
10611 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
10612 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Mike Mac2f518a2017-09-19 16:06:03 -070010613 if (isScreenOn(mScreenState)) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010614 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
Mike Mac2f518a2017-09-19 16:06:03 -070010615 mDischargeScreenDozeUnplugLevel = 0;
10616 mDischargeScreenOffUnplugLevel = 0;
10617 } else if (isScreenDoze(mScreenState)) {
10618 mDischargeScreenOnUnplugLevel = 0;
10619 mDischargeScreenDozeUnplugLevel = mHistoryCur.batteryLevel;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010620 mDischargeScreenOffUnplugLevel = 0;
10621 } else {
10622 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010623 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010624 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
10625 }
10626 mDischargeAmountScreenOn = 0;
10627 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010628 mDischargeAmountScreenDoze = 0;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010629 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010630 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080010631 }
10632
10633 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -070010634 final long uptimeMillis = mClocks.uptimeMillis();
10635 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010636 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -070010637 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010638 mScreenOnTimer.reset(false);
Mike Mac2f518a2017-09-19 16:06:03 -070010639 mScreenDozeTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010640 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010641 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010642 }
Adam Lesinski1a76a622016-06-22 10:28:47 -070010643
10644 if (mPowerProfile != null) {
10645 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
10646 } else {
10647 mEstimatedBatteryCapacity = -1;
10648 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070010649 mMinLearnedBatteryCapacity = -1;
10650 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010651 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070010652 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -070010653 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -070010654 mLongestLightIdleTime = 0;
10655 mLongestFullIdleTime = 0;
10656 mDeviceIdleModeLightTimer.reset(false);
10657 mDeviceIdleModeFullTimer.reset(false);
10658 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070010659 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010660 mPhoneOnTimer.reset(false);
10661 mAudioOnTimer.reset(false);
10662 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070010663 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070010664 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010665 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -080010666 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010667 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010668 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010669 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010670 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010671 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010672 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010673 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080010674 mNetworkByteActivityCounters[i].reset(false);
10675 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070010676 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010677 mMobileRadioActiveTimer.reset(false);
10678 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010679 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080010680 mMobileRadioActiveUnknownTime.reset(false);
10681 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010682 mWifiOnTimer.reset(false);
10683 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010684 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010685 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080010686 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070010687 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
10688 mWifiSupplStateTimer[i].reset(false);
10689 }
10690 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
10691 mWifiSignalStrengthsTimer[i].reset(false);
10692 }
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080010693 mWifiMulticastWakelockTimer.reset(false);
Siddharth Rayb50a6842017-12-14 15:15:28 -080010694 mWifiActiveTimer.reset(false);
10695 mWifiActivity.reset(false);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080010696 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
10697 mGpsSignalQualityTimer[i].reset(false);
10698 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010699 mBluetoothActivity.reset(false);
10700 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080010701 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010702
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010703 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -070010704 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010705 mUidStats.remove(mUidStats.keyAt(i));
10706 i--;
10707 }
10708 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010709
Bookatz50df7112017-08-04 14:53:26 -070010710 if (mRpmStats.size() > 0) {
10711 for (SamplingTimer timer : mRpmStats.values()) {
10712 mOnBatteryTimeBase.remove(timer);
10713 }
10714 mRpmStats.clear();
10715 }
10716 if (mScreenOffRpmStats.size() > 0) {
10717 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
10718 mOnBatteryScreenOffTimeBase.remove(timer);
10719 }
10720 mScreenOffRpmStats.clear();
10721 }
10722
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010723 if (mKernelWakelockStats.size() > 0) {
10724 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080010725 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010726 }
10727 mKernelWakelockStats.clear();
10728 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010729
James Carr3a226052016-07-01 14:49:52 -070010730 if (mKernelMemoryStats.size() > 0) {
10731 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
10732 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
10733 }
10734 mKernelMemoryStats.clear();
10735 }
10736
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010737 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070010738 for (SamplingTimer timer : mWakeupReasonStats.values()) {
10739 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010740 }
10741 mWakeupReasonStats.clear();
10742 }
10743
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010744 mLastHistoryStepDetails = null;
10745 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
10746 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
10747 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
10748 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
10749 mLastStepStatUserTime = mCurStepStatUserTime = 0;
10750 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
10751 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
10752 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
10753 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
10754 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
10755
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010756 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010757
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010758 clearHistoryLocked();
10759 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010760
Dianne Hackborn40c87252014-03-19 16:55:40 -070010761 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010762 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010763 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
10764 // Not recording process starts/stops.
10765 continue;
10766 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010767 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010768 if (active == null) {
10769 continue;
10770 }
Dianne Hackborn37de0982014-05-09 09:32:18 -070010771 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
10772 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010773 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -070010774 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
10775 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010776 }
10777 }
10778 }
10779 }
10780
Mike Mac2f518a2017-09-19 16:06:03 -070010781 void updateDischargeScreenLevelsLocked(int oldState, int newState) {
10782 updateOldDischargeScreenLevelLocked(oldState);
10783 updateNewDischargeScreenLevelLocked(newState);
10784 }
10785
10786 private void updateOldDischargeScreenLevelLocked(int state) {
10787 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010788 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
10789 if (diff > 0) {
10790 mDischargeAmountScreenOn += diff;
10791 mDischargeAmountScreenOnSinceCharge += diff;
10792 }
Mike Mac2f518a2017-09-19 16:06:03 -070010793 } else if (isScreenDoze(state)) {
10794 int diff = mDischargeScreenDozeUnplugLevel - mDischargeCurrentLevel;
10795 if (diff > 0) {
10796 mDischargeAmountScreenDoze += diff;
10797 mDischargeAmountScreenDozeSinceCharge += diff;
10798 }
10799 } else if (isScreenOff(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010800 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
10801 if (diff > 0) {
10802 mDischargeAmountScreenOff += diff;
10803 mDischargeAmountScreenOffSinceCharge += diff;
10804 }
10805 }
Mike Mac2f518a2017-09-19 16:06:03 -070010806 }
10807
10808 private void updateNewDischargeScreenLevelLocked(int state) {
10809 if (isScreenOn(state)) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010810 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
10811 mDischargeScreenOffUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010812 mDischargeScreenDozeUnplugLevel = 0;
10813 } else if (isScreenDoze(state)){
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010814 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070010815 mDischargeScreenDozeUnplugLevel = mDischargeCurrentLevel;
10816 mDischargeScreenOffUnplugLevel = 0;
10817 } else if (isScreenOff(state)) {
10818 mDischargeScreenOnUnplugLevel = 0;
10819 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080010820 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
10821 }
10822 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010823
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010824 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010825 if (mOnBatteryInternal) {
Mike Mac2f518a2017-09-19 16:06:03 -070010826 updateDischargeScreenLevelsLocked(mScreenState, mScreenState);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080010827 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010828 }
10829
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010830 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
10831 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
10832
10833 private final Object mWifiNetworkLock = new Object();
10834
10835 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010836 private String[] mWifiIfaces = EmptyArray.STRING;
10837
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010838 @GuardedBy("mWifiNetworkLock")
10839 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010840
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010841 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010842
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010843 @GuardedBy("mModemNetworkLock")
10844 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010845
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010846 @GuardedBy("mModemNetworkLock")
10847 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
10848
10849 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
10850 try {
10851 if (!ArrayUtils.isEmpty(ifaces)) {
10852 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
10853 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
10854 }
10855 } catch (IOException e) {
10856 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010857 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010858 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010859 }
10860
10861 /**
10862 * Distribute WiFi energy info and network traffic to apps.
10863 * @param info The energy information from the WiFi controller.
10864 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010865 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010866 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010867 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010868 }
10869
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010870 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070010871 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010872 synchronized (mWifiNetworkLock) {
10873 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
10874 if (latestStats != null) {
10875 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
10876 mNetworkStatsPool.acquire());
10877 mNetworkStatsPool.release(mLastWifiNetworkStats);
10878 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070010879 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010880 }
10881
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010882 synchronized (this) {
10883 if (!mOnBatteryInternal) {
10884 if (delta != null) {
10885 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010886 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010887 return;
10888 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010889
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010890 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
10891 SparseLongArray rxPackets = new SparseLongArray();
10892 SparseLongArray txPackets = new SparseLongArray();
10893 long totalTxPackets = 0;
10894 long totalRxPackets = 0;
10895 if (delta != null) {
10896 NetworkStats.Entry entry = new NetworkStats.Entry();
10897 final int size = delta.size();
10898 for (int i = 0; i < size; i++) {
10899 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010900
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010901 if (DEBUG_ENERGY) {
10902 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
10903 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
10904 + " txPackets=" + entry.txPackets);
10905 }
10906
10907 if (entry.rxBytes == 0 && entry.txBytes == 0) {
10908 // Skip the lookup below since there is no work to do.
10909 continue;
10910 }
10911
10912 final Uid u = getUidStatsLocked(mapUid(entry.uid));
10913 if (entry.rxBytes != 0) {
10914 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080010915 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010916 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10917 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
10918 entry.rxPackets);
10919 }
10920 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
10921 entry.rxBytes);
10922 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
10923 entry.rxPackets);
10924
10925 rxPackets.put(u.getUid(), entry.rxPackets);
10926
10927 // Sum the total number of packets so that the Rx Power can
10928 // be evenly distributed amongst the apps.
10929 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080010930 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010931
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010932 if (entry.txBytes != 0) {
10933 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -080010934 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010935 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
10936 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
10937 entry.txPackets);
10938 }
10939 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
10940 entry.txBytes);
10941 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
10942 entry.txPackets);
10943
10944 txPackets.put(u.getUid(), entry.txPackets);
10945
10946 // Sum the total number of packets so that the Tx Power can
10947 // be evenly distributed amongst the apps.
10948 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -080010949 }
Adam Lesinskiba88e682015-12-08 12:06:55 -080010950 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010951 mNetworkStatsPool.release(delta);
10952 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -070010953 }
10954
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010955 if (info != null) {
10956 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -070010957
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010958 // Measured in mAms
10959 final long txTimeMs = info.getControllerTxTimeMillis();
10960 final long rxTimeMs = info.getControllerRxTimeMillis();
Siddharth Rayb50a6842017-12-14 15:15:28 -080010961 final long scanTimeMs = info.getControllerScanTimeMillis();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010962 final long idleTimeMs = info.getControllerIdleTimeMillis();
10963 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070010964
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010965 long leftOverRxTimeMs = rxTimeMs;
10966 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -070010967
Adam Lesinskie08af192015-03-25 16:42:59 -070010968 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010969 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
10970 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
10971 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
10972 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
10973 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Siddharth Rayb50a6842017-12-14 15:15:28 -080010974 Slog.d(TAG, " Scan Time: " + scanTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070010975 }
Adam Lesinskie08af192015-03-25 16:42:59 -070010976
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010977 long totalWifiLockTimeMs = 0;
10978 long totalScanTimeMs = 0;
10979
10980 // On the first pass, collect some totals so that we can normalize power
10981 // calculations if we need to.
10982 final int uidStatsSize = mUidStats.size();
10983 for (int i = 0; i < uidStatsSize; i++) {
10984 final Uid uid = mUidStats.valueAt(i);
10985
10986 // Sum the total scan power for all apps.
10987 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
10988 elapsedRealtimeMs * 1000) / 1000;
10989
10990 // Sum the total time holding wifi lock for all apps.
10991 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
10992 elapsedRealtimeMs * 1000) / 1000;
10993 }
10994
10995 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
10996 Slog.d(TAG,
10997 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
10998 + rxTimeMs + " ms). Normalizing scan time.");
10999 }
11000 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
11001 Slog.d(TAG,
11002 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
11003 + txTimeMs + " ms). Normalizing scan time.");
11004 }
11005
11006 // Actually assign and distribute power usage to apps.
11007 for (int i = 0; i < uidStatsSize; i++) {
11008 final Uid uid = mUidStats.valueAt(i);
11009
11010 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
11011 elapsedRealtimeMs * 1000) / 1000;
11012 if (scanTimeSinceMarkMs > 0) {
11013 // Set the new mark so that next time we get new data since this point.
11014 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
11015
11016 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
11017 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
11018
11019 // Our total scan time is more than the reported Tx/Rx time.
11020 // This is possible because the cost of a scan is approximate.
11021 // Let's normalize the result so that we evenly blame each app
11022 // scanning.
11023 //
11024 // This means that we may have apps that transmitted/received packets not be
11025 // blamed for this, but this is fine as scans are relatively more expensive.
11026 if (totalScanTimeMs > rxTimeMs) {
11027 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
11028 totalScanTimeMs;
11029 }
11030 if (totalScanTimeMs > txTimeMs) {
11031 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
11032 totalScanTimeMs;
11033 }
11034
11035 if (DEBUG_ENERGY) {
11036 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
11037 + scanRxTimeSinceMarkMs + " ms Tx:"
11038 + scanTxTimeSinceMarkMs + " ms)");
11039 }
11040
11041 ControllerActivityCounterImpl activityCounter =
11042 uid.getOrCreateWifiControllerActivityLocked();
11043 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
11044 activityCounter.getTxTimeCounters()[0].addCountLocked(
11045 scanTxTimeSinceMarkMs);
11046 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
11047 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
11048 }
11049
11050 // Distribute evenly the power consumed while Idle to each app holding a WiFi
11051 // lock.
11052 final long wifiLockTimeSinceMarkMs =
11053 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
11054 elapsedRealtimeMs * 1000) / 1000;
11055 if (wifiLockTimeSinceMarkMs > 0) {
11056 // Set the new mark so that next time we get new data since this point.
11057 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
11058
11059 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
11060 / totalWifiLockTimeMs;
11061 if (DEBUG_ENERGY) {
11062 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
11063 + myIdleTimeMs + " ms");
11064 }
11065 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
11066 .addCountLocked(myIdleTimeMs);
11067 }
11068 }
11069
Adam Lesinskie08af192015-03-25 16:42:59 -070011070 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011071 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
11072 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -070011073 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011074
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011075 // Distribute the remaining Tx power appropriately between all apps that transmitted
11076 // packets.
11077 for (int i = 0; i < txPackets.size(); i++) {
11078 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
11079 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
11080 / totalTxPackets;
11081 if (DEBUG_ENERGY) {
11082 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
11083 }
11084 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
11085 .addCountLocked(myTxTimeMs);
11086 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011087
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011088 // Distribute the remaining Rx power appropriately between all apps that received
11089 // packets.
11090 for (int i = 0; i < rxPackets.size(); i++) {
11091 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
11092 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
11093 / totalRxPackets;
11094 if (DEBUG_ENERGY) {
11095 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
11096 }
11097 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
11098 .addCountLocked(myRxTimeMs);
11099 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011100
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011101 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
11102
11103
11104 // Update WiFi controller stats.
11105 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
11106 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
11107 info.getControllerTxTimeMillis());
Siddharth Rayb50a6842017-12-14 15:15:28 -080011108 mWifiActivity.getScanTimeCounter().addCountLocked(
11109 info.getControllerScanTimeMillis());
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011110 mWifiActivity.getIdleTimeCounter().addCountLocked(
11111 info.getControllerIdleTimeMillis());
11112
11113 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11114 final double opVolt = mPowerProfile.getAveragePower(
11115 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11116 if (opVolt != 0) {
11117 // We store the power drain as mAms.
11118 mWifiActivity.getPowerCounter().addCountLocked(
11119 (long) (info.getControllerEnergyUsed() / opVolt));
11120 }
Adam Lesinskie08af192015-03-25 16:42:59 -070011121 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011122 }
11123 }
11124
11125 /**
11126 * Distribute Cell radio energy info and network traffic to apps.
11127 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011128 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011129 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011130 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011131 }
11132
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011133 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -070011134 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011135 synchronized (mModemNetworkLock) {
11136 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
11137 if (latestStats != null) {
11138 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
11139 mNetworkStatsPool.acquire());
11140 mNetworkStatsPool.release(mLastModemNetworkStats);
11141 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -070011142 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011143 }
11144
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011145 synchronized (this) {
11146 if (!mOnBatteryInternal) {
11147 if (delta != null) {
11148 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011149 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011150 return;
Adam Lesinskie08af192015-03-25 16:42:59 -070011151 }
11152
Siddharth Ray2038af82018-01-17 17:40:26 -080011153 if (activityInfo != null) {
11154 mHasModemReporting = true;
11155 mModemActivity.getIdleTimeCounter().addCountLocked(
11156 activityInfo.getIdleTimeMillis());
11157 mModemActivity.getRxTimeCounter().addCountLocked(activityInfo.getRxTimeMillis());
11158 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11159 mModemActivity.getTxTimeCounters()[lvl]
11160 .addCountLocked(activityInfo.getTxTimeMillis()[lvl]);
11161 }
11162
11163 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11164 final double opVolt = mPowerProfile.getAveragePower(
11165 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11166 if (opVolt != 0) {
11167 double energyUsed =
11168 activityInfo.getSleepTimeMillis() *
11169 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_SLEEP)
11170 + activityInfo.getIdleTimeMillis() *
11171 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_IDLE)
11172 + activityInfo.getRxTimeMillis() *
11173 mPowerProfile.getAveragePower(PowerProfile.POWER_MODEM_CONTROLLER_RX);
11174 int[] txCurrentMa = activityInfo.getTxTimeMillis();
11175 for (int i = 0; i < Math.min(txCurrentMa.length,
11176 SignalStrength.NUM_SIGNAL_STRENGTH_BINS); i++) {
11177 energyUsed += txCurrentMa[i] * mPowerProfile.getAveragePower(
11178 PowerProfile.POWER_MODEM_CONTROLLER_TX, i);
11179 }
11180
11181 // We store the power drain as mAms.
11182 mModemActivity.getPowerCounter().addCountLocked((long) energyUsed);
11183 }
11184 }
11185
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070011186 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011187 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
11188 elapsedRealtimeMs * 1000);
11189 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
11190
11191 long totalRxPackets = 0;
11192 long totalTxPackets = 0;
11193 if (delta != null) {
11194 NetworkStats.Entry entry = new NetworkStats.Entry();
11195 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011196 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011197 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011198 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11199 continue;
11200 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011201
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011202 if (DEBUG_ENERGY) {
11203 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
11204 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
11205 + " txPackets=" + entry.txPackets);
11206 }
11207
11208 totalRxPackets += entry.rxPackets;
11209 totalTxPackets += entry.txPackets;
11210
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011211 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011212 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
11213 entry.rxPackets);
11214 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
11215 entry.txPackets);
11216 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
11217 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
11218 entry.rxBytes, entry.rxPackets);
11219 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
11220 entry.txBytes, entry.txPackets);
11221 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011222
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011223 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11224 entry.rxBytes);
11225 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11226 entry.txBytes);
11227 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
11228 entry.rxPackets);
11229 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
11230 entry.txPackets);
11231 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011232
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011233 // Now distribute proportional blame to the apps that did networking.
11234 long totalPackets = totalRxPackets + totalTxPackets;
11235 if (totalPackets > 0) {
11236 for (int i = 0; i < size; i++) {
11237 entry = delta.getValues(i, entry);
11238 if (entry.rxPackets == 0 && entry.txPackets == 0) {
11239 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011240 }
11241
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011242 final Uid u = getUidStatsLocked(mapUid(entry.uid));
11243
11244 // Distribute total radio active time in to this app.
11245 final long appPackets = entry.rxPackets + entry.txPackets;
11246 final long appRadioTime = (radioTime * appPackets) / totalPackets;
11247 u.noteMobileRadioActiveTimeLocked(appRadioTime);
11248
11249 // Remove this app from the totals, so that we don't lose any time
11250 // due to rounding.
11251 radioTime -= appRadioTime;
11252 totalPackets -= appPackets;
11253
11254 if (activityInfo != null) {
11255 ControllerActivityCounterImpl activityCounter =
11256 u.getOrCreateModemControllerActivityLocked();
11257 if (totalRxPackets > 0 && entry.rxPackets > 0) {
11258 final long rxMs = (entry.rxPackets * activityInfo.getRxTimeMillis())
11259 / totalRxPackets;
11260 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
11261 }
11262
11263 if (totalTxPackets > 0 && entry.txPackets > 0) {
11264 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
11265 long txMs =
11266 entry.txPackets * activityInfo.getTxTimeMillis()[lvl];
11267 txMs /= totalTxPackets;
11268 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
11269 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011270 }
11271 }
11272 }
11273 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070011274
11275 if (radioTime > 0) {
11276 // Whoops, there is some radio time we can't blame on an app!
11277 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
11278 mMobileRadioActiveUnknownCount.addCountLocked(1);
11279 }
11280
11281 mNetworkStatsPool.release(delta);
11282 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011283 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011284 }
11285 }
11286
11287 /**
11288 * Distribute Bluetooth energy info and network traffic to apps.
11289 * @param info The energy information from the bluetooth controller.
11290 */
11291 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011292 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011293 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070011294 }
11295
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011296 if (info == null || !mOnBatteryInternal) {
11297 return;
11298 }
Adam Lesinskie283d332015-04-16 12:29:25 -070011299
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011300 mHasBluetoothReporting = true;
11301
Bookatz867c0d72017-03-07 18:23:42 -080011302 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011303 final long rxTimeMs = info.getControllerRxTimeMillis();
11304 final long txTimeMs = info.getControllerTxTimeMillis();
11305
11306 if (DEBUG_ENERGY) {
11307 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
11308 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
11309 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
11310 Slog.d(TAG, " Idle Time: " + info.getControllerIdleTimeMillis() + " ms");
11311 }
11312
11313 long totalScanTimeMs = 0;
11314
11315 final int uidCount = mUidStats.size();
11316 for (int i = 0; i < uidCount; i++) {
11317 final Uid u = mUidStats.valueAt(i);
11318 if (u.mBluetoothScanTimer == null) {
11319 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070011320 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011321
Bookatzaa4594a2017-03-24 12:39:56 -070011322 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011323 elapsedRealtimeMs * 1000) / 1000;
11324 }
11325
11326 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
11327 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
11328
11329 if (DEBUG_ENERGY) {
11330 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
11331 + " TX=" + normalizeScanTxTime);
11332 }
11333
11334 long leftOverRxTimeMs = rxTimeMs;
11335 long leftOverTxTimeMs = txTimeMs;
11336
11337 for (int i = 0; i < uidCount; i++) {
11338 final Uid u = mUidStats.valueAt(i);
11339 if (u.mBluetoothScanTimer == null) {
11340 continue;
11341 }
11342
Bookatzaa4594a2017-03-24 12:39:56 -070011343 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011344 elapsedRealtimeMs * 1000) / 1000;
11345 if (scanTimeSinceMarkMs > 0) {
11346 // Set the new mark so that next time we get new data since this point.
11347 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
11348
11349 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
11350 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
11351
11352 if (normalizeScanRxTime) {
11353 // Scan time is longer than the total rx time in the controller,
11354 // so distribute the scan time proportionately. This means regular traffic
11355 // will not blamed, but scans are more expensive anyways.
11356 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
11357 }
11358
11359 if (normalizeScanTxTime) {
11360 // Scan time is longer than the total tx time in the controller,
11361 // so distribute the scan time proportionately. This means regular traffic
11362 // will not blamed, but scans are more expensive anyways.
11363 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
11364 }
11365
11366 final ControllerActivityCounterImpl counter =
11367 u.getOrCreateBluetoothControllerActivityLocked();
11368 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
11369 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
11370
11371 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
11372 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
11373 }
11374 }
11375
11376 if (DEBUG_ENERGY) {
11377 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs
11378 + " TX=" + leftOverTxTimeMs);
11379 }
11380
11381 //
11382 // Now distribute blame to apps that did bluetooth traffic.
11383 //
11384
11385 long totalTxBytes = 0;
11386 long totalRxBytes = 0;
11387
11388 final UidTraffic[] uidTraffic = info.getUidTraffic();
11389 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
11390 for (int i = 0; i < numUids; i++) {
11391 final UidTraffic traffic = uidTraffic[i];
11392
11393 // Add to the global counters.
11394 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(
11395 traffic.getRxBytes());
11396 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(
11397 traffic.getTxBytes());
11398
11399 // Add to the UID counters.
11400 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
11401 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, traffic.getRxBytes(), 0);
11402 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, traffic.getTxBytes(), 0);
11403
11404 // Calculate the total traffic.
11405 totalTxBytes += traffic.getTxBytes();
11406 totalRxBytes += traffic.getRxBytes();
11407 }
11408
11409 if ((totalTxBytes != 0 || totalRxBytes != 0) &&
11410 (leftOverRxTimeMs != 0 || leftOverTxTimeMs != 0)) {
Adam Lesinski50e47602015-12-04 17:04:54 -080011411 for (int i = 0; i < numUids; i++) {
11412 final UidTraffic traffic = uidTraffic[i];
11413
Adam Lesinski50e47602015-12-04 17:04:54 -080011414 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011415 final ControllerActivityCounterImpl counter =
11416 u.getOrCreateBluetoothControllerActivityLocked();
11417
11418 if (totalRxBytes > 0 && traffic.getRxBytes() > 0) {
11419 final long timeRxMs = (leftOverRxTimeMs * traffic.getRxBytes()) / totalRxBytes;
11420
11421 if (DEBUG_ENERGY) {
11422 Slog.d(TAG, "UID=" + traffic.getUid() + " rx_bytes=" + traffic.getRxBytes()
11423 + " rx_time=" + timeRxMs);
11424 }
11425 counter.getRxTimeCounter().addCountLocked(timeRxMs);
11426 leftOverRxTimeMs -= timeRxMs;
11427 }
11428
11429 if (totalTxBytes > 0 && traffic.getTxBytes() > 0) {
11430 final long timeTxMs = (leftOverTxTimeMs * traffic.getTxBytes()) / totalTxBytes;
11431
11432 if (DEBUG_ENERGY) {
11433 Slog.d(TAG, "UID=" + traffic.getUid() + " tx_bytes=" + traffic.getTxBytes()
11434 + " tx_time=" + timeTxMs);
11435 }
11436
11437 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
11438 leftOverTxTimeMs -= timeTxMs;
11439 }
Adam Lesinski50e47602015-12-04 17:04:54 -080011440 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011441 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011442
11443 mBluetoothActivity.getRxTimeCounter().addCountLocked(
11444 info.getControllerRxTimeMillis());
11445 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(
11446 info.getControllerTxTimeMillis());
11447 mBluetoothActivity.getIdleTimeCounter().addCountLocked(
11448 info.getControllerIdleTimeMillis());
11449
11450 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
11451 final double opVolt = mPowerProfile.getAveragePower(
11452 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
11453 if (opVolt != 0) {
11454 // We store the power drain as mAms.
11455 mBluetoothActivity.getPowerCounter().addCountLocked(
11456 (long) (info.getControllerEnergyUsed() / opVolt));
11457 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011458 }
11459
11460 /**
Bookatz0b8a0502017-09-13 11:51:52 -070011461 * Read and record Resource Power Manager (RPM) state and voter times.
11462 * If RPM stats were fetched more recently than RPM_STATS_UPDATE_FREQ_MS ago, uses the old data
11463 * instead of fetching it anew.
Bookatz50df7112017-08-04 14:53:26 -070011464 */
11465 public void updateRpmStatsLocked() {
11466 if (mPlatformIdleStateCallback == null) return;
Bookatz0b8a0502017-09-13 11:51:52 -070011467 long now = SystemClock.elapsedRealtime();
11468 if (now - mLastRpmStatsUpdateTimeMs >= RPM_STATS_UPDATE_FREQ_MS) {
11469 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
11470 mLastRpmStatsUpdateTimeMs = now;
11471 }
Bookatz50df7112017-08-04 14:53:26 -070011472
11473 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
11474 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
11475
11476 // Update values for this platform state.
11477 final String pName = pstate.getKey();
11478 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
11479 final int pCount = pstate.getValue().mCount;
11480 getRpmTimerLocked(pName).update(pTimeUs, pCount);
Bookatz82b341172017-09-07 19:06:08 -070011481 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11482 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
11483 }
Bookatz50df7112017-08-04 14:53:26 -070011484
11485 // Update values for each voter of this platform state.
11486 for (Map.Entry<String, RpmStats.PowerStateElement> voter
11487 : pstate.getValue().mVoters.entrySet()) {
11488 final String vName = pName + "." + voter.getKey();
11489 final long vTimeUs = voter.getValue().mTimeMs * 1000;
11490 final int vCount = voter.getValue().mCount;
11491 getRpmTimerLocked(vName).update(vTimeUs, vCount);
Bookatz82b341172017-09-07 19:06:08 -070011492 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11493 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
11494 }
Bookatz50df7112017-08-04 14:53:26 -070011495 }
11496 }
11497
11498 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
11499 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
11500
11501 final String subsysName = subsys.getKey();
11502 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
11503 : subsys.getValue().mStates.entrySet()) {
11504 final String name = subsysName + "." + sstate.getKey();
11505 final long timeUs = sstate.getValue().mTimeMs * 1000;
11506 final int count = sstate.getValue().mCount;
11507 getRpmTimerLocked(name).update(timeUs, count);
Bookatz82b341172017-09-07 19:06:08 -070011508 if (SCREEN_OFF_RPM_STATS_ENABLED) {
11509 getScreenOffRpmTimerLocked(name).update(timeUs, count);
11510 }
Bookatz50df7112017-08-04 14:53:26 -070011511 }
11512 }
11513 }
11514
11515 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011516 * Read and distribute kernel wake lock use across apps.
11517 */
11518 public void updateKernelWakelocksLocked() {
11519 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
11520 mTmpWakelockStats);
11521 if (wakelockStats == null) {
11522 // Not crashing might make board bringup easier.
11523 Slog.w(TAG, "Couldn't get kernel wake lock stats");
11524 return;
11525 }
11526
11527 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
11528 String name = ent.getKey();
11529 KernelWakelockStats.Entry kws = ent.getValue();
11530
11531 SamplingTimer kwlt = mKernelWakelockStats.get(name);
11532 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011533 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011534 mKernelWakelockStats.put(name, kwlt);
11535 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070011536
Adam Lesinski757c6ea2016-04-21 09:55:41 -070011537 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011538 kwlt.setUpdateVersion(kws.mVersion);
11539 }
11540
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011541 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070011542 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
11543 // this time.
11544 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
11545 SamplingTimer st = ent.getValue();
11546 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
11547 st.endSample();
11548 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011549 }
11550 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011551
Adam Lesinskid84ad302016-05-17 18:31:02 -070011552 // Record whether we've seen a non-zero time (for debugging b/22716723).
11553 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070011554 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
11555 }
11556
11557 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
11558 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
11559 wakelockStats.kernelWakelockVersion);
11560 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070011561 }
11562
Adam Lesinski72478f02015-06-17 15:39:43 -070011563 // We use an anonymous class to access these variables,
11564 // so they can't live on the stack or they'd have to be
11565 // final MutableLong objects (more allocations).
11566 // Used in updateCpuTimeLocked().
11567 long mTempTotalCpuUserTimeUs;
11568 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011569 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011570
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011571 /**
James Carr3a226052016-07-01 14:49:52 -070011572 * Reads the newest memory stats from the kernel.
11573 */
11574 public void updateKernelMemoryBandwidthLocked() {
11575 mKernelMemoryBandwidthStats.updateStats();
11576 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
11577 final int bandwidthEntryCount = bandwidthEntries.size();
11578 int index;
11579 for (int i = 0; i < bandwidthEntryCount; i++) {
11580 SamplingTimer timer;
11581 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
11582 timer = mKernelMemoryStats.valueAt(index);
11583 } else {
11584 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
11585 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
11586 }
11587 timer.update(bandwidthEntries.valueAt(i), 1);
11588 if (DEBUG_MEMORY) {
11589 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
11590 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
11591 mKernelMemoryStats.get(
11592 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
11593 mKernelMemoryStats.size()));
11594 }
11595 }
11596 }
11597
11598 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070011599 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
11600 * and we are on battery with screen off, we give more of the cpu time to those apps holding
11601 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011602 */
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011603 public void updateCpuTimeLocked() {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070011604 if (mPowerProfile == null) {
11605 return;
11606 }
11607
Adam Lesinski72478f02015-06-17 15:39:43 -070011608 if (DEBUG_ENERGY_CPU) {
11609 Slog.d(TAG, "!Cpu updating!");
11610 }
11611
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011612 if (mCpuFreqs == null) {
11613 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
11614 }
11615
Sudheer Shanka38383232017-07-25 09:55:03 -070011616 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
11617 // usually holding the wakelock on behalf of an app.
11618 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
11619 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Adam Lesinski72478f02015-06-17 15:39:43 -070011620 if (mOnBatteryScreenOffTimeBase.isRunning()) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011621 partialTimersToConsider = new ArrayList<>();
11622 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011623 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011624 // Since the collection and blaming of wakelocks can be scheduled to run after
11625 // some delay, the mPartialTimers list may have new entries. We can't blame
11626 // the newly added timer for past cpu time, so we only consider timers that
11627 // were present for one round of collection. Once a timer has gone through
11628 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070011629 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070011630 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011631 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011632 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011633 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011634 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070011635
Sudheer Shanka38383232017-07-25 09:55:03 -070011636 // When the battery is not on, we don't attribute the cpu times to any timers but we still
11637 // need to take the snapshots.
11638 if (!mOnBatteryInternal) {
11639 mKernelUidCpuTimeReader.readDelta(null);
11640 mKernelUidCpuFreqTimeReader.readDelta(null);
Mike Mafae87da2018-01-19 20:07:20 -080011641 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11642 mKernelUidCpuActiveTimeReader.readDelta(null);
11643 mKernelUidCpuClusterTimeReader.readDelta(null);
11644 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011645 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
11646 mKernelCpuSpeedReaders[cluster].readDelta();
11647 }
11648 return;
11649 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011650
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011651 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011652 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
11653 ? null : new SparseLongArray();
Sudheer Shanka38383232017-07-25 09:55:03 -070011654 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011655 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
11656 // freqs, so no need to approximate these values.
11657 if (updatedUids != null) {
11658 updateClusterSpeedTimes(updatedUids);
Sudheer Shanka671985f2017-05-19 11:33:42 -070011659 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011660 readKernelUidCpuFreqTimesLocked(partialTimersToConsider);
Mike Mafae87da2018-01-19 20:07:20 -080011661 if (mConstants.TRACK_CPU_ACTIVE_CLUSTER_TIME) {
11662 readKernelUidCpuActiveTimesLocked();
11663 readKernelUidCpuClusterTimesLocked();
11664 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011665 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011666
Sudheer Shanka38383232017-07-25 09:55:03 -070011667 /**
11668 * Mark the current partial timers as gone through a collection so that they will be
11669 * considered in the next cpu times distribution to wakelock holders.
11670 */
11671 @VisibleForTesting
11672 public void markPartialTimersAsEligible() {
11673 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
11674 // No difference, so each timer is now considered for the next collection.
11675 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
11676 mPartialTimers.get(i).mInList = true;
11677 }
11678 } else {
11679 // The lists are different, meaning we added (or removed a timer) since the last
11680 // collection.
11681 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
11682 mLastPartialTimers.get(i).mInList = false;
11683 }
11684 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070011685
Sudheer Shanka38383232017-07-25 09:55:03 -070011686 // Mark the current timers as gone through a collection.
11687 final int numPartialTimers = mPartialTimers.size();
11688 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070011689 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070011690 timer.mInList = true;
11691 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070011692 }
11693 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011694 }
Adam Lesinski72478f02015-06-17 15:39:43 -070011695
Sudheer Shanka38383232017-07-25 09:55:03 -070011696 /**
11697 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
11698 * calculate cpu times spent by each uid at different frequencies.
11699 *
11700 * @param updatedUids The uids for which times spent at different frequencies are calculated.
11701 */
11702 @VisibleForTesting
11703 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011704 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011705 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070011706 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011707 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011708 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
11709 if (clusterSpeedTimesMs[cluster] != null) {
11710 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
11711 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011712 }
11713 }
11714 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011715 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011716 // We have cpu times per freq aggregated over all uids but we need the times per uid.
11717 // So, we distribute total time spent by an uid to different cpu freqs based on the
11718 // amount of time cpu was running at that freq.
11719 final int updatedUidsCount = updatedUids.size();
11720 for (int i = 0; i < updatedUidsCount; ++i) {
11721 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070011722 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011723 // Add the cpu speeds to this UID.
11724 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070011725 if (u.mCpuClusterSpeedTimesUs == null ||
11726 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011727 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011728 }
11729
Sudheer Shankaaf857412017-07-21 00:14:24 -070011730 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
11731 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
11732 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
11733 u.mCpuClusterSpeedTimesUs[cluster].length) {
11734 u.mCpuClusterSpeedTimesUs[cluster]
11735 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011736 }
11737
Sudheer Shankaaf857412017-07-21 00:14:24 -070011738 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011739 for (int speed = 0; speed < speedsInCluster; speed++) {
11740 if (cpuSpeeds[speed] == null) {
11741 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11742 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070011743 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
11744 * clusterSpeedTimesMs[cluster][speed]
11745 / totalCpuClustersTimeMs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011746 }
11747 }
11748 }
11749 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011750 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070011751
Sudheer Shanka38383232017-07-25 09:55:03 -070011752 /**
11753 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
11754 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
11755 * wakelock holders.
11756 *
11757 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
11758 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
11759 */
11760 @VisibleForTesting
11761 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
11762 @Nullable SparseLongArray updatedUids) {
11763 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
11764 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11765 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070011766
Sudheer Shanka38383232017-07-25 09:55:03 -070011767 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
11768 uid = mapUid(uid);
11769 if (Process.isIsolated(uid)) {
11770 // This could happen if the isolated uid mapping was removed before that process
11771 // was actually killed.
11772 mKernelUidCpuTimeReader.removeUid(uid);
11773 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
11774 return;
11775 }
11776 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11777 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
11778 mKernelUidCpuTimeReader.removeUid(uid);
11779 return;
11780 }
11781 final Uid u = getUidStatsLocked(uid);
11782
11783 // Accumulate the total system and user time.
11784 mTempTotalCpuUserTimeUs += userTimeUs;
11785 mTempTotalCpuSystemTimeUs += systemTimeUs;
11786
11787 StringBuilder sb = null;
11788 if (DEBUG_ENERGY_CPU) {
11789 sb = new StringBuilder();
11790 sb.append(" got time for uid=").append(u.mUid).append(": u=");
11791 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11792 sb.append(" s=");
11793 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11794 sb.append("\n");
11795 }
11796
11797 if (numWakelocks > 0) {
11798 // We have wakelocks being held, so only give a portion of the
11799 // time to the process. The rest will be distributed among wakelock
11800 // holders.
11801 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
11802 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
11803 }
11804
11805 if (sb != null) {
11806 sb.append(" adding to uid=").append(u.mUid).append(": u=");
11807 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11808 sb.append(" s=");
11809 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11810 Slog.d(TAG, sb.toString());
11811 }
11812
11813 u.mUserCpuTime.addCountLocked(userTimeUs);
11814 u.mSystemCpuTime.addCountLocked(systemTimeUs);
11815 if (updatedUids != null) {
11816 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
11817 }
11818 });
11819
11820 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11821 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11822 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
11823 }
11824
11825 if (numWakelocks > 0) {
11826 // Distribute a portion of the total cpu time to wakelock holders.
11827 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11828 mTempTotalCpuSystemTimeUs =
11829 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
11830
11831 for (int i = 0; i < numWakelocks; ++i) {
11832 final StopwatchTimer timer = partialTimers.get(i);
11833 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
11834 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
11835
11836 if (DEBUG_ENERGY_CPU) {
11837 final StringBuilder sb = new StringBuilder();
11838 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
11839 .append(": u=");
11840 TimeUtils.formatDuration(userTimeUs / 1000, sb);
11841 sb.append(" s=");
11842 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
11843 Slog.d(TAG, sb.toString());
11844 }
11845
11846 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs);
11847 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs);
11848 if (updatedUids != null) {
11849 final int uid = timer.mUid.getUid();
11850 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
11851 }
11852
11853 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
11854 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000);
11855
11856 mTempTotalCpuUserTimeUs -= userTimeUs;
11857 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070011858 }
11859 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011860 }
11861
Sudheer Shanka38383232017-07-25 09:55:03 -070011862 /**
11863 * Take a snapshot of the cpu times spent by each uid in each freq and update the
11864 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011865 *
11866 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070011867 */
11868 @VisibleForTesting
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011869 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers) {
11870 final boolean perClusterTimesAvailable =
11871 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
11872 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
11873 final int numClusters = mPowerProfile.getNumCpuClusters();
11874 mWakeLockAllocationsUs = null;
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080011875 final long startTimeMs = mClocks.uptimeMillis();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011876 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
11877 uid = mapUid(uid);
11878 if (Process.isIsolated(uid)) {
11879 mKernelUidCpuFreqTimeReader.removeUid(uid);
11880 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
11881 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070011882 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011883 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11884 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
11885 mKernelUidCpuFreqTimeReader.removeUid(uid);
11886 return;
11887 }
11888 final Uid u = getUidStatsLocked(uid);
11889 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
11890 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
11891 }
11892 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
11893 if (u.mScreenOffCpuFreqTimeMs == null ||
11894 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
11895 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
11896 mOnBatteryScreenOffTimeBase);
11897 }
11898 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011899
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011900 if (perClusterTimesAvailable) {
11901 if (u.mCpuClusterSpeedTimesUs == null ||
11902 u.mCpuClusterSpeedTimesUs.length != numClusters) {
11903 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070011904 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011905 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
11906 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070011907 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011908
11909 int freqIndex = 0;
11910 for (int cluster = 0; cluster < numClusters; ++cluster) {
11911 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
11912 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
11913 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
11914 u.mCpuClusterSpeedTimesUs[cluster]
11915 = new LongSamplingCounter[speedsInCluster];
11916 }
11917 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
11918 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
11919 }
11920 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
11921 for (int speed = 0; speed < speedsInCluster; ++speed) {
11922 if (cpuTimesUs[speed] == null) {
11923 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11924 }
11925 final long appAllocationUs;
11926 if (mWakeLockAllocationsUs != null) {
11927 appAllocationUs =
11928 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
11929 mWakeLockAllocationsUs[cluster][speed] +=
11930 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
11931 } else {
11932 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
11933 }
11934 cpuTimesUs[speed].addCountLocked(appAllocationUs);
11935 freqIndex++;
11936 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011937 }
Sudheer Shanka38383232017-07-25 09:55:03 -070011938 }
11939 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011940
Sudheer Shankaac5b88f2017-12-11 15:36:35 -080011941 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
11942 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
11943 Slog.d(TAG, "Reading cpu freq times took " + elapsedTimeMs + "ms");
11944 }
11945
Sudheer Shankab8ad5942017-08-08 12:16:09 -070011946 if (mWakeLockAllocationsUs != null) {
11947 for (int i = 0; i < numWakelocks; ++i) {
11948 final Uid u = partialTimers.get(i).mUid;
11949 if (u.mCpuClusterSpeedTimesUs == null ||
11950 u.mCpuClusterSpeedTimesUs.length != numClusters) {
11951 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
11952 }
11953
11954 for (int cluster = 0; cluster < numClusters; ++cluster) {
11955 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
11956 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
11957 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
11958 u.mCpuClusterSpeedTimesUs[cluster]
11959 = new LongSamplingCounter[speedsInCluster];
11960 }
11961 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
11962 for (int speed = 0; speed < speedsInCluster; ++speed) {
11963 if (cpuTimeUs[speed] == null) {
11964 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
11965 }
11966 final long allocationUs =
11967 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
11968 cpuTimeUs[speed].addCountLocked(allocationUs);
11969 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
11970 }
11971 }
11972 }
11973 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011974 }
11975
Mike Ma3d422c32017-10-25 11:08:57 -070011976 /**
11977 * Take a snapshot of the cpu active times spent by each uid and update the corresponding
11978 * counters.
11979 */
11980 @VisibleForTesting
11981 public void readKernelUidCpuActiveTimesLocked() {
11982 final long startTimeMs = mClocks.uptimeMillis();
11983 mKernelUidCpuActiveTimeReader.readDelta((uid, cpuActiveTimesUs) -> {
11984 uid = mapUid(uid);
11985 if (Process.isIsolated(uid)) {
11986 mKernelUidCpuActiveTimeReader.removeUid(uid);
11987 Slog.w(TAG, "Got active times for an isolated uid with no mapping: " + uid);
11988 return;
11989 }
11990 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
11991 Slog.w(TAG, "Got active times for an invalid user's uid " + uid);
11992 mKernelUidCpuActiveTimeReader.removeUid(uid);
11993 return;
11994 }
11995 final Uid u = getUidStatsLocked(uid);
11996 u.mCpuActiveTimeMs.addCountLocked(cpuActiveTimesUs);
11997 });
11998
11999 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12000 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12001 Slog.d(TAG, "Reading cpu active times took " + elapsedTimeMs + "ms");
12002 }
12003 }
12004
12005 /**
12006 * Take a snapshot of the cpu cluster times spent by each uid and update the corresponding
12007 * counters.
12008 */
12009 @VisibleForTesting
12010 public void readKernelUidCpuClusterTimesLocked() {
12011 final long startTimeMs = mClocks.uptimeMillis();
12012 mKernelUidCpuClusterTimeReader.readDelta((uid, cpuClusterTimesUs) -> {
12013 uid = mapUid(uid);
12014 if (Process.isIsolated(uid)) {
12015 mKernelUidCpuClusterTimeReader.removeUid(uid);
12016 Slog.w(TAG, "Got cluster times for an isolated uid with no mapping: " + uid);
12017 return;
12018 }
12019 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
12020 Slog.w(TAG, "Got cluster times for an invalid user's uid " + uid);
12021 mKernelUidCpuClusterTimeReader.removeUid(uid);
12022 return;
12023 }
12024 final Uid u = getUidStatsLocked(uid);
12025 u.mCpuClusterTimesMs.addCountLocked(cpuClusterTimesUs);
12026 });
12027
12028 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
12029 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
12030 Slog.d(TAG, "Reading cpu cluster times took " + elapsedTimeMs + "ms");
12031 }
12032 }
12033
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012034 boolean setChargingLocked(boolean charging) {
12035 if (mCharging != charging) {
12036 mCharging = charging;
12037 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012038 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012039 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012040 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012041 }
12042 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
12043 return true;
12044 }
12045 return false;
12046 }
12047
Mike Mac2f518a2017-09-19 16:06:03 -070012048 protected void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime,
12049 final boolean onBattery, final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012050 boolean doWrite = false;
12051 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
12052 m.arg1 = onBattery ? 1 : 0;
12053 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012054
Dianne Hackborn40c87252014-03-19 16:55:40 -070012055 final long uptime = mSecUptime * 1000;
12056 final long realtime = mSecRealtime * 1000;
Mike Mac2f518a2017-09-19 16:06:03 -070012057 final int screenState = mScreenState;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012058 if (onBattery) {
12059 // We will reset our status if we are unplugging after the
12060 // battery was last full, or the level is at 100, or
12061 // we have gone through a significant charge (from a very low
12062 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012063 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070012064 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012065 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012066 || (mDischargeCurrentLevel < 20 && level >= 80)
12067 || (getHighDischargeAmountSinceCharge() >= 200
12068 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012069 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070012070 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070012071 + " lowAmount=" + getLowDischargeAmountSinceCharge()
12072 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012073 // Before we write, collect a snapshot of the final aggregated
12074 // stats to be reported in the next checkin. Only do this if we have
12075 // a sufficient amount of data to make it interesting.
12076 if (getLowDischargeAmountSinceCharge() >= 20) {
12077 final Parcel parcel = Parcel.obtain();
12078 writeSummaryToParcel(parcel, true);
12079 BackgroundThread.getHandler().post(new Runnable() {
12080 @Override public void run() {
12081 synchronized (mCheckinFile) {
12082 FileOutputStream stream = null;
12083 try {
12084 stream = mCheckinFile.startWrite();
12085 stream.write(parcel.marshall());
12086 stream.flush();
12087 FileUtils.sync(stream);
12088 stream.close();
12089 mCheckinFile.finishWrite(stream);
12090 } catch (IOException e) {
12091 Slog.w("BatteryStats",
12092 "Error writing checkin battery statistics", e);
12093 mCheckinFile.failWrite(stream);
12094 } finally {
12095 parcel.recycle();
12096 }
12097 }
12098 }
12099 });
12100 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012101 doWrite = true;
12102 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080012103 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012104 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080012105 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012106 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012107 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080012108 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012109 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012110 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012111 if (mCharging) {
12112 setChargingLocked(false);
12113 }
12114 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012115 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012116 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012117 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012118 mDischargeStepTracker.clearTime();
12119 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012120 mInitStepMode = mCurStepMode;
12121 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012122 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012123 mHistoryCur.batteryLevel = (byte)level;
12124 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12125 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
12126 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012127 if (reset) {
12128 mRecordingHistory = true;
12129 startRecordingHistory(mSecRealtime, mSecUptime, reset);
12130 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012131 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012132 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012133 if (isScreenOn(screenState)) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012134 mDischargeScreenOnUnplugLevel = level;
Mike Mac2f518a2017-09-19 16:06:03 -070012135 mDischargeScreenDozeUnplugLevel = 0;
12136 mDischargeScreenOffUnplugLevel = 0;
12137 } else if (isScreenDoze(screenState)) {
12138 mDischargeScreenOnUnplugLevel = 0;
12139 mDischargeScreenDozeUnplugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012140 mDischargeScreenOffUnplugLevel = 0;
12141 } else {
12142 mDischargeScreenOnUnplugLevel = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012143 mDischargeScreenDozeUnplugLevel = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012144 mDischargeScreenOffUnplugLevel = level;
12145 }
12146 mDischargeAmountScreenOn = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012147 mDischargeAmountScreenDoze = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012148 mDischargeAmountScreenOff = 0;
Mike Mac2f518a2017-09-19 16:06:03 -070012149 updateTimeBasesLocked(true, screenState, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012150 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012151 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080012152 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012153 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012154 mHistoryCur.batteryLevel = (byte)level;
12155 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
12156 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
12157 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070012158 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012159 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012160 if (level < mDischargeUnplugLevel) {
12161 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
12162 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
12163 }
Mike Mac2f518a2017-09-19 16:06:03 -070012164 updateDischargeScreenLevelsLocked(screenState, screenState);
12165 updateTimeBasesLocked(false, screenState, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012166 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012167 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070012168 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012169 mInitStepMode = mCurStepMode;
12170 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080012171 }
12172 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
12173 if (mFile != null) {
12174 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012175 }
12176 }
12177 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012178
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012179 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
12180 boolean reset) {
12181 mRecordingHistory = true;
12182 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn37de0982014-05-09 09:32:18 -070012183 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs,
12184 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012185 mHistoryCur);
12186 mHistoryCur.currentTime = 0;
12187 if (reset) {
12188 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
12189 }
12190 }
12191
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012192 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
12193 final long uptimeMs) {
12194 if (mRecordingHistory) {
12195 mHistoryCur.currentTime = currentTime;
12196 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_CURRENT_TIME,
12197 mHistoryCur);
12198 mHistoryCur.currentTime = 0;
12199 }
12200 }
12201
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012202 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
12203 if (mRecordingHistory) {
12204 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080012205 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_SHUTDOWN,
12206 mHistoryCur);
12207 mHistoryCur.currentTime = 0;
12208 }
12209 }
12210
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012211 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012212 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012213 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070012214 }
12215 }
12216
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012217 // This should probably be exposed in the API, though it's not critical
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012218 public static final int BATTERY_PLUGGED_NONE = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012219
Bookatz8c6571b2017-10-24 15:04:41 -070012220 public void setBatteryStateLocked(final int status, final int health, final int plugType,
12221 final int level, /* not final */ int temp, final int volt, final int chargeUAh,
12222 final int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070012223 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
12224 temp = Math.max(0, temp);
12225
Bookatz8c6571b2017-10-24 15:04:41 -070012226 reportChangesToStatsLog(mHaveBatteryLevel ? mHistoryCur : null,
12227 status, plugType, level, temp);
12228
Todd Poynor1acf06a2017-12-07 19:19:35 -080012229 final boolean onBattery =
12230 plugType == BATTERY_PLUGGED_NONE &&
12231 status != BatteryManager.BATTERY_STATUS_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080012232 final long uptime = mClocks.uptimeMillis();
12233 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012234 if (!mHaveBatteryLevel) {
12235 mHaveBatteryLevel = true;
12236 // We start out assuming that the device is plugged in (not
12237 // on battery). If our first report is now that we are indeed
12238 // plugged in, then twiddle our state to correctly reflect that
12239 // since we won't be going through the full setOnBattery().
12240 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012241 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012242 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012243 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012244 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012245 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012246 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012247 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012248 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012249 mHistoryCur.batteryStatus = (byte)status;
12250 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012251 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012252 mMaxChargeStepLevel = mMinDischargeStepLevel =
12253 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012254 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012255 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
12256 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
12257 }
12258 int oldStatus = mHistoryCur.batteryStatus;
12259 if (onBattery) {
12260 mDischargeCurrentLevel = level;
12261 if (!mRecordingHistory) {
12262 mRecordingHistory = true;
12263 startRecordingHistory(elapsedRealtime, uptime, true);
12264 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012265 } else if (level < 96 &&
12266 status != BatteryManager.BATTERY_STATUS_UNKNOWN) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012267 if (!mRecordingHistory) {
12268 mRecordingHistory = true;
12269 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012270 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070012271 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012272 mCurrentBatteryLevel = level;
12273 if (mDischargePlugLevel < 0) {
12274 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070012275 }
Adam Lesinski926969b2016-04-28 17:31:12 -070012276
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012277 if (onBattery != mOnBattery) {
12278 mHistoryCur.batteryLevel = (byte)level;
12279 mHistoryCur.batteryStatus = (byte)status;
12280 mHistoryCur.batteryHealth = (byte)health;
12281 mHistoryCur.batteryPlugType = (byte)plugType;
12282 mHistoryCur.batteryTemperature = (short)temp;
12283 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012284 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12285 // Only record discharges
12286 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12287 mDischargeCounter.addCountLocked(chargeDiff);
12288 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012289 if (isScreenDoze(mScreenState)) {
12290 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12291 }
Mike Ma15313c92017-11-15 17:58:21 -080012292 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12293 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12294 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12295 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12296 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012297 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012298 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012299 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012300 } else {
12301 boolean changed = false;
12302 if (mHistoryCur.batteryLevel != level) {
12303 mHistoryCur.batteryLevel = (byte)level;
12304 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070012305
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012306 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
12307 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012308 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070012309 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012310 if (mHistoryCur.batteryStatus != status) {
12311 mHistoryCur.batteryStatus = (byte)status;
12312 changed = true;
12313 }
12314 if (mHistoryCur.batteryHealth != health) {
12315 mHistoryCur.batteryHealth = (byte)health;
12316 changed = true;
12317 }
12318 if (mHistoryCur.batteryPlugType != plugType) {
12319 mHistoryCur.batteryPlugType = (byte)plugType;
12320 changed = true;
12321 }
12322 if (temp >= (mHistoryCur.batteryTemperature+10)
12323 || temp <= (mHistoryCur.batteryTemperature-10)) {
12324 mHistoryCur.batteryTemperature = (short)temp;
12325 changed = true;
12326 }
12327 if (volt > (mHistoryCur.batteryVoltage+20)
12328 || volt < (mHistoryCur.batteryVoltage-20)) {
12329 mHistoryCur.batteryVoltage = (char)volt;
12330 changed = true;
12331 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012332 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
12333 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012334 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
12335 // Only record discharges
12336 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
12337 mDischargeCounter.addCountLocked(chargeDiff);
12338 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
Mike Mac2f518a2017-09-19 16:06:03 -070012339 if (isScreenDoze(mScreenState)) {
12340 mDischargeScreenDozeCounter.addCountLocked(chargeDiff);
12341 }
Mike Ma15313c92017-11-15 17:58:21 -080012342 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
12343 mDischargeLightDozeCounter.addCountLocked(chargeDiff);
12344 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
12345 mDischargeDeepDozeCounter.addCountLocked(chargeDiff);
12346 }
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012347 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070012348 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070012349 changed = true;
12350 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012351 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
12352 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
12353 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
12354 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012355 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012356 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
12357 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12358 modeBits, elapsedRealtime);
12359 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
12360 modeBits, elapsedRealtime);
12361 mLastDischargeStepLevel = level;
12362 mMinDischargeStepLevel = level;
12363 mInitStepMode = mCurStepMode;
12364 mModStepMode = 0;
12365 }
12366 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012367 if (level >= 90) {
12368 // If the battery level is at least 90%, always consider the device to be
12369 // charging even if it happens to go down a level.
12370 changed |= setChargingLocked(true);
12371 mLastChargeStepLevel = level;
12372 } if (!mCharging) {
12373 if (mLastChargeStepLevel < level) {
12374 // We have not reporting that we are charging, but the level has now
12375 // gone up, so consider the state to be charging.
12376 changed |= setChargingLocked(true);
12377 mLastChargeStepLevel = level;
12378 }
12379 } else {
12380 if (mLastChargeStepLevel > level) {
12381 // We had reported that the device was charging, but here we are with
12382 // power connected and the level going down. Looks like the current
12383 // power supplied isn't enough, so consider the device to now be
12384 // discharging.
12385 changed |= setChargingLocked(false);
12386 mLastChargeStepLevel = level;
12387 }
12388 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012389 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
12390 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12391 modeBits, elapsedRealtime);
12392 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
12393 modeBits, elapsedRealtime);
12394 mLastChargeStepLevel = level;
12395 mMaxChargeStepLevel = level;
12396 mInitStepMode = mCurStepMode;
12397 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070012398 }
12399 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070012400 if (changed) {
12401 addHistoryRecordLocked(elapsedRealtime, uptime);
12402 }
Evan Millarc64edde2009-04-18 12:26:32 -070012403 }
Todd Poynor1acf06a2017-12-07 19:19:35 -080012404 if (!onBattery &&
12405 (status == BatteryManager.BATTERY_STATUS_FULL ||
12406 status == BatteryManager.BATTERY_STATUS_UNKNOWN)) {
12407 // We don't record history while we are plugged in and fully charged
12408 // (or when battery is not present). The next time we are
12409 // unplugged, history will be cleared.
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070012410 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080012411 }
Adam Lesinski041d9172016-12-12 12:03:56 -080012412
Jocelyn Dangc627d102017-04-14 13:15:14 -070012413 if (mMinLearnedBatteryCapacity == -1) {
12414 mMinLearnedBatteryCapacity = chargeFullUAh;
12415 } else {
12416 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080012417 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070012418 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070012419 }
12420
Bookatz8c6571b2017-10-24 15:04:41 -070012421 // Inform StatsLog of setBatteryState changes.
12422 // If this is the first reporting, pass in recentPast == null.
12423 private void reportChangesToStatsLog(HistoryItem recentPast,
12424 final int status, final int plugType, final int level, final int temp) {
12425
12426 if (recentPast == null || recentPast.batteryStatus != status) {
12427 StatsLog.write(StatsLog.CHARGING_STATE_CHANGED, status);
12428 }
12429 if (recentPast == null || recentPast.batteryPlugType != plugType) {
12430 StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, plugType);
12431 }
12432 if (recentPast == null || recentPast.batteryLevel != level) {
12433 StatsLog.write(StatsLog.BATTERY_LEVEL_CHANGED, level);
12434 }
12435 // Let's just always print the temperature, regardless of whether it changed.
12436 StatsLog.write(StatsLog.DEVICE_TEMPERATURE_REPORTED, temp);
12437 }
12438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439 public long getAwakeTimeBattery() {
12440 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
12441 }
12442
12443 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080012444 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445 }
12446
12447 @Override
12448 public long computeUptime(long curTime, int which) {
12449 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012450 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012451 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012452 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012453 }
12454 return 0;
12455 }
12456
12457 @Override
12458 public long computeRealtime(long curTime, int which) {
12459 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012460 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012461 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070012462 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012463 }
12464 return 0;
12465 }
12466
12467 @Override
12468 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012469 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012470 }
12471
12472 @Override
12473 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012474 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012475 }
12476
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012477 @Override
12478 public long computeBatteryScreenOffUptime(long curTime, int which) {
12479 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
12480 }
12481
12482 @Override
12483 public long computeBatteryScreenOffRealtime(long curTime, int which) {
12484 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012485 }
12486
Dianne Hackborn260c5022014-04-29 11:23:16 -070012487 private long computeTimePerLevel(long[] steps, int numSteps) {
12488 // For now we'll do a simple average across all steps.
12489 if (numSteps <= 0) {
12490 return -1;
12491 }
12492 long total = 0;
12493 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012494 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012495 }
12496 return total / numSteps;
12497 /*
12498 long[] buckets = new long[numSteps];
12499 int numBuckets = 0;
12500 int numToAverage = 4;
12501 int i = 0;
12502 while (i < numSteps) {
12503 long totalTime = 0;
12504 int num = 0;
12505 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012506 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012507 num++;
12508 }
12509 buckets[numBuckets] = totalTime / num;
12510 numBuckets++;
12511 numToAverage *= 2;
12512 i += num;
12513 }
12514 if (numBuckets < 1) {
12515 return -1;
12516 }
12517 long averageTime = buckets[numBuckets-1];
12518 for (i=numBuckets-2; i>=0; i--) {
12519 averageTime = (averageTime + buckets[i]) / 2;
12520 }
12521 return averageTime;
12522 */
12523 }
12524
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012525 @Override
12526 public long computeBatteryTimeRemaining(long curTime) {
12527 if (!mOnBattery) {
12528 return -1;
12529 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012530 /* Simple implementation just looks at the average discharge per level across the
12531 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012532 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
12533 if (discharge < 2) {
12534 return -1;
12535 }
12536 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
12537 if (duration < 1000*1000) {
12538 return -1;
12539 }
12540 long usPerLevel = duration/discharge;
12541 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070012542 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012543 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012544 return -1;
12545 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012546 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012547 if (msPerLevel <= 0) {
12548 return -1;
12549 }
12550 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012551 }
12552
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012553 @Override
12554 public LevelStepTracker getDischargeLevelStepTracker() {
12555 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012556 }
12557
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012558 @Override
12559 public LevelStepTracker getDailyDischargeLevelStepTracker() {
12560 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012561 }
12562
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012563 @Override
12564 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012565 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012566 // Not yet working.
12567 return -1;
12568 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070012569 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012570 int curLevel = mCurrentBatteryLevel;
12571 int plugLevel = mDischargePlugLevel;
12572 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
12573 return -1;
12574 }
12575 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
12576 if (duration < 1000*1000) {
12577 return -1;
12578 }
12579 long usPerLevel = duration/(curLevel-plugLevel);
12580 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070012581 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012582 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070012583 return -1;
12584 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012585 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070012586 if (msPerLevel <= 0) {
12587 return -1;
12588 }
12589 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012590 }
12591
Siddharth Raya1fd0572017-11-13 14:20:47 -080012592 /*@hide */
12593 public CellularBatteryStats getCellularBatteryStats() {
12594 CellularBatteryStats s = new CellularBatteryStats();
12595 final int which = STATS_SINCE_CHARGED;
12596 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12597 final ControllerActivityCounter counter = getModemControllerActivity();
12598 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12599 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12600 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12601 long[] timeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES];
12602 for (int i = 0; i < timeInRatMs.length; i++) {
12603 timeInRatMs[i] = getPhoneDataConnectionTime(i, rawRealTime, which) / 1000;
12604 }
12605 long[] timeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
12606 for (int i = 0; i < timeInRxSignalStrengthLevelMs.length; i++) {
12607 timeInRxSignalStrengthLevelMs[i]
12608 = getPhoneSignalStrengthTime(i, rawRealTime, which) / 1000;
12609 }
12610 long[] txTimeMs = new long[Math.min(ModemActivityInfo.TX_POWER_LEVELS,
12611 counter.getTxTimeCounters().length)];
12612 long totalTxTimeMs = 0;
12613 for (int i = 0; i < txTimeMs.length; i++) {
12614 txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which);
12615 totalTxTimeMs += txTimeMs[i];
12616 }
12617 final long totalControllerActivityTimeMs
12618 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12619 final long sleepTimeMs
12620 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + totalTxTimeMs);
12621 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12622 s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000);
12623 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which));
12624 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which));
12625 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which));
12626 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which));
12627 s.setSleepTimeMs(sleepTimeMs);
12628 s.setIdleTimeMs(idleTimeMs);
12629 s.setRxTimeMs(rxTimeMs);
12630 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12631 s.setTimeInRatMs(timeInRatMs);
12632 s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs);
12633 s.setTxTimeMs(txTimeMs);
12634 return s;
12635 }
12636
Siddharth Rayb50a6842017-12-14 15:15:28 -080012637 /*@hide */
12638 public WifiBatteryStats getWifiBatteryStats() {
12639 WifiBatteryStats s = new WifiBatteryStats();
12640 final int which = STATS_SINCE_CHARGED;
12641 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12642 final ControllerActivityCounter counter = getWifiControllerActivity();
12643 final long idleTimeMs = counter.getIdleTimeCounter().getCountLocked(which);
12644 final long scanTimeMs = counter.getScanTimeCounter().getCountLocked(which);
12645 final long rxTimeMs = counter.getRxTimeCounter().getCountLocked(which);
12646 final long txTimeMs = counter.getTxTimeCounters()[0].getCountLocked(which);
12647 final long totalControllerActivityTimeMs
12648 = computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000, which) / 1000;
12649 final long sleepTimeMs
12650 = totalControllerActivityTimeMs - (idleTimeMs + rxTimeMs + txTimeMs);
12651 final long energyConsumedMaMs = counter.getPowerCounter().getCountLocked(which);
12652 long numAppScanRequest = 0;
12653 for (int i = 0; i < mUidStats.size(); i++) {
12654 numAppScanRequest += mUidStats.valueAt(i).mWifiScanTimer.getCountLocked(which);
12655 }
12656 long[] timeInStateMs = new long[NUM_WIFI_STATES];
12657 for (int i=0; i<NUM_WIFI_STATES; i++) {
12658 timeInStateMs[i] = getWifiStateTime(i, rawRealTime, which) / 1000;
12659 }
12660 long[] timeInSupplStateMs = new long[NUM_WIFI_SUPPL_STATES];
12661 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12662 timeInSupplStateMs[i] = getWifiSupplStateTime(i, rawRealTime, which) / 1000;
12663 }
12664 long[] timeSignalStrengthTimeMs = new long[NUM_WIFI_SIGNAL_STRENGTH_BINS];
12665 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12666 timeSignalStrengthTimeMs[i] = getWifiSignalStrengthTime(i, rawRealTime, which) / 1000;
12667 }
12668 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12669 s.setKernelActiveTimeMs(getWifiActiveTime(rawRealTime, which) / 1000);
12670 s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which));
12671 s.setNumBytesTx(getNetworkActivityBytes(NETWORK_WIFI_TX_DATA, which));
12672 s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which));
12673 s.setNumBytesRx(getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which));
12674 s.setSleepTimeMs(sleepTimeMs);
12675 s.setIdleTimeMs(idleTimeMs);
12676 s.setRxTimeMs(rxTimeMs);
12677 s.setTxTimeMs(txTimeMs);
12678 s.setScanTimeMs(scanTimeMs);
12679 s.setEnergyConsumedMaMs(energyConsumedMaMs);
12680 s.setNumAppScanRequest(numAppScanRequest);
12681 s.setTimeInStateMs(timeInStateMs);
12682 s.setTimeInSupplicantStateMs(timeInSupplStateMs);
12683 s.setTimeInRxSignalStrengthLevelMs(timeSignalStrengthTimeMs);
12684 return s;
12685 }
12686
Siddharth Ray78ccaf52017-12-23 16:16:21 -080012687 /*@hide */
12688 public GpsBatteryStats getGpsBatteryStats() {
12689 GpsBatteryStats s = new GpsBatteryStats();
12690 final int which = STATS_SINCE_CHARGED;
12691 final long rawRealTime = SystemClock.elapsedRealtime() * 1000;
12692 s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000);
12693 s.setEnergyConsumedMaMs(getGpsBatteryDrainMaMs());
12694 long[] time = new long[GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS];
12695 for (int i=0; i<time.length; i++) {
12696 time[i] = getGpsSignalQualityTime(i, rawRealTime, which) / 1000;
12697 }
12698 s.setTimeInGpsSignalQualityLevel(time);
12699 return s;
12700 }
12701
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012702 @Override
12703 public LevelStepTracker getChargeLevelStepTracker() {
12704 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012705 }
12706
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012707 @Override
12708 public LevelStepTracker getDailyChargeLevelStepTracker() {
12709 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070012710 }
12711
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012712 @Override
12713 public ArrayList<PackageChange> getDailyPackageChanges() {
12714 return mDailyPackageChanges;
12715 }
12716
Joe Onoratoe1acd632016-02-23 13:25:10 -080012717 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012718 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012719 }
12720
12721 @Override
12722 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012723 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012724 }
12725
12726 @Override
12727 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012728 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012729 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070012730
The Android Open Source Project10592532009-03-18 17:39:46 -070012731 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012732 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012733 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012734 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012735 }
12736 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012737
Evan Millar633a1742009-04-02 16:36:33 -070012738 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012739 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012740 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012741
The Android Open Source Project10592532009-03-18 17:39:46 -070012742 @Override
Evan Millar633a1742009-04-02 16:36:33 -070012743 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070012744 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070012745 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070012746 }
12747 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012748
Evan Millar633a1742009-04-02 16:36:33 -070012749 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012750 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070012751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012752
Amith Yamasanie43530a2009-08-21 13:11:37 -070012753 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012754 public int getLowDischargeAmountSinceCharge() {
12755 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012756 int val = mLowDischargeAmountSinceCharge;
12757 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12758 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
12759 }
12760 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012761 }
12762 }
12763
12764 @Override
12765 public int getHighDischargeAmountSinceCharge() {
12766 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080012767 int val = mHighDischargeAmountSinceCharge;
12768 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
12769 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
12770 }
12771 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012772 }
12773 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070012774
12775 @Override
12776 public int getDischargeAmount(int which) {
12777 int dischargeAmount = which == STATS_SINCE_CHARGED
12778 ? getHighDischargeAmountSinceCharge()
12779 : (getDischargeStartLevel() - getDischargeCurrentLevel());
12780 if (dischargeAmount < 0) {
12781 dischargeAmount = 0;
12782 }
12783 return dischargeAmount;
12784 }
12785
Mike Mac2f518a2017-09-19 16:06:03 -070012786 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012787 public int getDischargeAmountScreenOn() {
12788 synchronized(this) {
12789 int val = mDischargeAmountScreenOn;
Mike Mac2f518a2017-09-19 16:06:03 -070012790 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012791 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12792 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12793 }
12794 return val;
12795 }
12796 }
12797
Mike Mac2f518a2017-09-19 16:06:03 -070012798 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012799 public int getDischargeAmountScreenOnSinceCharge() {
12800 synchronized(this) {
12801 int val = mDischargeAmountScreenOnSinceCharge;
Mike Mac2f518a2017-09-19 16:06:03 -070012802 if (mOnBattery && isScreenOn(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012803 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
12804 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
12805 }
12806 return val;
12807 }
12808 }
12809
Mike Mac2f518a2017-09-19 16:06:03 -070012810 @Override
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012811 public int getDischargeAmountScreenOff() {
12812 synchronized(this) {
12813 int val = mDischargeAmountScreenOff;
Mike Mac2f518a2017-09-19 16:06:03 -070012814 if (mOnBattery && isScreenOff(mScreenState)
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012815 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12816 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12817 }
Mike Mac2f518a2017-09-19 16:06:03 -070012818 // For backward compatibility, doze discharge is counted into screen off.
12819 return val + getDischargeAmountScreenDoze();
12820 }
12821 }
12822
12823 @Override
12824 public int getDischargeAmountScreenOffSinceCharge() {
12825 synchronized(this) {
12826 int val = mDischargeAmountScreenOffSinceCharge;
12827 if (mOnBattery && isScreenOff(mScreenState)
12828 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
12829 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
12830 }
12831 // For backward compatibility, doze discharge is counted into screen off.
12832 return val + getDischargeAmountScreenDozeSinceCharge();
12833 }
12834 }
12835
12836 @Override
12837 public int getDischargeAmountScreenDoze() {
12838 synchronized(this) {
12839 int val = mDischargeAmountScreenDoze;
12840 if (mOnBattery && isScreenDoze(mScreenState)
12841 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
12842 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
12843 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012844 return val;
12845 }
12846 }
12847
Mike Mac2f518a2017-09-19 16:06:03 -070012848 @Override
12849 public int getDischargeAmountScreenDozeSinceCharge() {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012850 synchronized(this) {
Mike Mac2f518a2017-09-19 16:06:03 -070012851 int val = mDischargeAmountScreenDozeSinceCharge;
12852 if (mOnBattery && isScreenDoze(mScreenState)
12853 && mDischargeCurrentLevel < mDischargeScreenDozeUnplugLevel) {
12854 val += mDischargeScreenDozeUnplugLevel-mDischargeCurrentLevel;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012855 }
12856 return val;
12857 }
12858 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012860 /**
12861 * Retrieve the statistics object for a particular uid, creating if needed.
12862 */
12863 public Uid getUidStatsLocked(int uid) {
12864 Uid u = mUidStats.get(uid);
12865 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080012866 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012867 mUidStats.put(uid, u);
12868 }
12869 return u;
12870 }
12871
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012872 /**
12873 * Retrieve the statistics object for a particular uid. Returns null if the object is not
12874 * available.
12875 */
12876 public Uid getAvailableUidStatsLocked(int uid) {
12877 Uid u = mUidStats.get(uid);
12878 return u;
12879 }
12880
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012881 public void onCleanupUserLocked(int userId) {
12882 final int firstUidForUser = UserHandle.getUid(userId, 0);
12883 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
12884 mKernelUidCpuFreqTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
12885 mKernelUidCpuTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012886 if (mKernelSingleUidTimeReader != null) {
12887 mKernelSingleUidTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
12888 }
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070012889 }
12890
12891 public void onUserRemovedLocked(int userId) {
12892 final int firstUidForUser = UserHandle.getUid(userId, 0);
12893 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
12894 mUidStats.put(firstUidForUser, null);
12895 mUidStats.put(lastUidForUser, null);
12896 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
12897 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
12898 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
12899 }
12900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012901 /**
12902 * Remove the statistics object for a particular uid.
12903 */
12904 public void removeUidStatsLocked(int uid) {
Adam Lesinskib83ffee2015-05-12 14:43:47 -070012905 mKernelUidCpuTimeReader.removeUid(uid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -070012906 mKernelUidCpuFreqTimeReader.removeUid(uid);
Sudheer Shankab2f83c12017-11-13 19:25:01 -080012907 if (mKernelSingleUidTimeReader != null) {
12908 mKernelSingleUidTimeReader.removeUid(uid);
12909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012910 mUidStats.remove(uid);
12911 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070012912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012913 /**
12914 * Retrieve the statistics object for a particular process, creating
12915 * if needed.
12916 */
12917 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012918 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012919 Uid u = getUidStatsLocked(uid);
12920 return u.getProcessStatsLocked(name);
12921 }
12922
12923 /**
12924 * Retrieve the statistics object for a particular process, creating
12925 * if needed.
12926 */
12927 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012928 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012929 Uid u = getUidStatsLocked(uid);
12930 return u.getPackageStatsLocked(pkg);
12931 }
12932
12933 /**
12934 * Retrieve the statistics object for a particular service, creating
12935 * if needed.
12936 */
12937 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070012938 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012939 Uid u = getUidStatsLocked(uid);
12940 return u.getServiceStatsLocked(pkg, name);
12941 }
12942
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012943 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080012944 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070012945 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012946 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070012947 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012948
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012949 public boolean trackPerProcStateCpuTimes() {
12950 return mConstants.TRACK_CPU_TIMES_BY_PROC_STATE && mPerProcStateCpuTimesAvailable;
12951 }
12952
12953 public void systemServicesReady(Context context) {
12954 mConstants.startObserving(context.getContentResolver());
12955 }
12956
12957 @VisibleForTesting
12958 public final class Constants extends ContentObserver {
12959 public static final String KEY_TRACK_CPU_TIMES_BY_PROC_STATE
12960 = "track_cpu_times_by_proc_state";
Mike Mafae87da2018-01-19 20:07:20 -080012961 public static final String KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME
12962 = "track_cpu_active_cluster_time";
12963 public static final String KEY_READ_BINARY_CPU_TIME
12964 = "read_binary_cpu_time";
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012965
12966 private static final boolean DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE = true;
Mike Mafae87da2018-01-19 20:07:20 -080012967 private static final boolean DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME = true;
12968 private static final boolean DEFAULT_READ_BINARY_CPU_TIME = false;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012969
12970 public boolean TRACK_CPU_TIMES_BY_PROC_STATE = DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE;
Mike Mafae87da2018-01-19 20:07:20 -080012971 public boolean TRACK_CPU_ACTIVE_CLUSTER_TIME = DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME;
12972 // Not used right now.
12973 public boolean READ_BINARY_CPU_TIME = DEFAULT_READ_BINARY_CPU_TIME;
Sudheer Shanka5c19b892018-01-05 17:25:46 -080012974
12975 private ContentResolver mResolver;
12976 private final KeyValueListParser mParser = new KeyValueListParser(',');
12977
12978 public Constants(Handler handler) {
12979 super(handler);
12980 }
12981
12982 public void startObserving(ContentResolver resolver) {
12983 mResolver = resolver;
12984 mResolver.registerContentObserver(
12985 Settings.Global.getUriFor(Settings.Global.BATTERY_STATS_CONSTANTS),
12986 false /* notifyForDescendants */, this);
12987 updateConstants();
12988 }
12989
12990 @Override
12991 public void onChange(boolean selfChange, Uri uri) {
12992 updateConstants();
12993 }
12994
12995 private void updateConstants() {
12996 synchronized (BatteryStatsImpl.this) {
12997 try {
12998 mParser.setString(Settings.Global.getString(mResolver,
12999 Settings.Global.BATTERY_STATS_CONSTANTS));
13000 } catch (IllegalArgumentException e) {
13001 // Failed to parse the settings string, log this and move on
13002 // with defaults.
13003 Slog.e(TAG, "Bad batterystats settings", e);
13004 }
13005
13006 updateTrackCpuTimesByProcStateLocked(TRACK_CPU_TIMES_BY_PROC_STATE,
13007 mParser.getBoolean(KEY_TRACK_CPU_TIMES_BY_PROC_STATE,
13008 DEFAULT_TRACK_CPU_TIMES_BY_PROC_STATE));
Mike Mafae87da2018-01-19 20:07:20 -080013009 TRACK_CPU_ACTIVE_CLUSTER_TIME = mParser.getBoolean(
13010 KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME, DEFAULT_TRACK_CPU_ACTIVE_CLUSTER_TIME);
13011 READ_BINARY_CPU_TIME = mParser.getBoolean(
13012 KEY_READ_BINARY_CPU_TIME, DEFAULT_READ_BINARY_CPU_TIME);
13013
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013014 }
13015 }
13016
13017 private void updateTrackCpuTimesByProcStateLocked(boolean wasEnabled, boolean isEnabled) {
13018 TRACK_CPU_TIMES_BY_PROC_STATE = isEnabled;
13019 if (isEnabled && !wasEnabled) {
13020 mKernelSingleUidTimeReader.markDataAsStale(true);
13021 mExternalSync.scheduleCpuSyncDueToSettingChange();
13022 }
13023 }
13024
13025 public void dumpLocked(PrintWriter pw) {
13026 pw.print(KEY_TRACK_CPU_TIMES_BY_PROC_STATE); pw.print("=");
13027 pw.println(TRACK_CPU_TIMES_BY_PROC_STATE);
Mike Mafae87da2018-01-19 20:07:20 -080013028 pw.print(KEY_TRACK_CPU_ACTIVE_CLUSTER_TIME); pw.print("=");
13029 pw.println(TRACK_CPU_ACTIVE_CLUSTER_TIME);
13030 pw.print(KEY_READ_BINARY_CPU_TIME); pw.print("=");
13031 pw.println(READ_BINARY_CPU_TIME);
Sudheer Shanka5c19b892018-01-05 17:25:46 -080013032 }
13033 }
13034
13035 public void dumpConstantsLocked(PrintWriter pw) {
13036 mConstants.dumpLocked(pw);
13037 }
13038
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013039 Parcel mPendingWrite = null;
13040 final ReentrantLock mWriteLock = new ReentrantLock();
13041
13042 public void writeAsyncLocked() {
13043 writeLocked(false);
13044 }
13045
13046 public void writeSyncLocked() {
13047 writeLocked(true);
13048 }
13049
13050 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013051 if (mFile == null) {
13052 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013053 return;
13054 }
13055
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013056 if (mShuttingDown) {
13057 return;
13058 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013059
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013060 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013061 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080013062 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013063
13064 if (mPendingWrite != null) {
13065 mPendingWrite.recycle();
13066 }
13067 mPendingWrite = out;
13068
13069 if (sync) {
13070 commitPendingDataToDisk();
13071 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013072 BackgroundThread.getHandler().post(new Runnable() {
13073 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013074 commitPendingDataToDisk();
13075 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013076 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013077 }
13078 }
13079
13080 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013081 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013082 synchronized (this) {
13083 next = mPendingWrite;
13084 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070013085 if (next == null) {
13086 return;
13087 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013088 }
13089
Amith Yamasanid2450862017-02-07 15:58:24 -080013090 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013091 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013092 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013093 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013094 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070013095 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013096 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013097 mFile.commit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013098 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013099 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070013100 mFile.rollback();
13101 } finally {
13102 next.recycle();
13103 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070013104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013105 }
13106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013107 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013108 if (mDailyFile != null) {
13109 readDailyStatsLocked();
13110 }
13111
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013112 if (mFile == null) {
13113 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013114 return;
13115 }
13116
13117 mUidStats.clear();
13118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013119 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013120 File file = mFile.chooseForRead();
13121 if (!file.exists()) {
13122 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013123 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013124 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013125
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013126 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013127 Parcel in = Parcel.obtain();
13128 in.unmarshall(raw, 0, raw.length);
13129 in.setDataPosition(0);
13130 stream.close();
13131
13132 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080013133 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013134 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013135 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013136 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013137
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013138 mEndPlatformVersion = Build.ID;
13139
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013140 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013141 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080013142 final long elapsedRealtime = mClocks.elapsedRealtime();
13143 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013144 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013145 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080013146 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013147 addHistoryBufferLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
13148 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013149 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013150
13151 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013152 }
13153
13154 public int describeContents() {
13155 return 0;
13156 }
13157
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013158 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070013159 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013160
13161 mHistoryBuffer.setDataSize(0);
13162 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013163 mHistoryTagPool.clear();
13164 mNextHistoryTagIdx = 0;
13165 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013166
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013167 int numTags = in.readInt();
13168 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080013169 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013170 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013171 if (str == null) {
13172 throw new ParcelFormatException("null history tag string");
13173 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013174 int uid = in.readInt();
13175 HistoryTag tag = new HistoryTag();
13176 tag.string = str;
13177 tag.uid = uid;
13178 tag.poolIdx = idx;
13179 mHistoryTagPool.put(tag, idx);
13180 if (idx >= mNextHistoryTagIdx) {
13181 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013182 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013183 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080013184 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013185
13186 int bufSize = in.readInt();
13187 int curPos = in.dataPosition();
13188 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013189 throw new ParcelFormatException("File corrupt: history data buffer too large " +
13190 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013191 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013192 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
13193 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013194 } else {
13195 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
13196 + " bytes at " + curPos);
13197 mHistoryBuffer.appendFrom(in, curPos, bufSize);
13198 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013199 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013200
Dianne Hackbornae384452011-06-28 12:33:48 -070013201 if (andOldHistory) {
13202 readOldHistory(in);
13203 }
13204
13205 if (DEBUG_HISTORY) {
13206 StringBuilder sb = new StringBuilder(128);
13207 sb.append("****************** OLD mHistoryBaseTime: ");
13208 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13209 Slog.i(TAG, sb.toString());
13210 }
13211 mHistoryBaseTime = historyBaseTime;
13212 if (DEBUG_HISTORY) {
13213 StringBuilder sb = new StringBuilder(128);
13214 sb.append("****************** NEW mHistoryBaseTime: ");
13215 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13216 Slog.i(TAG, sb.toString());
13217 }
13218
13219 // We are just arbitrarily going to insert 1 minute from the sample of
13220 // the last run until samples in this run.
13221 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080013222 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013223 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070013224 if (DEBUG_HISTORY) {
13225 StringBuilder sb = new StringBuilder(128);
13226 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
13227 TimeUtils.formatDuration(mHistoryBaseTime, sb);
13228 Slog.i(TAG, sb.toString());
13229 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070013230 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013231 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013232
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013233 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013234 if (!USE_OLD_HISTORY) {
13235 return;
13236 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013237 mHistory = mHistoryEnd = mHistoryCache = null;
13238 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070013239 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013240 HistoryItem rec = new HistoryItem(time, in);
13241 addHistoryRecordLocked(rec);
13242 }
13243 }
13244
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013245 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070013246 if (DEBUG_HISTORY) {
13247 StringBuilder sb = new StringBuilder(128);
13248 sb.append("****************** WRITING mHistoryBaseTime: ");
13249 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070013250 sb.append(" mLastHistoryElapsedRealtime: ");
13251 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070013252 Slog.i(TAG, sb.toString());
13253 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070013254 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013255 if (!inclData) {
13256 out.writeInt(0);
13257 out.writeInt(0);
13258 return;
13259 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013260 out.writeInt(mHistoryTagPool.size());
13261 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
13262 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080013263 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080013264 out.writeString(tag.string);
13265 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080013266 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013267 out.writeInt(mHistoryBuffer.dataSize());
13268 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
13269 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
13270 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070013271
13272 if (andOldHistory) {
13273 writeOldHistory(out);
13274 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013275 }
13276
13277 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070013278 if (!USE_OLD_HISTORY) {
13279 return;
13280 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013281 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070013282 while (rec != null) {
13283 if (rec.time >= 0) rec.writeToParcel(out, 0);
13284 rec = rec.next;
13285 }
13286 out.writeLong(-1);
13287 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013288
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013289 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013290 final int version = in.readInt();
13291 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013292 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013293 + ", expected " + VERSION + "; erasing old stats");
13294 return;
13295 }
13296
Dianne Hackbornae384452011-06-28 12:33:48 -070013297 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013299 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013300 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013301 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013302 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013303 mStartPlatformVersion = in.readString();
13304 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013305 mOnBatteryTimeBase.readSummaryFromParcel(in);
13306 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013307 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013308 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070013309 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013310 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013311 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070013312 mMinLearnedBatteryCapacity = in.readInt();
13313 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070013314 mLowDischargeAmountSinceCharge = in.readInt();
13315 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013316 mDischargeAmountScreenOnSinceCharge = in.readInt();
13317 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070013318 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013319 mDischargeStepTracker.readFromParcel(in);
13320 mChargeStepTracker.readFromParcel(in);
13321 mDailyDischargeStepTracker.readFromParcel(in);
13322 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070013323 mDischargeCounter.readSummaryFromParcelLocked(in);
13324 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013325 mDischargeScreenDozeCounter.readSummaryFromParcelLocked(in);
Mike Ma15313c92017-11-15 17:58:21 -080013326 mDischargeLightDozeCounter.readSummaryFromParcelLocked(in);
13327 mDischargeDeepDozeCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013328 int NPKG = in.readInt();
13329 if (NPKG > 0) {
13330 mDailyPackageChanges = new ArrayList<>(NPKG);
13331 while (NPKG > 0) {
13332 NPKG--;
13333 PackageChange pc = new PackageChange();
13334 pc.mPackageName = in.readString();
13335 pc.mUpdate = in.readInt() != 0;
Dianne Hackborn3accca02013-09-20 09:32:11 -070013336 pc.mVersionCode = in.readLong();
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013337 mDailyPackageChanges.add(pc);
13338 }
13339 } else {
13340 mDailyPackageChanges = null;
13341 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013342 mDailyStartTime = in.readLong();
13343 mNextMinDailyDeadline = in.readLong();
13344 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013346 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013347
Jeff Browne95c3cd2014-05-02 16:59:26 -070013348 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013349 mScreenOnTimer.readSummaryFromParcelLocked(in);
Mike Mac2f518a2017-09-19 16:06:03 -070013350 mScreenDozeTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013351 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
13352 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
13353 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013354 mInteractive = false;
13355 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013356 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013357 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013358 mLongestLightIdleTime = in.readLong();
13359 mLongestFullIdleTime = in.readLong();
13360 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
13361 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
13362 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013363 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013364 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080013365 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070013366 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13367 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070013368 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013369 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
13370 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
13371 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013372 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013373 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13374 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013375 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013376 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080013377 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080013378 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013379 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013380 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
13381 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013382 mWifiMulticastWakelockTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070013383 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070013384 mWifiOn = false;
13385 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013386 mGlobalWifiRunning = false;
13387 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013388 for (int i=0; i<NUM_WIFI_STATES; i++) {
13389 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
13390 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013391 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13392 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
13393 }
13394 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13395 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
13396 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013397 mWifiActiveTimer.readSummaryFromParcelLocked(in);
13398 mWifiActivity.readSummaryFromParcel(in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013399 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13400 mGpsSignalQualityTimer[i].readSummaryFromParcelLocked(in);
13401 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013402 mBluetoothActivity.readSummaryFromParcel(in);
13403 mModemActivity.readSummaryFromParcel(in);
13404 mHasWifiReporting = in.readInt() != 0;
13405 mHasBluetoothReporting = in.readInt() != 0;
13406 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070013407
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013408 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013409 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013410 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013411 mCameraOnNesting = 0;
13412 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013413 mBluetoothScanNesting = 0;
13414 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013415
Bookatz50df7112017-08-04 14:53:26 -070013416 int NRPMS = in.readInt();
13417 if (NRPMS > 10000) {
13418 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
13419 }
13420 for (int irpm = 0; irpm < NRPMS; irpm++) {
13421 if (in.readInt() != 0) {
13422 String rpmName = in.readString();
13423 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13424 }
13425 }
13426 int NSORPMS = in.readInt();
13427 if (NSORPMS > 10000) {
13428 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
13429 }
13430 for (int irpm = 0; irpm < NSORPMS; irpm++) {
13431 if (in.readInt() != 0) {
13432 String rpmName = in.readString();
13433 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
13434 }
13435 }
13436
Evan Millarc64edde2009-04-18 12:26:32 -070013437 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013438 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013439 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013440 }
Evan Millarc64edde2009-04-18 12:26:32 -070013441 for (int ikw = 0; ikw < NKW; ikw++) {
13442 if (in.readInt() != 0) {
13443 String kwltName = in.readString();
13444 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
13445 }
13446 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070013447
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013448 int NWR = in.readInt();
13449 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013450 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013451 }
13452 for (int iwr = 0; iwr < NWR; iwr++) {
13453 if (in.readInt() != 0) {
13454 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013455 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013456 }
13457 }
13458
James Carr3a226052016-07-01 14:49:52 -070013459 int NMS = in.readInt();
13460 for (int ims = 0; ims < NMS; ims++) {
13461 if (in.readInt() != 0) {
13462 long kmstName = in.readLong();
13463 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
13464 }
13465 }
13466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013467 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013468 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013469 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013471 for (int iu = 0; iu < NU; iu++) {
13472 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080013473 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013474 mUidStats.put(uid, u);
13475
Bookatz867c0d72017-03-07 18:23:42 -080013476 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070013477 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080013478
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013479 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013480 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013481 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013482 }
The Android Open Source Project10592532009-03-18 17:39:46 -070013483 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013484 if (in.readInt() != 0) {
13485 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
13486 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013487 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013488 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070013489 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013490 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013491 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
13492 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13493 if (in.readInt() != 0) {
13494 u.makeWifiBatchedScanBin(i, null);
13495 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
13496 }
13497 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013498 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013499 if (in.readInt() != 0) {
13500 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
13501 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013502 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013503 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013504 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013505 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013506 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13507 }
13508 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013509 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13510 }
13511 if (in.readInt() != 0) {
13512 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
13513 }
13514 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013515 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
13516 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013517 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013518 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
13519 }
13520 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070013521 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
13522 }
13523 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013524 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
13525 }
Bookatz956f36bf2017-04-28 09:48:17 -070013526 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070013527 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
13528 }
13529 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070013530 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
13531 }
Bookatzb1f04f32017-05-19 13:57:32 -070013532 if (in.readInt() != 0) {
13533 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
13534 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080013535 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070013536 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
13537 if (in.readInt() != 0) {
13538 u.makeProcessState(i, null);
13539 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
13540 }
13541 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013542 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080013543 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013544 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070013545
Dianne Hackborn617f8772009-03-31 15:04:46 -070013546 if (in.readInt() != 0) {
13547 if (u.mUserActivityCounters == null) {
13548 u.initUserActivityLocked();
13549 }
13550 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
13551 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
13552 }
13553 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013554
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013555 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013556 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013557 u.initNetworkActivityLocked();
13558 }
13559 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013560 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
13561 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013562 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013563 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
13564 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013565 }
13566
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013567 u.mUserCpuTime.readSummaryFromParcelLocked(in);
13568 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
13569
Adam Lesinski6832f392015-09-05 18:05:40 -070013570 if (in.readInt() != 0) {
13571 final int numClusters = in.readInt();
13572 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
13573 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013574 }
Adam Lesinski6832f392015-09-05 18:05:40 -070013575
Sudheer Shankaaf857412017-07-21 00:14:24 -070013576 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070013577 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070013578 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070013579 final int NSB = in.readInt();
13580 if (mPowerProfile != null &&
13581 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
13582 throw new ParcelFormatException("File corrupt: too many speed bins " +
13583 NSB);
13584 }
13585
Sudheer Shankaaf857412017-07-21 00:14:24 -070013586 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070013587 for (int speed = 0; speed < NSB; speed++) {
13588 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013589 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070013590 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070013591 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070013592 }
13593 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070013594 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013595 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070013596 }
13597 }
13598 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070013599 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070013600 }
13601
Sudheer Shanka59f5c002017-05-15 10:57:15 -070013602 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13603 in, mOnBatteryTimeBase);
13604 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
13605 in, mOnBatteryScreenOffTimeBase);
Mike Ma3d422c32017-10-25 11:08:57 -070013606
13607 u.mCpuActiveTimeMs.readSummaryFromParcelLocked(in);
13608 u.mCpuClusterTimesMs.readSummaryFromParcelLocked(in);
13609
Sudheer Shankab2f83c12017-11-13 19:25:01 -080013610 int length = in.readInt();
13611 if (length == Uid.NUM_PROCESS_STATE) {
13612 u.mProcStateTimeMs = new LongSamplingCounterArray[length];
13613 for (int procState = 0; procState < length; ++procState) {
13614 u.mProcStateTimeMs[procState]
13615 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13616 in, mOnBatteryTimeBase);
13617 }
13618 } else {
13619 u.mProcStateTimeMs = null;
13620 }
13621 length = in.readInt();
13622 if (length == Uid.NUM_PROCESS_STATE) {
13623 u.mProcStateScreenOffTimeMs = new LongSamplingCounterArray[length];
13624 for (int procState = 0; procState < length; ++procState) {
13625 u.mProcStateScreenOffTimeMs[procState]
13626 = LongSamplingCounterArray.readSummaryFromParcelLocked(
13627 in, mOnBatteryScreenOffTimeBase);
13628 }
13629 } else {
13630 u.mProcStateScreenOffTimeMs = null;
13631 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070013632
13633 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070013634 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13635 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
13636 } else {
13637 u.mMobileRadioApWakeupCount = null;
13638 }
13639
13640 if (in.readInt() != 0) {
13641 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
13642 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
13643 } else {
13644 u.mWifiRadioApWakeupCount = null;
13645 }
13646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013647 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013648 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013649 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013651 for (int iw = 0; iw < NW; iw++) {
13652 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013653 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013654 }
13655
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013656 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013657 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013658 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013659 }
13660 for (int is = 0; is < NS; is++) {
13661 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013662 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013663 }
13664
13665 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070013666 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013667 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013668 }
13669 for (int ij = 0; ij < NJ; ij++) {
13670 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070013671 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013672 }
13673
Dianne Hackborn94326cb2017-06-28 16:17:20 -070013674 u.readJobCompletionsFromParcelLocked(in);
13675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013676 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013677 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013678 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013680 for (int is = 0; is < NP; is++) {
13681 int seNumber = in.readInt();
13682 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080013683 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013684 }
13685 }
13686
13687 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013688 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013689 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013691 for (int ip = 0; ip < NP; ip++) {
13692 String procName = in.readString();
13693 Uid.Proc p = u.getProcessStatsLocked(procName);
13694 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013695 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013696 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013697 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013698 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
13699 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013700 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013701 }
13702
13703 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013704 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013705 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070013706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013707 for (int ip = 0; ip < NP; ip++) {
13708 String pkgName = in.readString();
13709 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013710 final int NWA = in.readInt();
13711 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013712 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013713 }
13714 p.mWakeupAlarms.clear();
13715 for (int iwa=0; iwa<NWA; iwa++) {
13716 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070013717 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070013718 c.readSummaryFromParcelLocked(in);
13719 p.mWakeupAlarms.put(tag, c);
13720 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070013721 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013722 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070013723 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080013724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013725 for (int is = 0; is < NS; is++) {
13726 String servName = in.readString();
13727 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
13728 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013729 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013730 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013731 }
13732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013733 }
13734 }
13735
13736 /**
13737 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
13738 * disk. This format does not allow a lossless round-trip.
13739 *
13740 * @param out the Parcel to be written to.
13741 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013742 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080013743 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070013744
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013745 // Pull the clock time. This may update the time and make a new history entry
13746 // if we had originally pulled a time before the RTC was set.
13747 long startClockTime = getStartClockTime();
13748
Joe Onoratoabded112016-02-08 16:49:39 -080013749 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
13750 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013751
13752 out.writeInt(VERSION);
13753
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070013754 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013756 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013757 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013758 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070013759 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070013760 out.writeString(mStartPlatformVersion);
13761 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013762 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
13763 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013764 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013765 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070013766 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070013767 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070013768 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070013769 out.writeInt(mMinLearnedBatteryCapacity);
13770 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080013771 out.writeInt(getLowDischargeAmountSinceCharge());
13772 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080013773 out.writeInt(getDischargeAmountScreenOnSinceCharge());
13774 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Mike Mac2f518a2017-09-19 16:06:03 -070013775 out.writeInt(getDischargeAmountScreenDozeSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013776 mDischargeStepTracker.writeToParcel(out);
13777 mChargeStepTracker.writeToParcel(out);
13778 mDailyDischargeStepTracker.writeToParcel(out);
13779 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070013780 mDischargeCounter.writeSummaryFromParcelLocked(out);
13781 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Mike Mac2f518a2017-09-19 16:06:03 -070013782 mDischargeScreenDozeCounter.writeSummaryFromParcelLocked(out);
Mike Ma15313c92017-11-15 17:58:21 -080013783 mDischargeLightDozeCounter.writeSummaryFromParcelLocked(out);
13784 mDischargeDeepDozeCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013785 if (mDailyPackageChanges != null) {
13786 final int NPKG = mDailyPackageChanges.size();
13787 out.writeInt(NPKG);
13788 for (int i=0; i<NPKG; i++) {
13789 PackageChange pc = mDailyPackageChanges.get(i);
13790 out.writeString(pc.mPackageName);
13791 out.writeInt(pc.mUpdate ? 1 : 0);
Dianne Hackborn3accca02013-09-20 09:32:11 -070013792 out.writeLong(pc.mVersionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013793 }
13794 } else {
13795 out.writeInt(0);
13796 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080013797 out.writeLong(mDailyStartTime);
13798 out.writeLong(mNextMinDailyDeadline);
13799 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013800
13801 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Mike Mac2f518a2017-09-19 16:06:03 -070013802 mScreenDozeTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013803 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013804 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070013805 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070013806 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070013807 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070013808 out.writeLong(mLongestLightIdleTime);
13809 out.writeLong(mLongestFullIdleTime);
13810 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13811 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13812 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070013813 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013814 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080013815 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013816 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013817 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013818 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013819 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013820 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070013821 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013822 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080013823 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
13824 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070013825 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013826 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13827 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013828 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080013829 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
13830 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080013831 mWifiMulticastWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013832 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13833 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013834 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013835 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080013836 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070013837 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
13838 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13839 }
13840 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
13841 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13842 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080013843 mWifiActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13844 mWifiActivity.writeSummaryToParcel(out);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080013845 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
13846 mGpsSignalQualityTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13847 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080013848 mBluetoothActivity.writeSummaryToParcel(out);
13849 mModemActivity.writeSummaryToParcel(out);
13850 out.writeInt(mHasWifiReporting ? 1 : 0);
13851 out.writeInt(mHasBluetoothReporting ? 1 : 0);
13852 out.writeInt(mHasModemReporting ? 1 : 0);
13853
Dianne Hackborn1e01d162014-12-04 17:46:42 -080013854 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070013855 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013856 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080013857 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013858
Bookatz50df7112017-08-04 14:53:26 -070013859 out.writeInt(mRpmStats.size());
13860 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
13861 Timer rpmt = ent.getValue();
13862 if (rpmt != null) {
13863 out.writeInt(1);
13864 out.writeString(ent.getKey());
13865 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13866 } else {
13867 out.writeInt(0);
13868 }
13869 }
13870 out.writeInt(mScreenOffRpmStats.size());
13871 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
13872 Timer rpmt = ent.getValue();
13873 if (rpmt != null) {
13874 out.writeInt(1);
13875 out.writeString(ent.getKey());
13876 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13877 } else {
13878 out.writeInt(0);
13879 }
13880 }
13881
Evan Millarc64edde2009-04-18 12:26:32 -070013882 out.writeInt(mKernelWakelockStats.size());
13883 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
13884 Timer kwlt = ent.getValue();
13885 if (kwlt != null) {
13886 out.writeInt(1);
13887 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013888 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13889 } else {
13890 out.writeInt(0);
13891 }
13892 }
13893
13894 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013895 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
13896 SamplingTimer timer = ent.getValue();
13897 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070013898 out.writeInt(1);
13899 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070013900 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070013901 } else {
13902 out.writeInt(0);
13903 }
13904 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013905
James Carr3a226052016-07-01 14:49:52 -070013906 out.writeInt(mKernelMemoryStats.size());
13907 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
13908 Timer kmt = mKernelMemoryStats.valueAt(i);
13909 if (kmt != null) {
13910 out.writeInt(1);
13911 out.writeLong(mKernelMemoryStats.keyAt(i));
13912 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13913 } else {
13914 out.writeInt(0);
13915 }
13916 }
13917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013918 final int NU = mUidStats.size();
13919 out.writeInt(NU);
13920 for (int iu = 0; iu < NU; iu++) {
13921 out.writeInt(mUidStats.keyAt(iu));
13922 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070013923
Bookatz867c0d72017-03-07 18:23:42 -080013924 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070013925 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080013926
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070013927 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013928 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013929 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013930 } else {
13931 out.writeInt(0);
13932 }
13933 if (u.mFullWifiLockTimer != null) {
13934 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013935 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013936 } else {
13937 out.writeInt(0);
13938 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070013939 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013940 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013941 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013942 } else {
13943 out.writeInt(0);
13944 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070013945 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
13946 if (u.mWifiBatchedScanTimer[i] != null) {
13947 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013948 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070013949 } else {
13950 out.writeInt(0);
13951 }
13952 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013953 if (u.mWifiMulticastTimer != null) {
13954 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013955 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013956 } else {
13957 out.writeInt(0);
13958 }
13959 if (u.mAudioTurnedOnTimer != null) {
13960 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013961 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013962 } else {
13963 out.writeInt(0);
13964 }
13965 if (u.mVideoTurnedOnTimer != null) {
13966 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013967 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070013968 } else {
13969 out.writeInt(0);
13970 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070013971 if (u.mFlashlightTurnedOnTimer != null) {
13972 out.writeInt(1);
13973 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13974 } else {
13975 out.writeInt(0);
13976 }
13977 if (u.mCameraTurnedOnTimer != null) {
13978 out.writeInt(1);
13979 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13980 } else {
13981 out.writeInt(0);
13982 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013983 if (u.mForegroundActivityTimer != null) {
13984 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080013985 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070013986 } else {
13987 out.writeInt(0);
13988 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070013989 if (u.mForegroundServiceTimer != null) {
13990 out.writeInt(1);
13991 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13992 } else {
13993 out.writeInt(0);
13994 }
Bookatzc8c44962017-05-11 12:12:54 -070013995 if (u.mAggregatedPartialWakelockTimer != null) {
13996 out.writeInt(1);
13997 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
13998 } else {
13999 out.writeInt(0);
14000 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014001 if (u.mBluetoothScanTimer != null) {
14002 out.writeInt(1);
14003 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14004 } else {
14005 out.writeInt(0);
14006 }
Bookatzb1f04f32017-05-19 13:57:32 -070014007 if (u.mBluetoothUnoptimizedScanTimer != null) {
14008 out.writeInt(1);
14009 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14010 } else {
14011 out.writeInt(0);
14012 }
Bookatz956f36bf2017-04-28 09:48:17 -070014013 if (u.mBluetoothScanResultCounter != null) {
14014 out.writeInt(1);
14015 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
14016 } else {
14017 out.writeInt(0);
14018 }
Bookatzb1f04f32017-05-19 13:57:32 -070014019 if (u.mBluetoothScanResultBgCounter != null) {
14020 out.writeInt(1);
14021 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
14022 } else {
14023 out.writeInt(0);
14024 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070014025 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
14026 if (u.mProcessStateTimer[i] != null) {
14027 out.writeInt(1);
14028 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14029 } else {
14030 out.writeInt(0);
14031 }
14032 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014033 if (u.mVibratorOnTimer != null) {
14034 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014035 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080014036 } else {
14037 out.writeInt(0);
14038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014039
Dianne Hackborn617f8772009-03-31 15:04:46 -070014040 if (u.mUserActivityCounters == null) {
14041 out.writeInt(0);
14042 } else {
14043 out.writeInt(1);
14044 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
14045 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
14046 }
14047 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014048
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014049 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014050 out.writeInt(0);
14051 } else {
14052 out.writeInt(1);
14053 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080014054 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
14055 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014056 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080014057 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
14058 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070014059 }
14060
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014061 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
14062 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
14063
Sudheer Shankaaf857412017-07-21 00:14:24 -070014064 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014065 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070014066 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
14067 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070014068 if (cpuSpeeds != null) {
14069 out.writeInt(1);
14070 out.writeInt(cpuSpeeds.length);
14071 for (LongSamplingCounter c : cpuSpeeds) {
14072 if (c != null) {
14073 out.writeInt(1);
14074 c.writeSummaryFromParcelLocked(out);
14075 } else {
14076 out.writeInt(0);
14077 }
14078 }
14079 } else {
14080 out.writeInt(0);
14081 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014082 }
Adam Lesinski6832f392015-09-05 18:05:40 -070014083 } else {
14084 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070014085 }
14086
Sudheer Shanka59f5c002017-05-15 10:57:15 -070014087 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
14088 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070014089
Mike Ma3d422c32017-10-25 11:08:57 -070014090 u.mCpuActiveTimeMs.writeSummaryFromParcelLocked(out);
14091 u.mCpuClusterTimesMs.writeSummaryToParcelLocked(out);
14092
Sudheer Shankab2f83c12017-11-13 19:25:01 -080014093 if (u.mProcStateTimeMs != null) {
14094 out.writeInt(u.mProcStateTimeMs.length);
14095 for (LongSamplingCounterArray counters : u.mProcStateTimeMs) {
14096 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14097 }
14098 } else {
14099 out.writeInt(0);
14100 }
14101 if (u.mProcStateScreenOffTimeMs != null) {
14102 out.writeInt(u.mProcStateScreenOffTimeMs.length);
14103 for (LongSamplingCounterArray counters : u.mProcStateScreenOffTimeMs) {
14104 LongSamplingCounterArray.writeSummaryToParcelLocked(out, counters);
14105 }
14106 } else {
14107 out.writeInt(0);
14108 }
14109
Adam Lesinski5f056f62016-07-14 16:56:08 -070014110 if (u.mMobileRadioApWakeupCount != null) {
14111 out.writeInt(1);
14112 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14113 } else {
14114 out.writeInt(0);
14115 }
14116
14117 if (u.mWifiRadioApWakeupCount != null) {
14118 out.writeInt(1);
14119 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
14120 } else {
14121 out.writeInt(0);
14122 }
14123
Dianne Hackbornd953c532014-08-16 18:17:38 -070014124 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
14125 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014126 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014127 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014128 out.writeString(wakeStats.keyAt(iw));
14129 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014130 if (wl.mTimerFull != null) {
14131 out.writeInt(1);
14132 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14133 } else {
14134 out.writeInt(0);
14135 }
14136 if (wl.mTimerPartial != null) {
14137 out.writeInt(1);
14138 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14139 } else {
14140 out.writeInt(0);
14141 }
14142 if (wl.mTimerWindow != null) {
14143 out.writeInt(1);
14144 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14145 } else {
14146 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014147 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014148 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070014149 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070014150 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070014151 } else {
14152 out.writeInt(0);
14153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014154 }
14155
Bookatz2bffb5b2017-04-13 11:59:33 -070014156 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014157 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014158 out.writeInt(NS);
14159 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014160 out.writeString(syncStats.keyAt(is));
14161 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014162 }
14163
Bookatzaa4594a2017-03-24 12:39:56 -070014164 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070014165 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014166 out.writeInt(NJ);
14167 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070014168 out.writeString(jobStats.keyAt(ij));
14169 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014170 }
14171
Dianne Hackborn94326cb2017-06-28 16:17:20 -070014172 u.writeJobCompletionsToParcelLocked(out);
14173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014174 int NSE = u.mSensorStats.size();
14175 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014176 for (int ise=0; ise<NSE; ise++) {
14177 out.writeInt(u.mSensorStats.keyAt(ise));
14178 Uid.Sensor se = u.mSensorStats.valueAt(ise);
14179 if (se.mTimer != null) {
14180 out.writeInt(1);
14181 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
14182 } else {
14183 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014184 }
14185 }
14186
14187 int NP = u.mProcessStats.size();
14188 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014189 for (int ip=0; ip<NP; ip++) {
14190 out.writeString(u.mProcessStats.keyAt(ip));
14191 Uid.Proc ps = u.mProcessStats.valueAt(ip);
14192 out.writeLong(ps.mUserTime);
14193 out.writeLong(ps.mSystemTime);
14194 out.writeLong(ps.mForegroundTime);
14195 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014196 out.writeInt(ps.mNumCrashes);
14197 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070014198 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014199 }
14200
14201 NP = u.mPackageStats.size();
14202 out.writeInt(NP);
14203 if (NP > 0) {
14204 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
14205 : u.mPackageStats.entrySet()) {
14206 out.writeString(ent.getKey());
14207 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014208 final int NWA = ps.mWakeupAlarms.size();
14209 out.writeInt(NWA);
14210 for (int iwa=0; iwa<NWA; iwa++) {
14211 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
14212 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
14213 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014214 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014215 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070014216 for (int is=0; is<NS; is++) {
14217 out.writeString(ps.mServiceStats.keyAt(is));
14218 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
14219 long time = ss.getStartTimeToNowLocked(
14220 mOnBatteryTimeBase.getUptime(NOW_SYS));
14221 out.writeLong(time);
14222 out.writeInt(ss.mStarts);
14223 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014224 }
14225 }
14226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014227 }
14228 }
14229
14230 public void readFromParcel(Parcel in) {
14231 readFromParcelLocked(in);
14232 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014234 void readFromParcelLocked(Parcel in) {
14235 int magic = in.readInt();
14236 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070014237 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014238 }
14239
Dianne Hackbornae384452011-06-28 12:33:48 -070014240 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014242 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080014243 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014244 mStartPlatformVersion = in.readString();
14245 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014246 mUptime = in.readLong();
14247 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014248 mRealtime = in.readLong();
14249 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014250 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014251 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070014252 mMinLearnedBatteryCapacity = in.readInt();
14253 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014254 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014255 mOnBatteryTimeBase.readFromParcel(in);
14256 mOnBatteryScreenOffTimeBase.readFromParcel(in);
14257
Jeff Browne95c3cd2014-05-02 16:59:26 -070014258 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080014259 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014260 mScreenDozeTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014261 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014262 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
14263 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014264 }
Dianne Hackborn29325132014-05-21 15:01:03 -070014265 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014266 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014267 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014268 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
14269 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014270 mLongestLightIdleTime = in.readLong();
14271 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080014272 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
14273 mOnBatteryTimeBase, in);
14274 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
14275 mOnBatteryTimeBase, in);
14276 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
14277 mOnBatteryTimeBase, in);
14278 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
14279 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014280 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014281 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014282 null, mOnBatteryTimeBase, in);
14283 }
Joe Onoratoabded112016-02-08 16:49:39 -080014284 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
14285 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014286 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014287 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014288 null, mOnBatteryTimeBase, in);
14289 }
14290 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14291 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14292 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
14293 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014294 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080014295 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
14296 mOnBatteryTimeBase, in);
Kweku Adams87b19ec2017-10-09 12:40:03 -070014297 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
Joe Onoratoabded112016-02-08 16:49:39 -080014298 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014299 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014300 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
14301 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014302 mWifiMulticastWakelockTimer = new StopwatchTimer(mClocks, null, -4, null,
14303 mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014304 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014305 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014306 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014307 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080014308 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
14309 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014310 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014311 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014312 null, mOnBatteryTimeBase, in);
14313 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014314 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014315 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014316 null, mOnBatteryTimeBase, in);
14317 }
14318 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080014319 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070014320 null, mOnBatteryTimeBase, in);
14321 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014322 mWifiActiveTimer = new StopwatchTimer(mClocks, null, -900, null,
14323 mOnBatteryTimeBase, in);
14324 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14325 NUM_WIFI_TX_LEVELS, in);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014326 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14327 mGpsSignalQualityTimer[i] = new StopwatchTimer(mClocks, null, -1000-i,
14328 null, mOnBatteryTimeBase, in);
14329 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014330 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14331 NUM_BT_TX_LEVELS, in);
14332 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
14333 ModemActivityInfo.TX_POWER_LEVELS, in);
14334 mHasWifiReporting = in.readInt() != 0;
14335 mHasBluetoothReporting = in.readInt() != 0;
14336 mHasModemReporting = in.readInt() != 0;
14337
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014338 mNumConnectivityChange = in.readInt();
14339 mLoadedNumConnectivityChange = in.readInt();
14340 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014341 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014342 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014343 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014344 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014345 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014346 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014347 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014348 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014349 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080014350 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014351 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014352 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070014353 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014354 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014355 mLowDischargeAmountSinceCharge = in.readInt();
14356 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014357 mDischargeAmountScreenOn = in.readInt();
14358 mDischargeAmountScreenOnSinceCharge = in.readInt();
14359 mDischargeAmountScreenOff = in.readInt();
14360 mDischargeAmountScreenOffSinceCharge = in.readInt();
Mike Mac2f518a2017-09-19 16:06:03 -070014361 mDischargeAmountScreenDoze = in.readInt();
14362 mDischargeAmountScreenDozeSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014363 mDischargeStepTracker.readFromParcel(in);
14364 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014365 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Mac2f518a2017-09-19 16:06:03 -070014366 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase, in);
14367 mDischargeScreenDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
Mike Ma15313c92017-11-15 17:58:21 -080014368 mDischargeLightDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
14369 mDischargeDeepDozeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014370 mLastWriteTime = in.readLong();
14371
Bookatz50df7112017-08-04 14:53:26 -070014372 mRpmStats.clear();
14373 int NRPMS = in.readInt();
14374 for (int irpm = 0; irpm < NRPMS; irpm++) {
14375 if (in.readInt() != 0) {
14376 String rpmName = in.readString();
14377 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14378 mRpmStats.put(rpmName, rpmt);
14379 }
14380 }
14381 mScreenOffRpmStats.clear();
14382 int NSORPMS = in.readInt();
14383 for (int irpm = 0; irpm < NSORPMS; irpm++) {
14384 if (in.readInt() != 0) {
14385 String rpmName = in.readString();
14386 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
14387 mScreenOffRpmStats.put(rpmName, rpmt);
14388 }
14389 }
14390
Evan Millarc64edde2009-04-18 12:26:32 -070014391 mKernelWakelockStats.clear();
14392 int NKW = in.readInt();
14393 for (int ikw = 0; ikw < NKW; ikw++) {
14394 if (in.readInt() != 0) {
14395 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014396 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070014397 mKernelWakelockStats.put(wakelockName, kwlt);
14398 }
14399 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014400
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014401 mWakeupReasonStats.clear();
14402 int NWR = in.readInt();
14403 for (int iwr = 0; iwr < NWR; iwr++) {
14404 if (in.readInt() != 0) {
14405 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080014406 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014407 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014408 }
14409 }
14410
James Carr3a226052016-07-01 14:49:52 -070014411 mKernelMemoryStats.clear();
14412 int nmt = in.readInt();
14413 for (int imt = 0; imt < nmt; imt++) {
14414 if (in.readInt() != 0) {
14415 Long bucket = in.readLong();
14416 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
14417 mKernelMemoryStats.put(bucket, kmt);
14418 }
14419 }
14420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014421 mPartialTimers.clear();
14422 mFullTimers.clear();
14423 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014424 mWifiRunningTimers.clear();
14425 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070014426 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070014427 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014428 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070014429 mAudioTurnedOnTimers.clear();
14430 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014431 mFlashlightTurnedOnTimers.clear();
14432 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014433
14434 int numUids = in.readInt();
14435 mUidStats.clear();
14436 for (int i = 0; i < numUids; i++) {
14437 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080014438 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014439 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014440 mUidStats.append(uid, u);
14441 }
14442 }
14443
14444 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014445 writeToParcelLocked(out, true, flags);
14446 }
14447
14448 public void writeToParcelWithoutUids(Parcel out, int flags) {
14449 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014450 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014451
14452 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014453 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014454 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014455 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014456
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014457 // Pull the clock time. This may update the time and make a new history entry
14458 // if we had originally pulled a time before the RTC was set.
14459 long startClockTime = getStartClockTime();
14460
Joe Onoratoabded112016-02-08 16:49:39 -080014461 final long uSecUptime = mClocks.uptimeMillis() * 1000;
14462 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014463 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
14464 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014466 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014467
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070014468 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014470 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014471 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070014472 out.writeString(mStartPlatformVersion);
14473 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014474 out.writeLong(mUptime);
14475 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014476 out.writeLong(mRealtime);
14477 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014478 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070014479 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070014480 out.writeInt(mMinLearnedBatteryCapacity);
14481 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014482 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14483 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
14484
14485 mScreenOnTimer.writeToParcel(out, uSecRealtime);
Mike Mac2f518a2017-09-19 16:06:03 -070014486 mScreenDozeTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014487 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
14488 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
14489 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014490 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014491 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014492 out.writeLong(mLongestLightIdleTime);
14493 out.writeLong(mLongestFullIdleTime);
14494 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
14495 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
14496 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014497 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014498 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
14499 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
14500 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14501 }
14502 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
14503 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
14504 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
14505 }
14506 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
14507 mNetworkByteActivityCounters[i].writeToParcel(out);
14508 mNetworkPacketActivityCounters[i].writeToParcel(out);
14509 }
14510 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
14511 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014512 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014513 mMobileRadioActiveUnknownTime.writeToParcel(out);
14514 mMobileRadioActiveUnknownCount.writeToParcel(out);
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014515 mWifiMulticastWakelockTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014516 mWifiOnTimer.writeToParcel(out, uSecRealtime);
14517 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
14518 for (int i=0; i<NUM_WIFI_STATES; i++) {
14519 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
14520 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014521 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14522 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
14523 }
14524 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14525 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
14526 }
Siddharth Rayb50a6842017-12-14 15:15:28 -080014527 mWifiActiveTimer.writeToParcel(out, uSecRealtime);
14528 mWifiActivity.writeToParcel(out, 0);
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014529 for (int i=0; i< GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14530 mGpsSignalQualityTimer[i].writeToParcel(out, uSecRealtime);
14531 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080014532 mBluetoothActivity.writeToParcel(out, 0);
14533 mModemActivity.writeToParcel(out, 0);
14534 out.writeInt(mHasWifiReporting ? 1 : 0);
14535 out.writeInt(mHasBluetoothReporting ? 1 : 0);
14536 out.writeInt(mHasModemReporting ? 1 : 0);
14537
Dianne Hackborn1e01d162014-12-04 17:46:42 -080014538 out.writeInt(mNumConnectivityChange);
14539 out.writeInt(mLoadedNumConnectivityChange);
14540 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014541 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014542 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080014543 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070014544 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014545 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070014546 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014547 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014548 out.writeInt(mLowDischargeAmountSinceCharge);
14549 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080014550 out.writeInt(mDischargeAmountScreenOn);
14551 out.writeInt(mDischargeAmountScreenOnSinceCharge);
14552 out.writeInt(mDischargeAmountScreenOff);
14553 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Mike Mac2f518a2017-09-19 16:06:03 -070014554 out.writeInt(mDischargeAmountScreenDoze);
14555 out.writeInt(mDischargeAmountScreenDozeSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080014556 mDischargeStepTracker.writeToParcel(out);
14557 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070014558 mDischargeCounter.writeToParcel(out);
14559 mDischargeScreenOffCounter.writeToParcel(out);
Mike Mac2f518a2017-09-19 16:06:03 -070014560 mDischargeScreenDozeCounter.writeToParcel(out);
Mike Ma15313c92017-11-15 17:58:21 -080014561 mDischargeLightDozeCounter.writeToParcel(out);
14562 mDischargeDeepDozeCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014563 out.writeLong(mLastWriteTime);
14564
Bookatz50df7112017-08-04 14:53:26 -070014565 out.writeInt(mRpmStats.size());
14566 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
14567 SamplingTimer rpmt = ent.getValue();
14568 if (rpmt != null) {
14569 out.writeInt(1);
14570 out.writeString(ent.getKey());
14571 rpmt.writeToParcel(out, uSecRealtime);
14572 } else {
14573 out.writeInt(0);
14574 }
14575 }
14576 out.writeInt(mScreenOffRpmStats.size());
14577 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
14578 SamplingTimer rpmt = ent.getValue();
14579 if (rpmt != null) {
14580 out.writeInt(1);
14581 out.writeString(ent.getKey());
14582 rpmt.writeToParcel(out, uSecRealtime);
14583 } else {
14584 out.writeInt(0);
14585 }
14586 }
14587
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014588 if (inclUids) {
14589 out.writeInt(mKernelWakelockStats.size());
14590 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
14591 SamplingTimer kwlt = ent.getValue();
14592 if (kwlt != null) {
14593 out.writeInt(1);
14594 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014595 kwlt.writeToParcel(out, uSecRealtime);
14596 } else {
14597 out.writeInt(0);
14598 }
14599 }
14600 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014601 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
14602 SamplingTimer timer = ent.getValue();
14603 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014604 out.writeInt(1);
14605 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070014606 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014607 } else {
14608 out.writeInt(0);
14609 }
Evan Millarc64edde2009-04-18 12:26:32 -070014610 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014611 } else {
Bookatzba78b2b2017-10-10 11:06:33 -070014612 out.writeInt(0);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014613 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070014614 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070014615
James Carr3a226052016-07-01 14:49:52 -070014616 out.writeInt(mKernelMemoryStats.size());
14617 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
14618 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
14619 if (kmt != null) {
14620 out.writeInt(1);
14621 out.writeLong(mKernelMemoryStats.keyAt(i));
14622 kmt.writeToParcel(out, uSecRealtime);
14623 } else {
14624 out.writeInt(0);
14625 }
14626 }
14627
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014628 if (inclUids) {
14629 int size = mUidStats.size();
14630 out.writeInt(size);
14631 for (int i = 0; i < size; i++) {
14632 out.writeInt(mUidStats.keyAt(i));
14633 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014634
Bookatz867c0d72017-03-07 18:23:42 -080014635 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070014636 }
14637 } else {
14638 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014639 }
14640 }
14641
14642 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
14643 new Parcelable.Creator<BatteryStatsImpl>() {
14644 public BatteryStatsImpl createFromParcel(Parcel in) {
14645 return new BatteryStatsImpl(in);
14646 }
14647
14648 public BatteryStatsImpl[] newArray(int size) {
14649 return new BatteryStatsImpl[size];
14650 }
14651 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070014652
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014653 public void prepareForDumpLocked() {
14654 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080014655 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070014656
14657 // Pull the clock time. This may update the time and make a new history entry
14658 // if we had originally pulled a time before the RTC was set.
14659 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070014660 }
14661
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014662 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014663 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080014664 pw.println("mOnBatteryTimeBase:");
14665 mOnBatteryTimeBase.dump(pw, " ");
14666 pw.println("mOnBatteryScreenOffTimeBase:");
14667 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014668 Printer pr = new PrintWriterPrinter(pw);
Mike Mac2f518a2017-09-19 16:06:03 -070014669 pr.println("*** Screen on timer:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014670 mScreenOnTimer.logState(pr, " ");
Mike Mac2f518a2017-09-19 16:06:03 -070014671 pr.println("*** Screen doze timer:");
14672 mScreenDozeTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014673 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014674 pr.println("*** Screen brightness #" + i + ":");
14675 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070014676 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070014677 pr.println("*** Interactive timer:");
14678 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070014679 pr.println("*** Power save mode timer:");
14680 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070014681 pr.println("*** Device idle mode light timer:");
14682 mDeviceIdleModeLightTimer.logState(pr, " ");
14683 pr.println("*** Device idle mode full timer:");
14684 mDeviceIdleModeFullTimer.logState(pr, " ");
14685 pr.println("*** Device light idling timer:");
14686 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070014687 pr.println("*** Device idling timer:");
14688 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014689 pr.println("*** Phone timer:");
14690 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080014691 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070014692 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014693 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014694 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070014695 pr.println("*** Signal scanning :");
14696 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014697 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014698 pr.println("*** Data connection type #" + i + ":");
14699 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070014700 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070014701 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080014702 pr.println("*** Mobile network active timer:");
14703 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070014704 pr.println("*** Mobile network active adjusted timer:");
14705 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Ahmed ElArabawyf88571f2017-11-28 12:18:10 -080014706 pr.println("*** Wifi Multicast WakeLock Timer:");
14707 mWifiMulticastWakelockTimer.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070014708 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070014709 pr.println("*** Wifi timer:");
14710 mWifiOnTimer.logState(pr, " ");
14711 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070014712 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080014713 for (int i=0; i<NUM_WIFI_STATES; i++) {
14714 pr.println("*** Wifi state #" + i + ":");
14715 mWifiStateTimer[i].logState(pr, " ");
14716 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070014717 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
14718 pr.println("*** Wifi suppl state #" + i + ":");
14719 mWifiSupplStateTimer[i].logState(pr, " ");
14720 }
14721 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
14722 pr.println("*** Wifi signal strength #" + i + ":");
14723 mWifiSignalStrengthsTimer[i].logState(pr, " ");
14724 }
Siddharth Ray78ccaf52017-12-23 16:16:21 -080014725 for (int i=0; i<GnssMetrics.NUM_GPS_SIGNAL_QUALITY_LEVELS; i++) {
14726 pr.println("*** GPS signal quality #" + i + ":");
14727 mGpsSignalQualityTimer[i].logState(pr, " ");
14728 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070014729 pr.println("*** Flashlight timer:");
14730 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070014731 pr.println("*** Camera timer:");
14732 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014733 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080014734 super.dumpLocked(context, pw, flags, reqUid, histStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014736}