blob: 90455f643f35c29290cb24f1decaeca89a74a903 [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;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080024import android.content.Context;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070025import android.content.Intent;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070026import android.net.ConnectivityManager;
27import android.net.NetworkStats;
Adam Lesinski33dac552015-03-09 15:24:48 -070028import android.net.wifi.WifiActivityEnergyInfo;
Dianne Hackborn3251b902014-06-20 14:40:53 -070029import android.net.wifi.WifiManager;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070030import android.os.BatteryManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.os.BatteryStats;
Dianne Hackborncd0e3352014-08-07 17:08:09 -070032import android.os.Build;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070033import android.os.FileUtils;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070034import android.os.Handler;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080035import android.os.IBatteryPropertiesRegistrar;
Jeff Brown6f357d32014-01-15 20:40:55 -080036import android.os.Looper;
Dianne Hackborn0d903a82010-09-07 23:51:03 -070037import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.os.Parcel;
39import android.os.ParcelFormatException;
40import android.os.Parcelable;
Evan Millarc64edde2009-04-18 12:26:32 -070041import android.os.Process;
Adam Lesinskie1f480d2017-02-15 18:51:23 -080042import android.os.RemoteException;
43import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.os.SystemClock;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070045import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070046import android.os.WorkSource;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070047import android.telephony.DataConnectionRealTimeInfo;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080048import android.telephony.ModemActivityInfo;
Amith Yamasanif37447b2009-10-08 18:28:01 -070049import android.telephony.ServiceState;
Wink Savillee9b06d72009-05-18 21:47:50 -070050import android.telephony.SignalStrength;
Dianne Hackborn627bba72009-03-24 22:32:56 -070051import android.telephony.TelephonyManager;
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -070052import android.text.TextUtils;
Dianne Hackborn61659e52014-07-09 16:13:01 -070053import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.util.Log;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070055import android.util.LogWriter;
James Carr3a226052016-07-01 14:49:52 -070056import android.util.LongSparseArray;
57import android.util.LongSparseLongArray;
Dianne Hackbornd953c532014-08-16 18:17:38 -070058import android.util.MutableInt;
Adam Lesinski14ae39a2017-05-26 11:50:40 -070059import android.util.Pools;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070060import android.util.PrintWriterPrinter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.util.Printer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070062import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.util.SparseArray;
Dianne Hackborn099bc622014-01-22 13:39:16 -080064import android.util.SparseIntArray;
Adam Lesinskie08af192015-03-25 16:42:59 -070065import android.util.SparseLongArray;
Dianne Hackbornae384452011-06-28 12:33:48 -070066import android.util.TimeUtils;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080067import android.util.Xml;
Jeff Browne95c3cd2014-05-02 16:59:26 -070068import android.view.Display;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069
Adam Lesinski14ae39a2017-05-26 11:50:40 -070070import com.android.internal.annotations.GuardedBy;
Adam Lesinski98f0d462016-04-19 16:46:20 -070071import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070072import com.android.internal.net.NetworkStatsFactory;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080073import com.android.internal.util.ArrayUtils;
Dianne Hackborn8c841092013-06-24 13:46:13 -070074import com.android.internal.util.FastPrintWriter;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080075import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070076import com.android.internal.util.JournaledFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080077import com.android.internal.util.XmlUtils;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070078
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070079import libcore.util.EmptyArray;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080080import org.xmlpull.v1.XmlPullParser;
81import org.xmlpull.v1.XmlPullParserException;
82import org.xmlpull.v1.XmlSerializer;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070083
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080084import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import java.io.File;
86import java.io.FileInputStream;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080087import java.io.FileNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import java.io.FileOutputStream;
89import java.io.IOException;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070090import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010091import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import java.util.ArrayList;
Sudheer Shanka9b735c52017-05-09 18:26:18 -070093import java.util.Arrays;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080094import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.util.HashMap;
Evan Millarc64edde2009-04-18 12:26:32 -070096import java.util.Iterator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import java.util.Map;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -070098import java.util.concurrent.Future;
Christopher Tate4cee7252010-03-19 14:50:40 -070099import java.util.concurrent.atomic.AtomicInteger;
Dianne Hackbornce2ef762010-09-20 11:39:14 -0700100import java.util.concurrent.locks.ReentrantLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
102/**
103 * All information we are collecting about things that can happen that impact
104 * battery life. All times are represented in microseconds except where indicated
105 * otherwise.
106 */
Joe Onoratoabded112016-02-08 16:49:39 -0800107public class BatteryStatsImpl extends BatteryStats {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 private static final String TAG = "BatteryStatsImpl";
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800109 private static final boolean DEBUG = false;
Adam Lesinskia7c90c82015-06-18 14:52:24 -0700110 public static final boolean DEBUG_ENERGY = false;
Adam Lesinski50e47602015-12-04 17:04:54 -0800111 private static final boolean DEBUG_ENERGY_CPU = DEBUG_ENERGY;
James Carr3a226052016-07-01 14:49:52 -0700112 private static final boolean DEBUG_MEMORY = false;
Dianne Hackborn32907cf2010-06-10 17:50:20 -0700113 private static final boolean DEBUG_HISTORY = false;
Dianne Hackborne8c88e62011-08-17 19:09:09 -0700114 private static final boolean USE_OLD_HISTORY = false; // for debugging.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700115
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700116 // TODO: remove "tcp" from network methods, since we measure total stats.
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 // In-memory Parcel magic number, used to detect attempts to unmarshall bad data
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700119 private static final int MAGIC = 0xBA757475; // 'BATSTATS'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
121 // Current on-disk Parcel version
Bookatz50df7112017-08-04 14:53:26 -0700122 private static final int VERSION = 166 + (USE_OLD_HISTORY ? 1000 : 0);
Amith Yamasanie43530a2009-08-21 13:11:37 -0700123
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700124 // Maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100125 private static final int MAX_HISTORY_ITEMS;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700126
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700127 // No, really, THIS is the maximum number of items we will record in the history.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100128 private static final int MAX_MAX_HISTORY_ITEMS;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -0700129
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800130 // The maximum number of names wakelocks we will keep track of
131 // per uid; once the limit is reached, we batch the remaining wakelocks
132 // in to one common name.
Narayan Kamathb59b7c32017-06-12 14:11:03 +0100133 private static final int MAX_WAKELOCKS_PER_UID;
134
135 static final int MAX_HISTORY_BUFFER; // 256KB
136 static final int MAX_MAX_HISTORY_BUFFER; // 320KB
137
138 static {
139 if (ActivityManager.isLowRamDeviceStatic()) {
140 MAX_HISTORY_ITEMS = 800;
141 MAX_MAX_HISTORY_ITEMS = 1200;
142 MAX_WAKELOCKS_PER_UID = 40;
143 MAX_HISTORY_BUFFER = 96*1024; // 96KB
144 MAX_MAX_HISTORY_BUFFER = 128*1024; // 128KB
145 } else {
146 MAX_HISTORY_ITEMS = 2000;
147 MAX_MAX_HISTORY_ITEMS = 3000;
148 MAX_WAKELOCKS_PER_UID = 100;
149 MAX_HISTORY_BUFFER = 256*1024; // 256KB
150 MAX_MAX_HISTORY_BUFFER = 320*1024; // 256KB
151 }
152 }
Dianne Hackbornc24ab862011-10-18 15:55:03 -0700153
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800154 // Number of transmit power states the Wifi controller can be in.
155 private static final int NUM_WIFI_TX_LEVELS = 1;
156
157 // Number of transmit power states the Bluetooth controller can be in.
158 private static final int NUM_BT_TX_LEVELS = 1;
159
Joe Onoratoabded112016-02-08 16:49:39 -0800160 protected Clocks mClocks;
161
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700162 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700163 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800164 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700166 static final int MSG_UPDATE_WAKELOCKS = 1;
167 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700168 static final int MSG_REPORT_CHARGING = 3;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700169 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700170
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700171 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
172 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
173
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700174 private final KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
Adam Lesinski6832f392015-09-05 18:05:40 -0700175 private KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700176 private final KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
177 new KernelUidCpuFreqTimeReader();
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700178
James Carr3a226052016-07-01 14:49:52 -0700179 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
180 = new KernelMemoryBandwidthStats();
181 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
182 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
183 return mKernelMemoryStats;
184 }
185
Bookatz50df7112017-08-04 14:53:26 -0700186 /** Temporary container for Resource Power Manager stats. */
187 private final RpmStats mTmpRpmStats = new RpmStats();
188
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700189 public interface BatteryCallback {
190 public void batteryNeedsCpuUpdate();
191 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700192 public void batterySendBroadcast(Intent intent);
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700193 }
194
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700195 public interface PlatformIdleStateCallback {
Bookatz50df7112017-08-04 14:53:26 -0700196 public void fillLowPowerStats(RpmStats rpmStats);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700197 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000198 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700199 }
200
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700201 public static abstract class UserInfoProvider {
202 private int[] userIds;
203 protected abstract @Nullable int[] getUserIds();
204 private final void refreshUserIds() {
205 userIds = getUserIds();
206 }
207 private final boolean exists(int userId) {
208 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
209 }
210 }
211
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700212 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
213
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700214 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800215 public MyHandler(Looper looper) {
216 super(looper, null, true);
217 }
218
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700219 @Override
220 public void handleMessage(Message msg) {
221 BatteryCallback cb = mCallback;
222 switch (msg.what) {
223 case MSG_UPDATE_WAKELOCKS:
Adam Lesinski72478f02015-06-17 15:39:43 -0700224 synchronized (BatteryStatsImpl.this) {
Sudheer Shanka671985f2017-05-19 11:33:42 -0700225 updateCpuTimeLocked(false /* updateCpuFreqData */);
Adam Lesinski72478f02015-06-17 15:39:43 -0700226 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700227 if (cb != null) {
228 cb.batteryNeedsCpuUpdate();
229 }
230 break;
231 case MSG_REPORT_POWER_CHANGE:
232 if (cb != null) {
233 cb.batteryPowerChanged(msg.arg1 != 0);
234 }
235 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700236 case MSG_REPORT_CHARGING:
237 if (cb != null) {
238 final String action;
239 synchronized (BatteryStatsImpl.this) {
240 action = mCharging ? BatteryManager.ACTION_CHARGING
241 : BatteryManager.ACTION_DISCHARGING;
242 }
243 Intent intent = new Intent(action);
244 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
245 cb.batterySendBroadcast(intent);
246 }
247 break;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700248 }
249 }
250 }
251
Joe Onoratoabded112016-02-08 16:49:39 -0800252 public interface Clocks {
253 public long elapsedRealtime();
254 public long uptimeMillis();
255 }
256
257 public static class SystemClocks implements Clocks {
258 public long elapsedRealtime() {
259 return SystemClock.elapsedRealtime();
260 }
261
262 public long uptimeMillis() {
263 return SystemClock.uptimeMillis();
264 }
265 }
266
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700267 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700268 int UPDATE_CPU = 0x01;
269 int UPDATE_WIFI = 0x02;
270 int UPDATE_RADIO = 0x04;
271 int UPDATE_BT = 0x08;
Bookatz50df7112017-08-04 14:53:26 -0700272 int UPDATE_RPM = 0x10; // 16
273 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT | UPDATE_RPM;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800274
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700275 Future<?> scheduleSync(String reason, int flags);
276 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700277 }
278
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700279 public final MyHandler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700280 private ExternalStatsSync mExternalSync = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700281 private UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700282
283 private BatteryCallback mCallback;
284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800286 * Mapping isolated uids to the actual owning app uid.
287 */
288 final SparseIntArray mIsolatedUids = new SparseIntArray();
289
290 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 * The statistics we have collected organized by uids.
292 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800293 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
295 // A set of pools of currently active timers. When a timer is queried, we will divide the
296 // elapsed time by the number of active timers to arrive at that timer's share of the time.
297 // In order to do this, we must refresh each timer whenever the number of active timers
298 // changes.
Adam Lesinskie08af192015-03-25 16:42:59 -0700299 final ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
300 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
301 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700302 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700303 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
304 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
305 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
306 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
307 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
308 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
309 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
310 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700311 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
312 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800313 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700315 // Last partial timers we use for distributing CPU usage.
Adam Lesinskie08af192015-03-25 16:42:59 -0700316 final ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 // These are the objects that will want to do something when the device
319 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800320 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800321
322 // These are the objects that will want to do something when the device
323 // is unplugged from power *and* the screen is off.
324 final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
325
326 // Set to true when we want to distribute CPU across wakelocks for the next
327 // CPU update, even if we aren't currently running wake locks.
328 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700329
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700330 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700331
Dianne Hackborn37de0982014-05-09 09:32:18 -0700332 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800333
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700334 long mHistoryBaseTime;
335 boolean mHaveBatteryLevel = false;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700336 boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700337 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700338
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700339 final Parcel mHistoryBuffer = Parcel.obtain();
340 final HistoryItem mHistoryLastWritten = new HistoryItem();
341 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700342 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700343 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700344 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800345 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800346 int[] mReadHistoryUids;
347 int mReadHistoryChars;
348 int mNextHistoryTagIdx = 0;
349 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700350 int mHistoryBufferLastPos = -1;
351 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700352 int mActiveHistoryStates = 0xffffffff;
353 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700354 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700355 long mTrackRunningHistoryElapsedRealtime = 0;
356 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700357
358 final HistoryItem mHistoryCur = new HistoryItem();
359
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700360 HistoryItem mHistory;
361 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700362 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700363 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700364
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800365 // Used by computeHistoryStepDetails
366 HistoryStepDetails mLastHistoryStepDetails = null;
367 byte mLastHistoryStepLevel = 0;
368 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
369 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
370 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700371
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800372 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700373 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800374 */
375 long mLastStepCpuUserTime;
376 long mCurStepCpuUserTime;
377 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700378 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800379 */
380 long mLastStepCpuSystemTime;
381 long mCurStepCpuSystemTime;
382 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700383 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800384 */
385 long mLastStepStatUserTime;
386 long mLastStepStatSystemTime;
387 long mLastStepStatIOWaitTime;
388 long mLastStepStatIrqTime;
389 long mLastStepStatSoftIrqTime;
390 long mLastStepStatIdleTime;
391 long mCurStepStatUserTime;
392 long mCurStepStatSystemTime;
393 long mCurStepStatIOWaitTime;
394 long mCurStepStatIrqTime;
395 long mCurStepStatSoftIrqTime;
396 long mCurStepStatIdleTime;
397
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700398 private HistoryItem mHistoryIterator;
399 private boolean mReadOverflow;
400 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 int mStartCount;
403
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800404 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700405 String mStartPlatformVersion;
406 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408 long mUptime;
409 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 long mRealtime;
411 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700412
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800413 int mWakeLockNesting;
414 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700415 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700416 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800417
Jeff Browne95c3cd2014-05-02 16:59:26 -0700418 int mScreenState = Display.STATE_UNKNOWN;
Evan Millarc64edde2009-04-18 12:26:32 -0700419 StopwatchTimer mScreenOnTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700420
Dianne Hackborn617f8772009-03-31 15:04:46 -0700421 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700422 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700423
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800424 boolean mPretendScreenOff;
425
Jeff Browne95c3cd2014-05-02 16:59:26 -0700426 boolean mInteractive;
427 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700428
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700429 boolean mPowerSaveModeEnabled;
430 StopwatchTimer mPowerSaveModeEnabledTimer;
431
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700432 boolean mDeviceIdling;
433 StopwatchTimer mDeviceIdlingTimer;
434
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700435 boolean mDeviceLightIdling;
436 StopwatchTimer mDeviceLightIdlingTimer;
437
438 int mDeviceIdleMode;
439 long mLastIdleTimeStart;
440 long mLongestLightIdleTime;
441 long mLongestFullIdleTime;
442 StopwatchTimer mDeviceIdleModeLightTimer;
443 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700446 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700447
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700448 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700449 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700450
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700451 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700452 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700453
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700454 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700455 StopwatchTimer mFlashlightOnTimer;
456
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700457 int mCameraOnNesting;
458 StopwatchTimer mCameraOnTimer;
459
Dianne Hackborn627bba72009-03-24 22:32:56 -0700460 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800461 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700462 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800463 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700464
465 StopwatchTimer mPhoneSignalScanningTimer;
466
Dianne Hackborn627bba72009-03-24 22:32:56 -0700467 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700468 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700469 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700470
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800471 final LongSamplingCounter[] mNetworkByteActivityCounters =
472 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
473 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700474 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
475
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800476 /**
477 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
478 */
479 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700480
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800481 /**
482 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
483 */
484 ControllerActivityCounterImpl mBluetoothActivity;
485
486 /**
487 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
488 */
489 ControllerActivityCounterImpl mModemActivity;
490
491 /**
492 * Whether the device supports WiFi controller energy reporting. This is set to true on
493 * the first WiFi energy report. See {@link #mWifiActivity}.
494 */
495 boolean mHasWifiReporting = false;
496
497 /**
498 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
499 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
500 */
501 boolean mHasBluetoothReporting = false;
502
503 /**
504 * Whether the device supports Modem controller energy reporting. This is set to true on
505 * the first Modem energy report. See {@link #mModemActivity}.
506 */
507 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700508
The Android Open Source Project10592532009-03-18 17:39:46 -0700509 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700510 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700511
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700512 boolean mGlobalWifiRunning;
513 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700514
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800515 int mWifiState = -1;
516 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
517
Dianne Hackborn3251b902014-06-20 14:40:53 -0700518 int mWifiSupplState = -1;
519 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
520
521 int mWifiSignalStrengthBin = -1;
522 final StopwatchTimer[] mWifiSignalStrengthsTimer =
523 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
524
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800525 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800526 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
527 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800528
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700529 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700530 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800531 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800532 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700533 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800534 LongSamplingCounter mMobileRadioActiveUnknownTime;
535 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800536
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700537 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 /**
540 * These provide time bases that discount the time the device is plugged
541 * in to power.
542 */
543 boolean mOnBattery;
544 boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700545
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700546 /**
547 * External reporting of whether the device is actually charging.
548 */
549 boolean mCharging = true;
550 int mLastChargingStateLevel;
551
The Android Open Source Project10592532009-03-18 17:39:46 -0700552 /*
553 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
554 */
Evan Millar633a1742009-04-02 16:36:33 -0700555 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700556 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700557 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700558 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700559 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700560 int mLowDischargeAmountSinceCharge;
561 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800562 int mDischargeScreenOnUnplugLevel;
563 int mDischargeScreenOffUnplugLevel;
564 int mDischargeAmountScreenOn;
565 int mDischargeAmountScreenOnSinceCharge;
566 int mDischargeAmountScreenOff;
567 int mDischargeAmountScreenOffSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700568
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700569 private LongSamplingCounter mDischargeScreenOffCounter;
570 private LongSamplingCounter mDischargeCounter;
571
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700572 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700573
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700574 int mInitStepMode = 0;
575 int mCurStepMode = 0;
576 int mModStepMode = 0;
577
Dianne Hackborn260c5022014-04-29 11:23:16 -0700578 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700579 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800580 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
581 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700582 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700583
584 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700585 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800586 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
587 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
588
589 static final int MAX_DAILY_ITEMS = 10;
590
591 long mDailyStartTime = 0;
592 long mNextMinDailyDeadline = 0;
593 long mNextMaxDailyDeadline = 0;
594
595 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700598
Amith Yamasanif37447b2009-10-08 18:28:01 -0700599 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800600 private int mPhoneServiceStateRaw = -1;
601 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700602
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800603 private int mNumConnectivityChange;
604 private int mLoadedNumConnectivityChange;
605 private int mUnpluggedNumConnectivityChange;
606
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700607 private int mEstimatedBatteryCapacity = -1;
608
Jocelyn Dangc627d102017-04-14 13:15:14 -0700609 private int mMinLearnedBatteryCapacity = -1;
610 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800611
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700612 private long[] mCpuFreqs;
613
Adam Lesinskie08af192015-03-25 16:42:59 -0700614 private PowerProfile mPowerProfile;
615
Evan Millarc64edde2009-04-18 12:26:32 -0700616 /*
Bookatz50df7112017-08-04 14:53:26 -0700617 * Holds a SamplingTimer associated with each Resource Power Manager state and voter,
618 * recording their times when on-battery (regardless of screen state).
619 */
620 private final HashMap<String, SamplingTimer> mRpmStats = new HashMap<>();
621 /** Times for each Resource Power Manager state and voter when screen-off and on-battery. */
622 private final HashMap<String, SamplingTimer> mScreenOffRpmStats = new HashMap<>();
623
624 @Override
625 public Map<String, ? extends Timer> getRpmStats() {
626 return mRpmStats;
627 }
628
629 @Override
630 public Map<String, ? extends Timer> getScreenOffRpmStats() {
631 return mScreenOffRpmStats;
632 }
633
634 /*
Evan Millarc64edde2009-04-18 12:26:32 -0700635 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
636 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700637 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700638
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700639 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700640 return mKernelWakelockStats;
641 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700642
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700643 String mLastWakeupReason = null;
644 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700645 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700646
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700647 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700648 return mWakeupReasonStats;
649 }
650
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700651 @Override
652 public LongCounter getDischargeScreenOffCoulombCounter() {
653 return mDischargeScreenOffCounter;
654 }
655
656 @Override
657 public LongCounter getDischargeCoulombCounter() {
658 return mDischargeCounter;
659 }
660
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700661 @Override
662 public int getEstimatedBatteryCapacity() {
663 return mEstimatedBatteryCapacity;
664 }
665
Jocelyn Dangc627d102017-04-14 13:15:14 -0700666 @Override
667 public int getMinLearnedBatteryCapacity() {
668 return mMinLearnedBatteryCapacity;
669 }
670
671 @Override
672 public int getMaxLearnedBatteryCapacity() {
673 return mMaxLearnedBatteryCapacity;
674 }
675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -0800677 this(new SystemClocks());
678 }
679
680 public BatteryStatsImpl(Clocks clocks) {
681 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700682 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700683 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800684 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700685 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700686 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700687 mUserInfoProvider = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700688 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 }
690
Joe Onoratoabded112016-02-08 16:49:39 -0800691 private void init(Clocks clocks) {
692 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -0800693 }
694
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700695 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800696 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
697 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
698 }
699
Joe Onoratoabded112016-02-08 16:49:39 -0800700 // methods are protected not private to be VisibleForTesting
701 public static class TimeBase {
702 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800703
Joe Onoratoabded112016-02-08 16:49:39 -0800704 protected long mUptime;
705 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800706
Joe Onoratoabded112016-02-08 16:49:39 -0800707 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800708
Joe Onoratoabded112016-02-08 16:49:39 -0800709 protected long mPastUptime;
710 protected long mUptimeStart;
711 protected long mPastRealtime;
712 protected long mRealtimeStart;
713 protected long mUnpluggedUptime;
714 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800715
716 public void dump(PrintWriter pw, String prefix) {
717 StringBuilder sb = new StringBuilder(128);
718 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
719 sb.setLength(0);
720 sb.append(prefix);
721 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700722 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800723 pw.println(sb.toString());
724 sb.setLength(0);
725 sb.append(prefix);
726 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700727 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800728 pw.println(sb.toString());
729 sb.setLength(0);
730 sb.append(prefix);
731 sb.append("mPastUptime=");
732 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
733 formatTimeMs(sb, mUptimeStart / 1000);
734 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
735 pw.println(sb.toString());
736 sb.setLength(0);
737 sb.append(prefix);
738 sb.append("mPastRealtime=");
739 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
740 formatTimeMs(sb, mRealtimeStart / 1000);
741 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
742 pw.println(sb.toString());
743 }
744
745 public void add(TimeBaseObs observer) {
746 mObservers.add(observer);
747 }
748
749 public void remove(TimeBaseObs observer) {
750 if (!mObservers.remove(observer)) {
751 Slog.wtf(TAG, "Removed unknown observer: " + observer);
752 }
753 }
754
Joe Onoratoabded112016-02-08 16:49:39 -0800755 public boolean hasObserver(TimeBaseObs observer) {
756 return mObservers.contains(observer);
757 }
758
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800759 public void init(long uptime, long realtime) {
760 mRealtime = 0;
761 mUptime = 0;
762 mPastUptime = 0;
763 mPastRealtime = 0;
764 mUptimeStart = uptime;
765 mRealtimeStart = realtime;
766 mUnpluggedUptime = getUptime(mUptimeStart);
767 mUnpluggedRealtime = getRealtime(mRealtimeStart);
768 }
769
770 public void reset(long uptime, long realtime) {
771 if (!mRunning) {
772 mPastUptime = 0;
773 mPastRealtime = 0;
774 } else {
775 mUptimeStart = uptime;
776 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -0800777 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
778 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800779 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -0800780 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800781 mUnpluggedRealtime = getRealtime(realtime);
782 }
783 }
784
785 public long computeUptime(long curTime, int which) {
786 switch (which) {
787 case STATS_SINCE_CHARGED:
788 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800789 case STATS_CURRENT:
790 return getUptime(curTime);
791 case STATS_SINCE_UNPLUGGED:
792 return getUptime(curTime) - mUnpluggedUptime;
793 }
794 return 0;
795 }
796
797 public long computeRealtime(long curTime, int which) {
798 switch (which) {
799 case STATS_SINCE_CHARGED:
800 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800801 case STATS_CURRENT:
802 return getRealtime(curTime);
803 case STATS_SINCE_UNPLUGGED:
804 return getRealtime(curTime) - mUnpluggedRealtime;
805 }
806 return 0;
807 }
808
809 public long getUptime(long curTime) {
810 long time = mPastUptime;
811 if (mRunning) {
812 time += curTime - mUptimeStart;
813 }
814 return time;
815 }
816
817 public long getRealtime(long curTime) {
818 long time = mPastRealtime;
819 if (mRunning) {
820 time += curTime - mRealtimeStart;
821 }
822 return time;
823 }
824
825 public long getUptimeStart() {
826 return mUptimeStart;
827 }
828
829 public long getRealtimeStart() {
830 return mRealtimeStart;
831 }
832
833 public boolean isRunning() {
834 return mRunning;
835 }
836
837 public boolean setRunning(boolean running, long uptime, long realtime) {
838 if (mRunning != running) {
839 mRunning = running;
840 if (running) {
841 mUptimeStart = uptime;
842 mRealtimeStart = realtime;
843 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
844 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
845
846 for (int i = mObservers.size() - 1; i >= 0; i--) {
847 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
848 }
849 } else {
850 mPastUptime += uptime - mUptimeStart;
851 mPastRealtime += realtime - mRealtimeStart;
852
853 long batteryUptime = getUptime(uptime);
854 long batteryRealtime = getRealtime(realtime);
855
856 for (int i = mObservers.size() - 1; i >= 0; i--) {
857 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
858 }
859 }
860 return true;
861 }
862 return false;
863 }
864
865 public void readSummaryFromParcel(Parcel in) {
866 mUptime = in.readLong();
867 mRealtime = in.readLong();
868 }
869
870 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
871 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
872 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
873 }
874
875 public void readFromParcel(Parcel in) {
876 mRunning = false;
877 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800878 mPastUptime = in.readLong();
879 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -0700880 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800881 mPastRealtime = in.readLong();
882 mRealtimeStart = in.readLong();
883 mUnpluggedUptime = in.readLong();
884 mUnpluggedRealtime = in.readLong();
885 }
886
887 public void writeToParcel(Parcel out, long uptime, long realtime) {
888 final long runningUptime = getUptime(uptime);
889 final long runningRealtime = getRealtime(realtime);
890 out.writeLong(mUptime);
891 out.writeLong(runningUptime);
892 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -0700893 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800894 out.writeLong(runningRealtime);
895 out.writeLong(mRealtimeStart);
896 out.writeLong(mUnpluggedUptime);
897 out.writeLong(mUnpluggedRealtime);
898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -0700902 * State for keeping track of counting information.
903 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800904 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -0700905 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800906 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700907 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700908 int mUnpluggedCount;
909 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700910
Bookatz8c6f3c52017-05-24 12:00:17 -0700911 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800912 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -0700913 mPluggedCount = in.readInt();
914 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700915 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700916 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800917 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700918 }
919
Bookatz8c6f3c52017-05-24 12:00:17 -0700920 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800921 mTimeBase = timeBase;
922 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700923 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700924
Dianne Hackborn617f8772009-03-31 15:04:46 -0700925 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700926 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700927 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700928 out.writeInt(mUnpluggedCount);
929 }
930
Bookatz8c6f3c52017-05-24 12:00:17 -0700931 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800932 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700933 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700934 }
935
Bookatz8c6f3c52017-05-24 12:00:17 -0700936 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800937 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700938 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700939 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700940
Dianne Hackborn617f8772009-03-31 15:04:46 -0700941 /**
942 * Writes a possibly null Counter to a Parcel.
943 *
944 * @param out the Parcel to be written to.
945 * @param counter a Counter, or null.
946 */
947 public static void writeCounterToParcel(Parcel out, Counter counter) {
948 if (counter == null) {
949 out.writeInt(0); // indicates null
950 return;
951 }
952 out.writeInt(1); // indicates non-null
953
954 counter.writeToParcel(out);
955 }
956
957 @Override
Evan Millarc64edde2009-04-18 12:26:32 -0700958 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -0700959 int val = mCount.get();
960 if (which == STATS_SINCE_UNPLUGGED) {
961 val -= mUnpluggedCount;
962 } else if (which != STATS_SINCE_CHARGED) {
963 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700964 }
965
966 return val;
967 }
968
969 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700970 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -0700971 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -0700972 + " mUnpluggedCount=" + mUnpluggedCount
973 + " mPluggedCount=" + mPluggedCount);
974 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700975
Bookatz8c6f3c52017-05-24 12:00:17 -0700976 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
977 public void stepAtomic() {
978 if (mTimeBase.isRunning()) {
979 mCount.incrementAndGet();
980 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700981 }
982
Bookatz4ebc0642017-05-11 12:21:19 -0700983 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -0700984 if (mTimeBase.isRunning()) {
985 mCount.addAndGet(delta);
986 }
Bookatz4ebc0642017-05-11 12:21:19 -0700987 }
988
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700989 /**
990 * Clear state of this counter.
991 */
992 void reset(boolean detachIfReset) {
993 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -0700994 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700995 if (detachIfReset) {
996 detach();
997 }
998 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700999
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001000 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001001 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001002 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001003
Bookatz8c6f3c52017-05-24 12:00:17 -07001004 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1005 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001006 int count = mCount.get();
1007 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001008 }
1009
Bookatz8c6f3c52017-05-24 12:00:17 -07001010 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1011 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001012 mLoadedCount = in.readInt();
1013 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001014 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001015 }
1016 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001017
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001018 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001019 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1020 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001021 public long[] mCounts;
1022 public long[] mLoadedCounts;
1023 public long[] mUnpluggedCounts;
1024 public long[] mPluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001025
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001026 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001027 mTimeBase = timeBase;
1028 mPluggedCounts = in.createLongArray();
1029 mCounts = copyArray(mPluggedCounts, mCounts);
1030 mLoadedCounts = in.createLongArray();
1031 mUnpluggedCounts = in.createLongArray();
1032 timeBase.add(this);
1033 }
1034
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001035 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001036 mTimeBase = timeBase;
1037 timeBase.add(this);
1038 }
1039
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001040 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001041 out.writeLongArray(mCounts);
1042 out.writeLongArray(mLoadedCounts);
1043 out.writeLongArray(mUnpluggedCounts);
1044 }
1045
1046 @Override
1047 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
1048 mUnpluggedCounts = copyArray(mPluggedCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001049 }
1050
1051 @Override
1052 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1053 mPluggedCounts = copyArray(mCounts, mPluggedCounts);
1054 }
1055
1056 @Override
1057 public long[] getCountsLocked(int which) {
1058 long[] val = copyArray(mTimeBase.isRunning() ? mCounts : mPluggedCounts, null);
1059 if (which == STATS_SINCE_UNPLUGGED) {
1060 subtract(val, mUnpluggedCounts);
1061 } else if (which != STATS_SINCE_CHARGED) {
1062 subtract(val, mLoadedCounts);
1063 }
1064 return val;
1065 }
1066
1067 @Override
1068 public void logState(Printer pw, String prefix) {
1069 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1070 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
1071 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts)
1072 + " mPluggedCounts=" + Arrays.toString(mPluggedCounts));
1073 }
1074
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001075 public void addCountLocked(long[] counts) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001076 if (counts == null) {
1077 return;
1078 }
Bookatz8c6f3c52017-05-24 12:00:17 -07001079 if (mTimeBase.isRunning()) {
1080 if (mCounts == null) {
1081 mCounts = new long[counts.length];
1082 }
1083 for (int i = 0; i < counts.length; ++i) {
1084 mCounts[i] += counts[i];
1085 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001086 }
1087 }
1088
Sudheer Shankaa87245d2017-08-10 12:02:31 -07001089 public int getSize() {
1090 return mCounts == null ? 0 : mCounts.length;
1091 }
1092
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001093 /**
1094 * Clear state of this counter.
1095 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001096 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001097 fillArray(mCounts, 0);
1098 fillArray(mLoadedCounts, 0);
1099 fillArray(mPluggedCounts, 0);
1100 fillArray(mUnpluggedCounts, 0);
1101 if (detachIfReset) {
1102 detach();
1103 }
1104 }
1105
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001106 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001107 mTimeBase.remove(this);
1108 }
1109
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001110 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001111 out.writeLongArray(mCounts);
1112 }
1113
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001114 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001115 mCounts = in.createLongArray();
1116 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1117 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
1118 mPluggedCounts = copyArray(mCounts, mPluggedCounts);
1119 }
1120
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001121 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1122 if (counterArray != null) {
1123 out.writeInt(1);
1124 counterArray.writeToParcel(out);
1125 } else {
1126 out.writeInt(0);
1127 }
1128 }
1129
1130 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1131 if (in.readInt() != 0) {
1132 return new LongSamplingCounterArray(timeBase, in);
1133 } else {
1134 return null;
1135 }
1136 }
1137
1138 public static void writeSummaryToParcelLocked(Parcel out,
1139 LongSamplingCounterArray counterArray) {
1140 if (counterArray != null) {
1141 out.writeInt(1);
1142 counterArray.writeSummaryToParcelLocked(out);
1143 } else {
1144 out.writeInt(0);
1145 }
1146 }
1147
1148 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1149 TimeBase timeBase) {
1150 if (in.readInt() != 0) {
1151 final LongSamplingCounterArray counterArray
1152 = new LongSamplingCounterArray(timeBase);
1153 counterArray.readSummaryFromParcelLocked(in);
1154 return counterArray;
1155 } else {
1156 return null;
1157 }
1158 }
1159
Bookatz8c6f3c52017-05-24 12:00:17 -07001160 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001161 if (a != null) {
1162 Arrays.fill(a, val);
1163 }
1164 }
1165
Bookatz8c6f3c52017-05-24 12:00:17 -07001166 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001167 if (toSubtract == null) {
1168 return;
1169 }
1170 for (int i = 0; i < val.length; i++) {
1171 val[i] -= toSubtract[i];
1172 }
1173 }
1174
Bookatz8c6f3c52017-05-24 12:00:17 -07001175 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001176 if (src == null) {
1177 return null;
1178 } else {
1179 if (dest == null) {
1180 dest = new long[src.length];
1181 }
1182 System.arraycopy(src, 0, dest, 0, src.length);
1183 return dest;
1184 }
1185 }
1186 }
1187
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001188 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001189 final TimeBase mTimeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001190 long mCount;
1191 long mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001192 long mUnpluggedCount;
1193 long mPluggedCount;
1194
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001195 LongSamplingCounter(TimeBase timeBase, Parcel in) {
1196 mTimeBase = timeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001197 mPluggedCount = in.readLong();
1198 mCount = mPluggedCount;
1199 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001200 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001201 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001202 }
1203
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001204 LongSamplingCounter(TimeBase timeBase) {
1205 mTimeBase = timeBase;
1206 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001207 }
1208
1209 public void writeToParcel(Parcel out) {
1210 out.writeLong(mCount);
1211 out.writeLong(mLoadedCount);
1212 out.writeLong(mUnpluggedCount);
1213 }
1214
1215 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001216 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001217 mUnpluggedCount = mPluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001218 }
1219
1220 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001221 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001222 mPluggedCount = mCount;
1223 }
1224
1225 public long getCountLocked(int which) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001226 long val = mTimeBase.isRunning() ? mCount : mPluggedCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001227 if (which == STATS_SINCE_UNPLUGGED) {
1228 val -= mUnpluggedCount;
1229 } else if (which != STATS_SINCE_CHARGED) {
1230 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001231 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001232 return val;
1233 }
1234
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001235 @Override
1236 public void logState(Printer pw, String prefix) {
1237 pw.println(prefix + "mCount=" + mCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001238 + " mLoadedCount=" + mLoadedCount
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001239 + " mUnpluggedCount=" + mUnpluggedCount
1240 + " mPluggedCount=" + mPluggedCount);
1241 }
1242
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001243 void addCountLocked(long count) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001244 if (mTimeBase.isRunning()) {
1245 mCount += count;
1246 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001247 }
1248
1249 /**
1250 * Clear state of this counter.
1251 */
1252 void reset(boolean detachIfReset) {
1253 mCount = 0;
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001254 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001255 if (detachIfReset) {
1256 detach();
1257 }
1258 }
1259
1260 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001261 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001262 }
1263
1264 void writeSummaryFromParcelLocked(Parcel out) {
1265 out.writeLong(mCount);
1266 }
1267
1268 void readSummaryFromParcelLocked(Parcel in) {
1269 mLoadedCount = in.readLong();
1270 mCount = mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001271 mUnpluggedCount = mPluggedCount = mLoadedCount;
1272 }
1273 }
1274
Dianne Hackborn617f8772009-03-31 15:04:46 -07001275 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 * State for keeping track of timing information.
1277 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001278 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001279 protected final Clocks mClocks;
1280 protected final int mType;
1281 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001282
Joe Onoratoabded112016-02-08 16:49:39 -08001283 protected int mCount;
1284 protected int mLoadedCount;
1285 protected int mLastCount;
1286 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 // Times are in microseconds for better accuracy when dividing by the
1289 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 /**
1292 * The total time we have accumulated since the start of the original
1293 * boot, to the last time something interesting happened in the
1294 * current run.
1295 */
Joe Onoratoabded112016-02-08 16:49:39 -08001296 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 /**
1299 * The total time we loaded for the previous runs. Subtract this from
1300 * mTotalTime to find the time for the current run of the system.
1301 */
Joe Onoratoabded112016-02-08 16:49:39 -08001302 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 /**
1305 * The run time of the last run of the system, as loaded from the
1306 * saved data.
1307 */
Joe Onoratoabded112016-02-08 16:49:39 -08001308 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 /**
1311 * The value of mTotalTime when unplug() was last called. Subtract
1312 * this from mTotalTime to find the time since the last unplug from
1313 * power.
1314 */
Joe Onoratoabded112016-02-08 16:49:39 -08001315 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001316
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001317 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001318 * The total time this timer has been running until the latest mark has been set.
1319 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1320 */
Joe Onoratoabded112016-02-08 16:49:39 -08001321 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001322
1323 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001324 * Constructs from a parcel.
1325 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001326 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001327 * @param in
1328 */
Joe Onoratoabded112016-02-08 16:49:39 -08001329 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1330 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001332 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 mCount = in.readInt();
1335 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001336 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 mUnpluggedCount = in.readInt();
1338 mTotalTime = in.readLong();
1339 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001340 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001342 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001343 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001344 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 }
1346
Joe Onoratoabded112016-02-08 16:49:39 -08001347 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1348 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001350 mTimeBase = timeBase;
1351 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 }
Evan Millarc64edde2009-04-18 12:26:32 -07001353
1354 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001355
Evan Millarc64edde2009-04-18 12:26:32 -07001356 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001357
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001358 /**
1359 * Clear state of this timer. Returns true if the timer is inactive
1360 * so can be completely dropped.
1361 */
Joe Onoratoabded112016-02-08 16:49:39 -08001362 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001363 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001364 mCount = mLoadedCount = mLastCount = 0;
1365 if (detachIfReset) {
1366 detach();
1367 }
1368 return true;
1369 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001370
Joe Onoratoabded112016-02-08 16:49:39 -08001371 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001372 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001373 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001374
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001375 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001376 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1377 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001378 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001381 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001384 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
1386
Adam Lesinskie08af192015-03-25 16:42:59 -07001387 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001388 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001390 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 + " old mUnpluggedTime=" + mUnpluggedTime
1392 + " old mUnpluggedCount=" + mUnpluggedCount);
1393 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001394 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001395 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 if (DEBUG && mType < 0) {
1397 Log.v(TAG, "unplug #" + mType
1398 + ": new mUnpluggedTime=" + mUnpluggedTime
1399 + " new mUnpluggedCount=" + mUnpluggedCount);
1400 }
1401 }
1402
Adam Lesinskie08af192015-03-25 16:42:59 -07001403 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001404 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001405 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001406 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001407 + " old mTotalTime=" + mTotalTime);
1408 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001409 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001410 mCount = computeCurrentCountLocked();
1411 if (DEBUG && mType < 0) {
1412 Log.v(TAG, "plug #" + mType
1413 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 /**
1418 * Writes a possibly null Timer to a Parcel.
1419 *
1420 * @param out the Parcel to be written to.
1421 * @param timer a Timer, or null.
1422 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001423 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 if (timer == null) {
1425 out.writeInt(0); // indicates null
1426 return;
1427 }
1428 out.writeInt(1); // indicates non-null
1429
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001430 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 }
1432
1433 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001434 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001435 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1436 if (which == STATS_SINCE_UNPLUGGED) {
1437 val -= mUnpluggedTime;
1438 } else if (which != STATS_SINCE_CHARGED) {
1439 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
1441
1442 return val;
1443 }
1444
1445 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001446 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001447 int val = computeCurrentCountLocked();
1448 if (which == STATS_SINCE_UNPLUGGED) {
1449 val -= mUnpluggedCount;
1450 } else if (which != STATS_SINCE_CHARGED) {
1451 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 }
1453
1454 return val;
1455 }
1456
Adam Lesinskie08af192015-03-25 16:42:59 -07001457 @Override
1458 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1459 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1460 return val - mTimeBeforeMark;
1461 }
1462
1463 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001464 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001465 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1467 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001468 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001470 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001472 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001473
1474
Joe Onoratoabded112016-02-08 16:49:39 -08001475 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001476 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1477 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001478 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001479 }
1480
Joe Onoratoabded112016-02-08 16:49:39 -08001481 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001482 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001483 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001484 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001485 mUnpluggedTime = mTotalTime;
1486 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001487 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001488 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001489
1490 // When reading the summary, we set the mark to be the latest information.
1491 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001492 }
1493 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001494
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001495 /**
1496 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1497 * method. The state of the timer according to its {@link TimeBase} will determine how much
1498 * of the value is recorded.
1499 *
1500 * If the value being recorded resets, {@link #endSample()} can be called in order to
1501 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1502 * between calls, the {@link #endSample()} is automatically called and the new value is
1503 * expected to increase monotonically from that point on.
1504 */
Joe Onoratoabded112016-02-08 16:49:39 -08001505 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001506
Evan Millarc64edde2009-04-18 12:26:32 -07001507 /**
1508 * The most recent reported count from /proc/wakelocks.
1509 */
1510 int mCurrentReportedCount;
1511
1512 /**
1513 * The reported count from /proc/wakelocks when unplug() was last
1514 * called.
1515 */
1516 int mUnpluggedReportedCount;
1517
1518 /**
1519 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001520 */
Evan Millarc64edde2009-04-18 12:26:32 -07001521 long mCurrentReportedTotalTime;
1522
1523
1524 /**
1525 * The reported total_time from /proc/wakelocks when unplug() was last
1526 * called.
1527 */
1528 long mUnpluggedReportedTotalTime;
1529
1530 /**
1531 * Whether we are currently in a discharge cycle.
1532 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001533 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001534
1535 /**
1536 * Whether we are currently recording reported values.
1537 */
1538 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001539
Evan Millarc64edde2009-04-18 12:26:32 -07001540 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001541 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001542 */
1543 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001544
Adam Lesinski98f0d462016-04-19 16:46:20 -07001545 @VisibleForTesting
1546 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001547 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001548 mCurrentReportedCount = in.readInt();
1549 mUnpluggedReportedCount = in.readInt();
1550 mCurrentReportedTotalTime = in.readLong();
1551 mUnpluggedReportedTotalTime = in.readLong();
1552 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001553 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001554 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001555
Adam Lesinski98f0d462016-04-19 16:46:20 -07001556 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001557 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001558 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001559 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001560 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001561 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001562
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001563 /**
1564 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1565 * be less than the values used for a previous invocation.
1566 */
1567 public void endSample() {
1568 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1569 mCount = computeCurrentCountLocked();
1570 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1571 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001572 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001573
Evan Millarc64edde2009-04-18 12:26:32 -07001574 public void setUpdateVersion(int version) {
1575 mUpdateVersion = version;
1576 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001577
Evan Millarc64edde2009-04-18 12:26:32 -07001578 public int getUpdateVersion() {
1579 return mUpdateVersion;
1580 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001581
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001582 /**
1583 * Updates the current recorded values. These are meant to be monotonically increasing
1584 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1585 *
1586 * If the values being recorded have been reset, the monotonically increasing requirement
1587 * will be broken. In this case, {@link #endSample()} is automatically called and
1588 * the total value of totalTime and count are recorded, starting a new monotonically
1589 * increasing sample.
1590 *
1591 * @param totalTime total time of sample in microseconds.
1592 * @param count total number of times the event being sampled occurred.
1593 */
1594 public void update(long totalTime, int count) {
1595 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001596 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001597 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001598 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001599 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001600
1601 mTrackingReportedValues = true;
1602
1603 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1604 endSample();
1605 }
1606
1607 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001608 mCurrentReportedCount = count;
1609 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001610
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001611 /**
1612 * Adds deltaTime and deltaCount to the current sample.
1613 *
1614 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1615 * @param deltaCount additional number of times the event being sampled occurred.
1616 */
1617 public void add(long deltaTime, int deltaCount) {
1618 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001619 }
1620
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001621 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001622 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
1623 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001624 if (mTrackingReportedValues) {
1625 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
1626 mUnpluggedReportedCount = mCurrentReportedCount;
1627 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001628 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07001629 }
1630
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001631 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001632 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1633 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1634 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07001635 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001636
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001637 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001638 public void logState(Printer pw, String prefix) {
1639 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001640 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07001641 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
1642 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
1643 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
1644 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001645
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001646 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001647 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001648 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001649 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
1650 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001651
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001652 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001653 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001654 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001655 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
1656 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001657
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001658 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001659 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1660 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001661 out.writeInt(mCurrentReportedCount);
1662 out.writeInt(mUnpluggedReportedCount);
1663 out.writeLong(mCurrentReportedTotalTime);
1664 out.writeLong(mUnpluggedReportedTotalTime);
1665 out.writeInt(mTrackingReportedValues ? 1 : 0);
1666 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001667
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001668 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001669 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001670 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001671 mTrackingReportedValues = false;
1672 mUnpluggedReportedTotalTime = 0;
1673 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001674 return true;
1675 }
Evan Millarc64edde2009-04-18 12:26:32 -07001676 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001677
Evan Millarc64edde2009-04-18 12:26:32 -07001678 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001679 * A timer that increments in batches. It does not run for durations, but just jumps
1680 * for a pre-determined amount.
1681 */
Joe Onoratoabded112016-02-08 16:49:39 -08001682 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001683 final Uid mUid;
1684
1685 /**
1686 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
1687 */
1688 long mLastAddedTime;
1689
1690 /**
1691 * The last duration that we added to the timer. This is in microseconds.
1692 */
1693 long mLastAddedDuration;
1694
1695 /**
1696 * Whether we are currently in a discharge cycle.
1697 */
1698 boolean mInDischarge;
1699
Joe Onoratoabded112016-02-08 16:49:39 -08001700 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
1701 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001702 mUid = uid;
1703 mLastAddedTime = in.readLong();
1704 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001705 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001706 }
1707
Joe Onoratoabded112016-02-08 16:49:39 -08001708 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
1709 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001710 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001711 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001712 }
1713
1714 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001715 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1716 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001717 out.writeLong(mLastAddedTime);
1718 out.writeLong(mLastAddedDuration);
1719 }
1720
1721 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001722 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001723 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001724 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001725 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001726 }
1727
1728 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001729 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001730 recomputeLastDuration(elapsedRealtime, false);
1731 mInDischarge = true;
1732 // If we are still within the last added duration, then re-added whatever remains.
1733 if (mLastAddedTime == elapsedRealtime) {
1734 mTotalTime += mLastAddedDuration;
1735 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001736 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001737 }
1738
1739 @Override
1740 public void logState(Printer pw, String prefix) {
1741 super.logState(pw, prefix);
1742 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
1743 + " mLastAddedDuration=" + mLastAddedDuration);
1744 }
1745
1746 private long computeOverage(long curTime) {
1747 if (mLastAddedTime > 0) {
1748 return mLastTime + mLastAddedDuration - curTime;
1749 }
1750 return 0;
1751 }
1752
1753 private void recomputeLastDuration(long curTime, boolean abort) {
1754 final long overage = computeOverage(curTime);
1755 if (overage > 0) {
1756 // Aborting before the duration ran out -- roll back the remaining
1757 // duration. Only do this if currently discharging; otherwise we didn't
1758 // actually add the time.
1759 if (mInDischarge) {
1760 mTotalTime -= overage;
1761 }
1762 if (abort) {
1763 mLastAddedTime = 0;
1764 } else {
1765 mLastAddedTime = curTime;
1766 mLastAddedDuration -= overage;
1767 }
1768 }
1769 }
1770
1771 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08001772 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001773 recomputeLastDuration(now, true);
1774 mLastAddedTime = now;
1775 mLastAddedDuration = durationMillis * 1000;
1776 if (mInDischarge) {
1777 mTotalTime += mLastAddedDuration;
1778 mCount++;
1779 }
1780 }
1781
1782 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08001783 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001784 recomputeLastDuration(now, true);
1785 }
1786
1787 @Override
1788 protected int computeCurrentCountLocked() {
1789 return mCount;
1790 }
1791
1792 @Override
1793 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001794 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001795 if (overage > 0) {
1796 return mTotalTime = overage;
1797 }
1798 return mTotalTime;
1799 }
1800
1801 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001802 public boolean reset(boolean detachIfReset) {
1803 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001804 recomputeLastDuration(now, true);
1805 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001806 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001807 return !stillActive;
1808 }
1809 }
1810
Joe Onorato92fd23f2016-07-25 11:18:42 -07001811
1812 /**
1813 * A StopwatchTimer that also tracks the total and max individual
1814 * time spent active according to the given timebase. Whereas
1815 * StopwatchTimer apportions the time amongst all in the pool,
1816 * the total and max durations are not apportioned.
1817 */
1818 public static class DurationTimer extends StopwatchTimer {
1819 /**
1820 * The time (in ms) that the timer was last acquired or the time base
1821 * last (re-)started. Increasing the nesting depth does not reset this time.
1822 *
1823 * -1 if the timer is currently not running or the time base is not running.
1824 *
1825 * If written to a parcel, the start time is reset, as is mNesting in the base class
1826 * StopwatchTimer.
1827 */
1828 long mStartTimeMs = -1;
1829
1830 /**
Bookatz867c0d72017-03-07 18:23:42 -08001831 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001832 */
1833 long mMaxDurationMs;
1834
1835 /**
Bookatz867c0d72017-03-07 18:23:42 -08001836 * The time (in ms) that that the timer has been active since most recent
1837 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001838 */
1839 long mCurrentDurationMs;
1840
Bookatz867c0d72017-03-07 18:23:42 -08001841 /**
1842 * The total time (in ms) that that the timer has been active since most recent reset()
1843 * prior to the current startRunningLocked. This is the sum of all past currentDurations
1844 * (but not including the present currentDuration) since reset. Not pooled.
1845 */
1846 long mTotalDurationMs;
1847
Joe Onorato92fd23f2016-07-25 11:18:42 -07001848 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
1849 TimeBase timeBase, Parcel in) {
1850 super(clocks, uid, type, timerPool, timeBase, in);
1851 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08001852 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07001853 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07001854 }
1855
1856 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
1857 TimeBase timeBase) {
1858 super(clocks, uid, type, timerPool, timeBase);
1859 }
1860
1861 @Override
1862 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1863 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08001864 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07001865 out.writeLong(mTotalDurationMs);
1866 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07001867 }
1868
1869 /**
1870 * Write the summary to the parcel.
1871 *
1872 * Since the time base is probably meaningless after we come back, reading
1873 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08001874 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001875 */
1876 @Override
1877 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
1878 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08001879 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08001880 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07001881 }
1882
1883 /**
1884 * Read the summary parcel.
1885 *
1886 * Has the side effect of stopping the timer.
1887 */
1888 @Override
1889 public void readSummaryFromParcelLocked(Parcel in) {
1890 super.readSummaryFromParcelLocked(in);
1891 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08001892 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07001893 mStartTimeMs = -1;
1894 mCurrentDurationMs = 0;
1895 }
1896
1897 /**
1898 * The TimeBase time started (again).
1899 *
1900 * If the timer is also running, store the start time.
1901 */
1902 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
1903 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
1904 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08001905 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001906 }
1907 }
1908
1909 /**
1910 * The TimeBase stopped running.
1911 *
1912 * If the timer is running, add the duration into mCurrentDurationMs.
1913 */
1914 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08001915 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
1916 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07001917 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08001918 // baseRealtimeUs has already been converted to the timebase's realtime.
1919 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001920 }
1921 mStartTimeMs = -1;
1922 }
1923
1924 @Override
1925 public void logState(Printer pw, String prefix) {
1926 super.logState(pw, prefix);
1927 }
1928
1929 @Override
1930 public void startRunningLocked(long elapsedRealtimeMs) {
1931 super.startRunningLocked(elapsedRealtimeMs);
1932 if (mNesting == 1 && mTimeBase.isRunning()) {
1933 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08001934 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001935 }
1936 }
1937
1938 /**
1939 * Decrements the mNesting ref-count on this timer.
1940 *
1941 * If it actually stopped (mNesting went to 0), then possibly update
1942 * mMaxDuration if the current duration was the longest ever.
1943 */
1944 @Override
1945 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08001946 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07001947 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08001948 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001949 if (durationMs > mMaxDurationMs) {
1950 mMaxDurationMs = durationMs;
1951 }
1952 mStartTimeMs = -1;
1953 mCurrentDurationMs = 0;
1954 }
Kweku Adams47db5a82016-12-09 19:04:50 -08001955 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
1956 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
1957 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07001958 }
1959
1960 @Override
1961 public boolean reset(boolean detachIfReset) {
1962 boolean result = super.reset(detachIfReset);
1963 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08001964 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001965 mCurrentDurationMs = 0;
1966 if (mNesting > 0) {
1967 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
1968 } else {
1969 mStartTimeMs = -1;
1970 }
1971 return result;
1972 }
1973
1974 /**
1975 * Returns the max duration that this timer has ever seen.
1976 *
1977 * Note that this time is NOT split between the timers in the timer group that
1978 * this timer is attached to. It is the TOTAL time.
1979 */
1980 @Override
1981 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
1982 if (mNesting > 0) {
1983 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
1984 if (durationMs > mMaxDurationMs) {
1985 return durationMs;
1986 }
1987 }
1988 return mMaxDurationMs;
1989 }
1990
1991 /**
1992 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08001993 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001994 *
1995 * Note that this time is NOT split between the timers in the timer group that
1996 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07001997 *
1998 * Note that if running timer is parceled and unparceled, this method will return
1999 * current duration value at the time of parceling even though timer may not be
2000 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07002001 */
2002 @Override
2003 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2004 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002005 if (mNesting > 0 && mTimeBase.isRunning()) {
2006 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2007 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002008 }
2009 return durationMs;
2010 }
Bookatz867c0d72017-03-07 18:23:42 -08002011
2012 /**
2013 * Returns the total cumulative duration that this timer has been on since reset().
2014 * If mTimerPool == null, this should be the same
2015 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2016 *
2017 * Note that this time is NOT split between the timers in the timer group that
2018 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2019 * the result will not be equivalent to getTotalTimeLocked.
2020 */
2021 @Override
2022 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2023 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2024 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002025 }
2026
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002027 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002028 * State for keeping track of timing information.
2029 */
Joe Onoratoabded112016-02-08 16:49:39 -08002030 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002031 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002032 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002033
Evan Millarc64edde2009-04-18 12:26:32 -07002034 int mNesting;
2035
Evan Millarc64edde2009-04-18 12:26:32 -07002036 /**
2037 * The last time at which we updated the timer. If mNesting is > 0,
2038 * subtract this from the current battery time to find the amount of
2039 * time we have been running since we last computed an update.
2040 */
2041 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002042
Evan Millarc64edde2009-04-18 12:26:32 -07002043 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002044 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002045 * was actually held for an interesting duration. If time base was not running when timer
2046 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002047 */
Bookatzceebafe2017-04-06 11:59:13 -07002048 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002049
Amith Yamasanif37447b2009-10-08 18:28:01 -07002050 long mTimeout;
2051
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002052 /**
2053 * For partial wake locks, keep track of whether we are in the list
2054 * to consume CPU cycles.
2055 */
2056 boolean mInList;
2057
Joe Onoratoabded112016-02-08 16:49:39 -08002058 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002059 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002060 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002061 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002062 mTimerPool = timerPool;
2063 mUpdateTime = in.readLong();
2064 }
2065
Joe Onoratoabded112016-02-08 16:49:39 -08002066 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002067 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002068 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002069 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002070 mTimerPool = timerPool;
2071 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002072
Joe Onoratoabded112016-02-08 16:49:39 -08002073 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002074 mTimeout = timeout;
2075 }
2076
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002077 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2078 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002079 out.writeLong(mUpdateTime);
2080 }
2081
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002082 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002083 if (mNesting > 0) {
2084 if (DEBUG && mType < 0) {
2085 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2086 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002087 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2088 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002089 if (DEBUG && mType < 0) {
2090 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2091 }
2092 }
2093 }
2094
2095 public void logState(Printer pw, String prefix) {
2096 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002097 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 + " mAcquireTime=" + mAcquireTime);
2099 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002100
Joe Onoratoabded112016-02-08 16:49:39 -08002101 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002103 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002104 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 if (mTimerPool != null) {
2106 // Accumulate time to all currently active timers before adding
2107 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002108 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 // Add this timer to the active pool
2110 mTimerPool.add(this);
2111 }
Bookatzceebafe2017-04-06 11:59:13 -07002112 if (mTimeBase.isRunning()) {
2113 // Increment the count
2114 mCount++;
2115 mAcquireTime = mTotalTime;
2116 } else {
2117 mAcquireTime = -1;
2118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 if (DEBUG && mType < 0) {
2120 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2121 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2122 + " mAcquireTime=" + mAcquireTime);
2123 }
2124 }
2125 }
2126
Joe Onoratoabded112016-02-08 16:49:39 -08002127 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002128 return mNesting > 0;
2129 }
2130
Joe Onoratoabded112016-02-08 16:49:39 -08002131 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 // Ignore attempt to stop a timer that isn't running
2133 if (mNesting == 0) {
2134 return;
2135 }
2136 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002137 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 if (mTimerPool != null) {
2139 // Accumulate time to all active counters, scaled by the total
2140 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002141 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 // Remove this timer from the active pool
2143 mTimerPool.remove(this);
2144 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 mNesting = 1;
2146 mTotalTime = computeRunTimeLocked(batteryRealtime);
2147 mNesting = 0;
2148 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 if (DEBUG && mType < 0) {
2151 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2152 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2153 + " mAcquireTime=" + mAcquireTime);
2154 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002155
Bookatzceebafe2017-04-06 11:59:13 -07002156 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 // If there was no change in the time, then discard this
2158 // count. A somewhat cheezy strategy, but hey.
2159 mCount--;
2160 }
2161 }
2162 }
2163
Joe Onoratoabded112016-02-08 16:49:39 -08002164 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002165 if (mNesting > 0) {
2166 mNesting = 1;
2167 stopRunningLocked(elapsedRealtimeMs);
2168 }
2169 }
2170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 // Update the total time for all other running Timers with the same type as this Timer
2172 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002173 private static long refreshTimersLocked(long batteryRealtime,
2174 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002175 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 final int N = pool.size();
2177 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002178 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 long heldTime = batteryRealtime - t.mUpdateTime;
2180 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002181 final long myTime = heldTime / N;
2182 if (t == self) {
2183 selfTime = myTime;
2184 }
2185 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 }
2187 t.mUpdateTime = batteryRealtime;
2188 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002189 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 }
2191
Evan Millarc64edde2009-04-18 12:26:32 -07002192 @Override
2193 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002194 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2195 curBatteryRealtime = mUpdateTime + mTimeout;
2196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 return mTotalTime + (mNesting > 0
2198 ? (curBatteryRealtime - mUpdateTime)
2199 / (mTimerPool != null ? mTimerPool.size() : 1)
2200 : 0);
2201 }
2202
Evan Millarc64edde2009-04-18 12:26:32 -07002203 @Override
2204 protected int computeCurrentCountLocked() {
2205 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 }
2207
Adam Lesinskie08af192015-03-25 16:42:59 -07002208 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002209 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002210 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002211 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002212 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002213 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002214 }
Bookatzceebafe2017-04-06 11:59:13 -07002215 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002216 return canDetach;
2217 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002218
Adam Lesinskie08af192015-03-25 16:42:59 -07002219 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002220 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002221 super.detach();
2222 if (mTimerPool != null) {
2223 mTimerPool.remove(this);
2224 }
2225 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002226
Adam Lesinskie08af192015-03-25 16:42:59 -07002227 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002228 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002229 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 mNesting = 0;
2231 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002232
2233 /**
2234 * Set the mark so that we can query later for the total time the timer has
2235 * accumulated since this point. The timer can be running or not.
2236 *
2237 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2238 */
2239 public void setMark(long elapsedRealtimeMs) {
2240 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2241 if (mNesting > 0) {
2242 // We are running.
2243 if (mTimerPool != null) {
2244 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2245 } else {
2246 mTotalTime += batteryRealtime - mUpdateTime;
2247 mUpdateTime = batteryRealtime;
2248 }
2249 }
2250 mTimeBeforeMark = mTotalTime;
2251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002253
Bookatz867c0d72017-03-07 18:23:42 -08002254 /**
2255 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2256 * TimeBase is effectively a subset of the other.
2257 */
Bookatzaa4594a2017-03-24 12:39:56 -07002258 public static class DualTimer extends DurationTimer {
2259 // This class both is a DurationTimer and also holds a second DurationTimer.
2260 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2261 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2262 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002263 // mSubTimer typically tracks only part of the total time, such as background time, as
2264 // determined by a subTimeBase. It is NOT pooled.
2265 private final DurationTimer mSubTimer;
2266
2267 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002268 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2269 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002270 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002271 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002272 */
2273 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2274 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002275 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002276 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2277 }
2278
2279 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002280 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2281 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002282 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002283 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002284 */
2285 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2286 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002287 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002288 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2289 }
2290
Bookatz867c0d72017-03-07 18:23:42 -08002291 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002292 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002293 public DurationTimer getSubTimer() {
2294 return mSubTimer;
2295 }
2296
Bookatzaa4594a2017-03-24 12:39:56 -07002297 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002298 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002299 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002300 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2301 }
2302
Bookatzaa4594a2017-03-24 12:39:56 -07002303 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002304 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002305 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002306 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2307 }
2308
Bookatzaa4594a2017-03-24 12:39:56 -07002309 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002310 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002311 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002312 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2313 }
2314
Bookatzaa4594a2017-03-24 12:39:56 -07002315 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002316 public boolean reset(boolean detachIfReset) {
2317 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002318 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2319 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002320 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002321 return !active;
2322 }
2323
Bookatzaa4594a2017-03-24 12:39:56 -07002324 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002325 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002326 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002327 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002328 }
2329
Bookatzaa4594a2017-03-24 12:39:56 -07002330 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002331 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002332 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002333 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2334 }
2335
Bookatzaa4594a2017-03-24 12:39:56 -07002336 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002337 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002338 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002339 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2340 }
2341
Bookatzaa4594a2017-03-24 12:39:56 -07002342 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002343 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002344 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002345 mSubTimer.readSummaryFromParcelLocked(in);
2346 }
2347 }
2348
2349
Dianne Hackbornd953c532014-08-16 18:17:38 -07002350 public abstract class OverflowArrayMap<T> {
2351 private static final String OVERFLOW_NAME = "*overflow*";
2352
Dianne Hackborn657153b2016-07-29 14:54:14 -07002353 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002354 final ArrayMap<String, T> mMap = new ArrayMap<>();
2355 T mCurOverflow;
2356 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002357 long mLastOverflowTime;
2358 long mLastOverflowFinishTime;
2359 long mLastClearTime;
2360 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002361
Dianne Hackborn657153b2016-07-29 14:54:14 -07002362 public OverflowArrayMap(int uid) {
2363 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002364 }
2365
2366 public ArrayMap<String, T> getMap() {
2367 return mMap;
2368 }
2369
2370 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002371 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002372 mMap.clear();
2373 mCurOverflow = null;
2374 mActiveOverflow = null;
2375 }
2376
2377 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002378 if (name == null) {
2379 name = "";
2380 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002381 mMap.put(name, obj);
2382 if (OVERFLOW_NAME.equals(name)) {
2383 mCurOverflow = obj;
2384 }
2385 }
2386
2387 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002388 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002389 if (mActiveOverflow != null) {
2390 if (mActiveOverflow.size() == 0) {
2391 mActiveOverflow = null;
2392 }
2393 }
2394 if (mActiveOverflow == null) {
2395 // There is no currently active overflow, so we should no longer have
2396 // an overflow entry.
2397 if (mMap.containsKey(OVERFLOW_NAME)) {
2398 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2399 + mMap.get(OVERFLOW_NAME));
2400 mMap.remove(OVERFLOW_NAME);
2401 }
2402 mCurOverflow = null;
2403 } else {
2404 // There is currently active overflow, so we should still have an overflow entry.
2405 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2406 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2407 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2408 }
2409 }
2410 }
2411
2412 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002413 if (name == null) {
2414 name = "";
2415 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002416 T obj = mMap.get(name);
2417 if (obj != null) {
2418 return obj;
2419 }
2420
2421 // No object exists for the given name, but do we currently have it
2422 // running as part of the overflow?
2423 if (mActiveOverflow != null) {
2424 MutableInt over = mActiveOverflow.get(name);
2425 if (over != null) {
2426 // We are already actively counting this name in the overflow object.
2427 obj = mCurOverflow;
2428 if (obj == null) {
2429 // Shouldn't be here, but we'll try to recover.
2430 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2431 obj = mCurOverflow = instantiateObject();
2432 mMap.put(OVERFLOW_NAME, obj);
2433 }
2434 over.value++;
2435 return obj;
2436 }
2437 }
2438
2439 // No object exists for given name nor in the overflow; we need to make
2440 // a new one.
2441 final int N = mMap.size();
2442 if (N >= MAX_WAKELOCKS_PER_UID) {
2443 // Went over the limit on number of objects to track; this one goes
2444 // in to the overflow.
2445 obj = mCurOverflow;
2446 if (obj == null) {
2447 // Need to start overflow now...
2448 obj = mCurOverflow = instantiateObject();
2449 mMap.put(OVERFLOW_NAME, obj);
2450 }
2451 if (mActiveOverflow == null) {
2452 mActiveOverflow = new ArrayMap<>();
2453 }
2454 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002455 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002456 return obj;
2457 }
2458
2459 // Normal case where we just need to make a new object.
2460 obj = instantiateObject();
2461 mMap.put(name, obj);
2462 return obj;
2463 }
2464
2465 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002466 if (name == null) {
2467 name = "";
2468 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002469 T obj = mMap.get(name);
2470 if (obj != null) {
2471 return obj;
2472 }
2473
2474 // No object exists for the given name, but do we currently have it
2475 // running as part of the overflow?
2476 if (mActiveOverflow != null) {
2477 MutableInt over = mActiveOverflow.get(name);
2478 if (over != null) {
2479 // We are already actively counting this name in the overflow object.
2480 obj = mCurOverflow;
2481 if (obj != null) {
2482 over.value--;
2483 if (over.value <= 0) {
2484 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002485 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002486 }
2487 return obj;
2488 }
2489 }
2490 }
2491
2492 // Huh, they are stopping an active operation but we can't find one!
2493 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002494 StringBuilder sb = new StringBuilder();
2495 sb.append("Unable to find object for ");
2496 sb.append(name);
2497 sb.append(" in uid ");
2498 sb.append(mUid);
2499 sb.append(" mapsize=");
2500 sb.append(mMap.size());
2501 sb.append(" activeoverflow=");
2502 sb.append(mActiveOverflow);
2503 sb.append(" curoverflow=");
2504 sb.append(mCurOverflow);
2505 long now = SystemClock.elapsedRealtime();
2506 if (mLastOverflowTime != 0) {
2507 sb.append(" lastOverflowTime=");
2508 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2509 }
2510 if (mLastOverflowFinishTime != 0) {
2511 sb.append(" lastOverflowFinishTime=");
2512 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2513 }
2514 if (mLastClearTime != 0) {
2515 sb.append(" lastClearTime=");
2516 TimeUtils.formatDuration(mLastClearTime-now, sb);
2517 }
2518 if (mLastCleanupTime != 0) {
2519 sb.append(" lastCleanupTime=");
2520 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2521 }
2522 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002523 return null;
2524 }
2525
2526 public abstract T instantiateObject();
2527 }
2528
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002529 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2530 implements Parcelable {
2531 private final LongSamplingCounter mIdleTimeMillis;
2532 private final LongSamplingCounter mRxTimeMillis;
2533 private final LongSamplingCounter[] mTxTimeMillis;
2534 private final LongSamplingCounter mPowerDrainMaMs;
2535
2536 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2537 mIdleTimeMillis = new LongSamplingCounter(timeBase);
2538 mRxTimeMillis = new LongSamplingCounter(timeBase);
2539 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2540 for (int i = 0; i < numTxStates; i++) {
2541 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2542 }
2543 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2544 }
2545
2546 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2547 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
2548 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2549 final int recordedTxStates = in.readInt();
2550 if (recordedTxStates != numTxStates) {
2551 throw new ParcelFormatException("inconsistent tx state lengths");
2552 }
2553
2554 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2555 for (int i = 0; i < numTxStates; i++) {
2556 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2557 }
2558 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2559 }
2560
2561 public void readSummaryFromParcel(Parcel in) {
2562 mIdleTimeMillis.readSummaryFromParcelLocked(in);
2563 mRxTimeMillis.readSummaryFromParcelLocked(in);
2564 final int recordedTxStates = in.readInt();
2565 if (recordedTxStates != mTxTimeMillis.length) {
2566 throw new ParcelFormatException("inconsistent tx state lengths");
2567 }
2568 for (LongSamplingCounter counter : mTxTimeMillis) {
2569 counter.readSummaryFromParcelLocked(in);
2570 }
2571 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2572 }
2573
2574 @Override
2575 public int describeContents() {
2576 return 0;
2577 }
2578
2579 public void writeSummaryToParcel(Parcel dest) {
2580 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
2581 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2582 dest.writeInt(mTxTimeMillis.length);
2583 for (LongSamplingCounter counter : mTxTimeMillis) {
2584 counter.writeSummaryFromParcelLocked(dest);
2585 }
2586 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2587 }
2588
2589 @Override
2590 public void writeToParcel(Parcel dest, int flags) {
2591 mIdleTimeMillis.writeToParcel(dest);
2592 mRxTimeMillis.writeToParcel(dest);
2593 dest.writeInt(mTxTimeMillis.length);
2594 for (LongSamplingCounter counter : mTxTimeMillis) {
2595 counter.writeToParcel(dest);
2596 }
2597 mPowerDrainMaMs.writeToParcel(dest);
2598 }
2599
2600 public void reset(boolean detachIfReset) {
2601 mIdleTimeMillis.reset(detachIfReset);
2602 mRxTimeMillis.reset(detachIfReset);
2603 for (LongSamplingCounter counter : mTxTimeMillis) {
2604 counter.reset(detachIfReset);
2605 }
2606 mPowerDrainMaMs.reset(detachIfReset);
2607 }
2608
2609 public void detach() {
2610 mIdleTimeMillis.detach();
2611 mRxTimeMillis.detach();
2612 for (LongSamplingCounter counter : mTxTimeMillis) {
2613 counter.detach();
2614 }
2615 mPowerDrainMaMs.detach();
2616 }
2617
2618 /**
2619 * @return a LongSamplingCounter, measuring time spent in the idle state in
2620 * milliseconds.
2621 */
2622 @Override
2623 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07002624 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002625 }
2626
2627 /**
2628 * @return a LongSamplingCounter, measuring time spent in the receive state in
2629 * milliseconds.
2630 */
2631 @Override
2632 public LongSamplingCounter getRxTimeCounter() {
2633 return mRxTimeMillis;
2634 }
2635
2636 /**
2637 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
2638 * milliseconds.
2639 */
2640 @Override
2641 public LongSamplingCounter[] getTxTimeCounters() {
2642 return mTxTimeMillis;
2643 }
2644
2645 /**
2646 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
2647 */
2648 @Override
2649 public LongSamplingCounter getPowerCounter() {
2650 return mPowerDrainMaMs;
2651 }
2652 }
2653
Bookatz50df7112017-08-04 14:53:26 -07002654 /** Get Resource Power Manager stats. Create a new one if it doesn't already exist. */
2655 public SamplingTimer getRpmTimerLocked(String name) {
2656 SamplingTimer rpmt = mRpmStats.get(name);
2657 if (rpmt == null) {
2658 rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2659 mRpmStats.put(name, rpmt);
2660 }
2661 return rpmt;
2662 }
2663
2664 /** Get Screen-off Resource Power Manager stats. Create new one if it doesn't already exist. */
2665 public SamplingTimer getScreenOffRpmTimerLocked(String name) {
2666 SamplingTimer rpmt = mScreenOffRpmStats.get(name);
2667 if (rpmt == null) {
2668 rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
2669 mScreenOffRpmStats.put(name, rpmt);
2670 }
2671 return rpmt;
2672 }
2673
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002674 /*
2675 * Get the wakeup reason counter, and create a new one if one
2676 * doesn't already exist.
2677 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002678 public SamplingTimer getWakeupReasonTimerLocked(String name) {
2679 SamplingTimer timer = mWakeupReasonStats.get(name);
2680 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002681 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002682 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002683 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002684 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002685 }
2686
Evan Millarc64edde2009-04-18 12:26:32 -07002687 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002688 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07002689 * doesn't already exist.
2690 */
2691 public SamplingTimer getKernelWakelockTimerLocked(String name) {
2692 SamplingTimer kwlt = mKernelWakelockStats.get(name);
2693 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002694 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07002695 mKernelWakelockStats.put(name, kwlt);
2696 }
2697 return kwlt;
2698 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07002699
James Carr3a226052016-07-01 14:49:52 -07002700 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
2701 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
2702 if (kmt == null) {
2703 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2704 mKernelMemoryStats.put(bucket, kmt);
2705 }
2706 return kmt;
2707 }
2708
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002709 private int writeHistoryTag(HistoryTag tag) {
2710 Integer idxObj = mHistoryTagPool.get(tag);
2711 int idx;
2712 if (idxObj != null) {
2713 idx = idxObj;
2714 } else {
2715 idx = mNextHistoryTagIdx;
2716 HistoryTag key = new HistoryTag();
2717 key.setTo(tag);
2718 tag.poolIdx = idx;
2719 mHistoryTagPool.put(key, idx);
2720 mNextHistoryTagIdx++;
2721 mNumHistoryTagChars += key.string.length() + 1;
2722 }
2723 return idx;
2724 }
2725
2726 private void readHistoryTag(int index, HistoryTag tag) {
2727 tag.string = mReadHistoryStrings[index];
2728 tag.uid = mReadHistoryUids[index];
2729 tag.poolIdx = index;
2730 }
2731
Adam Lesinski926969b2016-04-28 17:31:12 -07002732 /*
2733 The history delta format uses flags to denote further data in subsequent ints in the parcel.
2734
2735 There is always the first token, which may contain the delta time, or an indicator of
2736 the length of the time (int or long) following this token.
2737
2738 First token: always present,
2739 31 23 15 7 0
2740 â–ˆ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â–ˆ
2741
2742 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
2743 follows containing the time, and 0x7ffff indicates a long immediately follows with the
2744 delta time.
2745 A: battery level changed and an int follows with battery data.
2746 B: state changed and an int follows with state change data.
2747 C: state2 has changed and an int follows with state2 change data.
2748 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
2749 E: event data has changed and an event struct follows.
2750 F: battery charge in coulombs has changed and an int with the charge follows.
2751 G: state flag denoting that the mobile radio was active.
2752 H: state flag denoting that the wifi radio was active.
2753 I: state flag denoting that a wifi scan occurred.
2754 J: state flag denoting that a wifi full lock was held.
2755 K: state flag denoting that the gps was on.
2756 L: state flag denoting that a wakelock was held.
2757 M: state flag denoting that the cpu was running.
2758
2759 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
2760 with the time delta.
2761
2762 Battery level int: if A in the first token is set,
2763 31 23 15 7 0
2764 â–ˆ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â–ˆ
2765
2766 D: indicates that extra history details follow.
2767 V: the battery voltage.
2768 T: the battery temperature.
2769 L: the battery level (out of 100).
2770
2771 State change int: if B in the first token is set,
2772 31 23 15 7 0
2773 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
2774
2775 A: wifi multicast was on.
2776 B: battery was plugged in.
2777 C: screen was on.
2778 D: phone was scanning for signal.
2779 E: audio was on.
2780 F: a sensor was active.
2781
2782 State2 change int: if C in the first token is set,
2783 31 23 15 7 0
2784 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
2785
2786 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
2787 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
2788 C: a bluetooth scan was active.
2789 D: the camera was active.
2790 E: bluetooth was on.
2791 F: a phone call was active.
2792 G: the device was charging.
2793 H: 2 bits indicating the device-idle (doze) state: off, light, full
2794 I: the flashlight was on.
2795 J: wifi was on.
2796 K: wifi was running.
2797 L: video was playing.
2798 M: power save mode was on.
2799
2800 Wakelock/wakereason struct: if D in the first token is set,
2801 TODO(adamlesinski): describe wakelock/wakereason struct.
2802
2803 Event struct: if E in the first token is set,
2804 TODO(adamlesinski): describe the event struct.
2805
2806 History step details struct: if D in the battery level int is set,
2807 TODO(adamlesinski): describe the history step details struct.
2808
2809 Battery charge int: if F in the first token is set, an int representing the battery charge
2810 in coulombs follows.
2811 */
2812
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002813 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08002814 static final int DELTA_TIME_MASK = 0x7ffff;
2815 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
2816 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
2817 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002818 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07002819 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002820 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07002821 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08002822 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07002823 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002824 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07002825 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002826 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07002827 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07002828 // Flag in delta int: contains the battery charge count in uAh.
2829 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002830 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07002831 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08002832
2833 // These are the pieces of battery state that are packed in to the upper bits of
2834 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07002835 // in STATE_BATTERY_MASK.
2836 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08002837 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
2838 static final int STATE_BATTERY_STATUS_SHIFT = 29;
2839 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
2840 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
2841 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
2842 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002843
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002844 // We use the low bit of the battery state int to indicate that we have full details
2845 // from a battery level change.
2846 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
2847
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002848 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002849 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002850 dest.writeInt(DELTA_TIME_ABS);
2851 cur.writeToParcel(dest, 0);
2852 return;
2853 }
2854
2855 final long deltaTime = cur.time - last.time;
2856 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
2857 final int lastStateInt = buildStateInt(last);
2858
2859 int deltaTimeToken;
2860 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
2861 deltaTimeToken = DELTA_TIME_LONG;
2862 } else if (deltaTime >= DELTA_TIME_ABS) {
2863 deltaTimeToken = DELTA_TIME_INT;
2864 } else {
2865 deltaTimeToken = (int)deltaTime;
2866 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002867 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002868 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
2869 ? BATTERY_DELTA_LEVEL_FLAG : 0;
2870 final boolean computeStepDetails = includeStepDetails != 0
2871 || mLastHistoryStepDetails == null;
2872 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002873 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
2874 if (batteryLevelIntChanged) {
2875 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
2876 }
2877 final int stateInt = buildStateInt(cur);
2878 final boolean stateIntChanged = stateInt != lastStateInt;
2879 if (stateIntChanged) {
2880 firstToken |= DELTA_STATE_FLAG;
2881 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002882 final boolean state2IntChanged = cur.states2 != last.states2;
2883 if (state2IntChanged) {
2884 firstToken |= DELTA_STATE2_FLAG;
2885 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002886 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002887 firstToken |= DELTA_WAKELOCK_FLAG;
2888 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002889 if (cur.eventCode != HistoryItem.EVENT_NONE) {
2890 firstToken |= DELTA_EVENT_FLAG;
2891 }
Adam Lesinski926969b2016-04-28 17:31:12 -07002892
Adam Lesinskia8018ac2016-05-03 10:18:10 -07002893 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
2894 if (batteryChargeChanged) {
2895 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07002896 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002897 dest.writeInt(firstToken);
2898 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
2899 + " deltaTime=" + deltaTime);
2900
2901 if (deltaTimeToken >= DELTA_TIME_INT) {
2902 if (deltaTimeToken == DELTA_TIME_INT) {
2903 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
2904 dest.writeInt((int)deltaTime);
2905 } else {
2906 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
2907 dest.writeLong(deltaTime);
2908 }
2909 }
2910 if (batteryLevelIntChanged) {
2911 dest.writeInt(batteryLevelInt);
2912 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
2913 + Integer.toHexString(batteryLevelInt)
2914 + " batteryLevel=" + cur.batteryLevel
2915 + " batteryTemp=" + cur.batteryTemperature
2916 + " batteryVolt=" + (int)cur.batteryVoltage);
2917 }
2918 if (stateIntChanged) {
2919 dest.writeInt(stateInt);
2920 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
2921 + Integer.toHexString(stateInt)
2922 + " batteryStatus=" + cur.batteryStatus
2923 + " batteryHealth=" + cur.batteryHealth
2924 + " batteryPlugType=" + cur.batteryPlugType
2925 + " states=0x" + Integer.toHexString(cur.states));
2926 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002927 if (state2IntChanged) {
2928 dest.writeInt(cur.states2);
2929 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
2930 + Integer.toHexString(cur.states2));
2931 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002932 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
2933 int wakeLockIndex;
2934 int wakeReasonIndex;
2935 if (cur.wakelockTag != null) {
2936 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
2937 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
2938 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
2939 } else {
2940 wakeLockIndex = 0xffff;
2941 }
2942 if (cur.wakeReasonTag != null) {
2943 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
2944 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
2945 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
2946 } else {
2947 wakeReasonIndex = 0xffff;
2948 }
2949 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002950 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002951 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002952 int index = writeHistoryTag(cur.eventTag);
2953 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08002954 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002955 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
2956 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
2957 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002958 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002959 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07002960 if (mPlatformIdleStateCallback != null) {
2961 mCurHistoryStepDetails.statPlatformIdleState =
2962 mPlatformIdleStateCallback.getPlatformLowPowerStats();
2963 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
2964 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00002965
2966 mCurHistoryStepDetails.statSubsystemPowerState =
2967 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
2968 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
2969 mCurHistoryStepDetails.statSubsystemPowerState);
2970
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07002971 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002972 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
2973 if (includeStepDetails != 0) {
2974 mCurHistoryStepDetails.writeToParcel(dest);
2975 }
2976 cur.stepDetails = mCurHistoryStepDetails;
2977 mLastHistoryStepDetails = mCurHistoryStepDetails;
2978 } else {
2979 cur.stepDetails = null;
2980 }
2981 if (mLastHistoryStepLevel < cur.batteryLevel) {
2982 mLastHistoryStepDetails = null;
2983 }
2984 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07002985
Adam Lesinskia8018ac2016-05-03 10:18:10 -07002986 if (batteryChargeChanged) {
2987 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
2988 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07002989 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002990 }
2991
2992 private int buildBatteryLevelInt(HistoryItem h) {
2993 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08002994 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
2995 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
2996 }
2997
2998 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
2999 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
3000 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
3001 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003002 }
3003
3004 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003005 int plugType = 0;
3006 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
3007 plugType = 1;
3008 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
3009 plugType = 2;
3010 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
3011 plugType = 3;
3012 }
3013 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
3014 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
3015 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07003016 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003017 }
3018
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003019 private void computeHistoryStepDetails(final HistoryStepDetails out,
3020 final HistoryStepDetails last) {
3021 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
3022
3023 // Perform a CPU update right after we do this collection, so we have started
3024 // collecting good data for the next step.
3025 requestImmediateCpuUpdate();
3026
3027 if (last == null) {
3028 // We are not generating a delta, so all we need to do is reset the stats
3029 // we will later be doing a delta from.
3030 final int NU = mUidStats.size();
3031 for (int i=0; i<NU; i++) {
3032 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3033 uid.mLastStepUserTime = uid.mCurStepUserTime;
3034 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3035 }
3036 mLastStepCpuUserTime = mCurStepCpuUserTime;
3037 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3038 mLastStepStatUserTime = mCurStepStatUserTime;
3039 mLastStepStatSystemTime = mCurStepStatSystemTime;
3040 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3041 mLastStepStatIrqTime = mCurStepStatIrqTime;
3042 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3043 mLastStepStatIdleTime = mCurStepStatIdleTime;
3044 tmp.clear();
3045 return;
3046 }
3047 if (DEBUG) {
3048 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3049 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3050 + " irq=" + mLastStepStatIrqTime + " sirq="
3051 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3052 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3053 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3054 + " irq=" + mCurStepStatIrqTime + " sirq="
3055 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3056 }
3057 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3058 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3059 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3060 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3061 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3062 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3063 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3064 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3065 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3066 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3067 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3068 final int NU = mUidStats.size();
3069 for (int i=0; i<NU; i++) {
3070 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3071 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3072 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3073 final int totalTime = totalUTime + totalSTime;
3074 uid.mLastStepUserTime = uid.mCurStepUserTime;
3075 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3076 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3077 continue;
3078 }
3079 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3080 out.appCpuUid3 = uid.mUid;
3081 out.appCpuUTime3 = totalUTime;
3082 out.appCpuSTime3 = totalSTime;
3083 } else {
3084 out.appCpuUid3 = out.appCpuUid2;
3085 out.appCpuUTime3 = out.appCpuUTime2;
3086 out.appCpuSTime3 = out.appCpuSTime2;
3087 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3088 out.appCpuUid2 = uid.mUid;
3089 out.appCpuUTime2 = totalUTime;
3090 out.appCpuSTime2 = totalSTime;
3091 } else {
3092 out.appCpuUid2 = out.appCpuUid1;
3093 out.appCpuUTime2 = out.appCpuUTime1;
3094 out.appCpuSTime2 = out.appCpuSTime1;
3095 out.appCpuUid1 = uid.mUid;
3096 out.appCpuUTime1 = totalUTime;
3097 out.appCpuSTime1 = totalSTime;
3098 }
3099 }
3100 }
3101 mLastStepCpuUserTime = mCurStepCpuUserTime;
3102 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3103 mLastStepStatUserTime = mCurStepStatUserTime;
3104 mLastStepStatSystemTime = mCurStepStatSystemTime;
3105 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3106 mLastStepStatIrqTime = mCurStepStatIrqTime;
3107 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3108 mLastStepStatIdleTime = mCurStepStatIdleTime;
3109 }
3110
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003111 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3112 int firstToken = src.readInt();
3113 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003114 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003115 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003116 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3117 + " deltaTimeToken=" + deltaTimeToken);
3118
3119 if (deltaTimeToken < DELTA_TIME_ABS) {
3120 cur.time += deltaTimeToken;
3121 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3122 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003123 cur.numReadInts += 2;
3124 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003125 cur.readFromParcel(src);
3126 return;
3127 } else if (deltaTimeToken == DELTA_TIME_INT) {
3128 int delta = src.readInt();
3129 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003130 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003131 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3132 } else {
3133 long delta = src.readLong();
3134 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3135 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003136 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003137 }
3138
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003139 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003140 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003141 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003142 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003143 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003144 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3145 + Integer.toHexString(batteryLevelInt)
3146 + " batteryLevel=" + cur.batteryLevel
3147 + " batteryTemp=" + cur.batteryTemperature
3148 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003149 } else {
3150 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003151 }
3152
3153 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3154 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003155 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003156 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3157 & STATE_BATTERY_STATUS_MASK);
3158 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3159 & STATE_BATTERY_HEALTH_MASK);
3160 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3161 & STATE_BATTERY_PLUG_MASK);
3162 switch (cur.batteryPlugType) {
3163 case 1:
3164 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3165 break;
3166 case 2:
3167 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3168 break;
3169 case 3:
3170 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3171 break;
3172 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003173 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003174 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3175 + Integer.toHexString(stateInt)
3176 + " batteryStatus=" + cur.batteryStatus
3177 + " batteryHealth=" + cur.batteryHealth
3178 + " batteryPlugType=" + cur.batteryPlugType
3179 + " states=0x" + Integer.toHexString(cur.states));
3180 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003181 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003182 }
3183
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003184 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3185 cur.states2 = src.readInt();
3186 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3187 + Integer.toHexString(cur.states2));
3188 }
3189
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003190 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003191 int indexes = src.readInt();
3192 int wakeLockIndex = indexes&0xffff;
3193 int wakeReasonIndex = (indexes>>16)&0xffff;
3194 if (wakeLockIndex != 0xffff) {
3195 cur.wakelockTag = cur.localWakelockTag;
3196 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3197 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3198 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3199 } else {
3200 cur.wakelockTag = null;
3201 }
3202 if (wakeReasonIndex != 0xffff) {
3203 cur.wakeReasonTag = cur.localWakeReasonTag;
3204 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3205 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3206 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3207 } else {
3208 cur.wakeReasonTag = null;
3209 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003210 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003211 } else {
3212 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003213 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003214 }
3215
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003216 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003217 cur.eventTag = cur.localEventTag;
3218 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003219 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003220 final int index = ((codeAndIndex>>16)&0xffff);
3221 readHistoryTag(index, cur.eventTag);
3222 cur.numReadInts += 1;
3223 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3224 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3225 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003226 } else {
3227 cur.eventCode = HistoryItem.EVENT_NONE;
3228 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003229
3230 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3231 cur.stepDetails = mReadHistoryStepDetails;
3232 cur.stepDetails.readFromParcel(src);
3233 } else {
3234 cur.stepDetails = null;
3235 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003236
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003237 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3238 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003239 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003240 }
3241
Dianne Hackbornfc064132014-06-02 12:42:12 -07003242 @Override
3243 public void commitCurrentHistoryBatchLocked() {
3244 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3245 }
3246
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003247 void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003248 if (!mHaveBatteryLevel || !mRecordingHistory) {
3249 return;
3250 }
3251
Dianne Hackborn40c87252014-03-19 16:55:40 -07003252 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003253 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3254 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003255 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003256 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003257 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3258 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003259 + Integer.toHexString(lastDiffStates) + " diff2="
3260 + Integer.toHexString(diffStates2) + " lastDiff2="
3261 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003262 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003263 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003264 && (diffStates2&lastDiffStates2) == 0
3265 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3266 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003267 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003268 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003269 || cur.eventCode == HistoryItem.EVENT_NONE)
3270 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3271 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3272 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3273 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3274 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3275 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003276 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003277 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003278 // as long as no bit has changed both between now and the last entry, as
3279 // well as the last entry and the one before it (so we capture any toggles).
3280 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003281 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3282 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3283 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003284 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003285 // If the last written history had a wakelock tag, we need to retain it.
3286 // Note that the condition above made sure that we aren't in a case where
3287 // both it and the current history item have a wakelock tag.
3288 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003289 cur.wakelockTag = cur.localWakelockTag;
3290 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003291 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003292 // If the last written history had a wake reason tag, we need to retain it.
3293 // Note that the condition above made sure that we aren't in a case where
3294 // both it and the current history item have a wakelock tag.
3295 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003296 cur.wakeReasonTag = cur.localWakeReasonTag;
3297 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003298 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003299 // If the last written history had an event, we need to retain it.
3300 // Note that the condition above made sure that we aren't in a case where
3301 // both it and the current history item have an event.
3302 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003303 cur.eventCode = mHistoryLastWritten.eventCode;
3304 cur.eventTag = cur.localEventTag;
3305 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003306 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003307 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003308 }
3309
Adam Lesinski45489782016-12-15 23:45:17 -08003310 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003311 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003312 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3313 // Clients can't deal with history buffers this large. This only
3314 // really happens when the device is on charger and interacted with
3315 // for long periods of time, like in retail mode. Since the device is
3316 // most likely charged, when unplugged, stats would have reset anyways.
3317 // Reset the stats and mark that we overflowed.
3318 // b/32540341
3319 resetAllStatsLocked();
3320
3321 // Mark that we want to set *OVERFLOW* event and the RESET:START
3322 // events.
3323 recordResetDueToOverflow = true;
3324
3325 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003326 if (!mHistoryOverflow) {
3327 mHistoryOverflow = true;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003328 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
3329 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003330 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003331 }
3332
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003333 // After overflow, we allow various bit-wise states to settle to 0.
3334 boolean writeAnyway = false;
3335 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3336 & mActiveHistoryStates;
3337 if (mHistoryLastWritten.states != curStates) {
3338 // mActiveHistoryStates keeps track of which bits in .states are now being
3339 // forced to 0.
3340 int old = mActiveHistoryStates;
3341 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3342 writeAnyway |= old != mActiveHistoryStates;
3343 }
3344 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3345 & mActiveHistoryStates2;
3346 if (mHistoryLastWritten.states2 != curStates2) {
3347 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3348 // forced to 0.
3349 int old = mActiveHistoryStates2;
3350 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3351 writeAnyway |= old != mActiveHistoryStates2;
3352 }
3353
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003354 // Once we've reached the maximum number of items, we only
3355 // record changes to the battery level and the most interesting states.
3356 // Once we've reached the maximum maximum number of items, we only
3357 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003358 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003359 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003360 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003361 & HistoryItem.MOST_INTERESTING_STATES) == 0
3362 || ((mHistoryLastWritten.states2^cur.states2)
3363 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003364 return;
3365 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003366
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003367 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003368 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003369 }
3370
Adam Lesinski45489782016-12-15 23:45:17 -08003371 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003372 // The history is currently empty; we need it to start with a time stamp.
3373 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003374 if (recordResetDueToOverflow) {
3375 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
3376 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003377 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_RESET, cur);
3378 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003379 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003380 }
3381
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003382 private void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd,
3383 HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003384 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003385 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003386 }
3387 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3388 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003389 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003390 mHistoryLastWritten.states &= mActiveHistoryStates;
3391 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003392 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003393 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003394 cur.wakelockTag = null;
3395 cur.wakeReasonTag = null;
3396 cur.eventCode = HistoryItem.EVENT_NONE;
3397 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003398 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3399 + " now " + mHistoryBuffer.dataPosition()
3400 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003401 }
3402
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003403 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003404 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003405
Dianne Hackborn40c87252014-03-19 16:55:40 -07003406 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003407 if (mTrackRunningHistoryElapsedRealtime != 0) {
3408 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3409 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3410 if (diffUptime < (diffElapsed-20)) {
3411 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3412 mHistoryAddTmp.setTo(mHistoryLastWritten);
3413 mHistoryAddTmp.wakelockTag = null;
3414 mHistoryAddTmp.wakeReasonTag = null;
3415 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3416 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
3417 addHistoryRecordInnerLocked(wakeElapsedTime, uptimeMs, mHistoryAddTmp);
3418 }
3419 }
3420 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3421 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3422 mTrackRunningHistoryUptime = uptimeMs;
3423 addHistoryRecordInnerLocked(elapsedRealtimeMs, uptimeMs, mHistoryCur);
3424 }
3425
3426 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
3427 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003428
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003429 if (!USE_OLD_HISTORY) {
3430 return;
3431 }
3432
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003433 if (!mHaveBatteryLevel || !mRecordingHistory) {
3434 return;
3435 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003436
3437 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003438 // and no states have since the last recorded entry changed and
3439 // are now resetting back to their original value, then just collapse
3440 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003441 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003442 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003443 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3444 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003445 // If the current is the same as the one before, then we no
3446 // longer need the entry.
3447 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003448 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003449 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003450 mHistoryLastEnd.next = null;
3451 mHistoryEnd.next = mHistoryCache;
3452 mHistoryCache = mHistoryEnd;
3453 mHistoryEnd = mHistoryLastEnd;
3454 mHistoryLastEnd = null;
3455 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003456 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3457 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003458 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003459 }
3460 return;
3461 }
3462
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003463 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003464 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003465
3466 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3467 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07003468 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003469 }
3470
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003471 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3472 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003473 // record changes to the battery level and the most interesting states.
3474 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003475 // record changes to the battery level.
3476 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003477 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003478 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003479 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003480 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003481 return;
3482 }
3483 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003484
Dianne Hackborn40c87252014-03-19 16:55:40 -07003485 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003486 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003487
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003488 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003489 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003490 mHistoryCur.eventCode = code;
3491 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3492 mHistoryCur.eventTag.string = name;
3493 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003494 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003495 }
3496
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003497 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003498 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003499 if (rec != null) {
3500 mHistoryCache = rec.next;
3501 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003502 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003503 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003504 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003505
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003506 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003507 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003508
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003509 void addHistoryRecordLocked(HistoryItem rec) {
3510 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003511 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003512 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003513 if (mHistoryEnd != null) {
3514 mHistoryEnd.next = rec;
3515 mHistoryEnd = rec;
3516 } else {
3517 mHistory = mHistoryEnd = rec;
3518 }
3519 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003520
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003521 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003522 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003523 if (USE_OLD_HISTORY) {
3524 if (mHistory != null) {
3525 mHistoryEnd.next = mHistoryCache;
3526 mHistoryCache = mHistory;
3527 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3528 }
3529 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003530 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003531
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003532 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003533 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003534 mTrackRunningHistoryElapsedRealtime = 0;
3535 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003536
3537 mHistoryBuffer.setDataSize(0);
3538 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003539 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003540 mHistoryLastLastWritten.clear();
3541 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003542 mHistoryTagPool.clear();
3543 mNextHistoryTagIdx = 0;
3544 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003545 mHistoryBufferLastPos = -1;
3546 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003547 mActiveHistoryStates = 0xffffffff;
3548 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003549 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003550
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003551 public void updateTimeBasesLocked(boolean unplugged, boolean screenOff, long uptime,
3552 long realtime) {
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003553 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3554 final boolean updateOnBatteryScreenOffTimeBase =
3555 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003556
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003557 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3558 if (updateOnBatteryScreenOffTimeBase) {
3559 updateKernelWakelocksLocked();
3560 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003561 }
Bookatz50df7112017-08-04 14:53:26 -07003562 updateRpmStatsLocked(); // if either OnBattery or OnBatteryScreenOff timebase changes.
Adam Lesinski72478f02015-06-17 15:39:43 -07003563 if (DEBUG_ENERGY_CPU) {
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003564 Slog.d(TAG, "Updating cpu time because screen is now " + (screenOff ? "off" : "on")
3565 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003566 }
Sudheer Shanka671985f2017-05-19 11:33:42 -07003567 updateCpuTimeLocked(true /* updateCpuFreqData */);
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003568
3569 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
3570 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
3571 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3572 final Uid u = mUidStats.valueAt(i);
3573 if (updateOnBatteryTimeBase) {
3574 u.updateOnBatteryBgTimeBase(uptime, realtime);
3575 }
3576 if (updateOnBatteryScreenOffTimeBase) {
3577 u.updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
3578 }
Bookatzc8c44962017-05-11 12:12:54 -07003579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003580 }
3581 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003582
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003583 private void updateBatteryPropertiesLocked() {
3584 try {
3585 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
3586 ServiceManager.getService("batteryproperties"));
3587 registrar.scheduleUpdate();
3588 } catch (RemoteException e) {
3589 // Ignore.
3590 }
3591 }
3592
Dianne Hackborn099bc622014-01-22 13:39:16 -08003593 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
3594 mIsolatedUids.put(isolatedUid, appUid);
3595 }
3596
Adam Lesinski61db88f2015-07-01 15:05:07 -07003597 /**
3598 * Schedules a read of the latest cpu times before removing the isolated UID.
3599 * @see #removeIsolatedUidLocked(int)
3600 */
3601 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003602 int curUid = mIsolatedUids.get(isolatedUid, -1);
3603 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07003604 if (mExternalSync != null) {
3605 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
3606 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08003607 }
3608 }
3609
Adam Lesinski61db88f2015-07-01 15:05:07 -07003610 /**
3611 * This should only be called after the cpu times have been read.
3612 * @see #scheduleRemoveIsolatedUidLocked(int, int)
3613 */
3614 public void removeIsolatedUidLocked(int isolatedUid) {
3615 mIsolatedUids.delete(isolatedUid);
3616 mKernelUidCpuTimeReader.removeUid(isolatedUid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -07003617 mKernelUidCpuFreqTimeReader.removeUid(isolatedUid);
Adam Lesinski61db88f2015-07-01 15:05:07 -07003618 }
3619
Dianne Hackborn099bc622014-01-22 13:39:16 -08003620 public int mapUid(int uid) {
3621 int isolated = mIsolatedUids.get(uid, -1);
3622 return isolated > 0 ? isolated : uid;
3623 }
3624
3625 public void noteEventLocked(int code, String name, int uid) {
3626 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003627 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3628 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003629 }
Joe Onoratoabded112016-02-08 16:49:39 -08003630 final long elapsedRealtime = mClocks.elapsedRealtime();
3631 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003632 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003633 }
3634
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003635 boolean ensureStartClockTime(final long currentTime) {
3636 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
3637 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
3638 // If the start clock time has changed by more than a year, then presumably
3639 // the previous time was completely bogus. So we are going to figure out a
3640 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08003641 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003642 return true;
3643 }
3644 return false;
3645 }
3646
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003647 public void noteCurrentTimeChangedLocked() {
3648 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003649 final long elapsedRealtime = mClocks.elapsedRealtime();
3650 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003651 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003652 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003653 }
3654
Dianne Hackborn61659e52014-07-09 16:13:01 -07003655 public void noteProcessStartLocked(String name, int uid) {
3656 uid = mapUid(uid);
3657 if (isOnBattery()) {
3658 Uid u = getUidStatsLocked(uid);
3659 u.getProcessStatsLocked(name).incStartsLocked();
3660 }
3661 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3662 return;
3663 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003664 if (!mRecordAllHistory) {
3665 return;
3666 }
Joe Onoratoabded112016-02-08 16:49:39 -08003667 final long elapsedRealtime = mClocks.elapsedRealtime();
3668 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07003669 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
3670 }
3671
Dianne Hackborn1e01d162014-12-04 17:46:42 -08003672 public void noteProcessCrashLocked(String name, int uid) {
3673 uid = mapUid(uid);
3674 if (isOnBattery()) {
3675 Uid u = getUidStatsLocked(uid);
3676 u.getProcessStatsLocked(name).incNumCrashesLocked();
3677 }
3678 }
3679
3680 public void noteProcessAnrLocked(String name, int uid) {
3681 uid = mapUid(uid);
3682 if (isOnBattery()) {
3683 Uid u = getUidStatsLocked(uid);
3684 u.getProcessStatsLocked(name).incNumAnrsLocked();
3685 }
3686 }
3687
Dianne Hackborna8d10942015-11-19 17:55:19 -08003688 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07003689 int parentUid = mapUid(uid);
3690 if (uid != parentUid) {
3691 // Isolated UIDs process state is already rolled up into parent, so no need to track
3692 // Otherwise the parent's process state will get downgraded incorrectly
3693 return;
3694 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08003695 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003696 }
3697
3698 public void noteProcessFinishLocked(String name, int uid) {
3699 uid = mapUid(uid);
3700 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
3701 return;
3702 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003703 if (!mRecordAllHistory) {
3704 return;
3705 }
Joe Onoratoabded112016-02-08 16:49:39 -08003706 final long elapsedRealtime = mClocks.elapsedRealtime();
3707 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003708 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003709 }
3710
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003711 public void noteSyncStartLocked(String name, int uid) {
3712 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003713 final long elapsedRealtime = mClocks.elapsedRealtime();
3714 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003715 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
3716 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
3717 return;
3718 }
3719 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
3720 }
3721
3722 public void noteSyncFinishLocked(String name, int uid) {
3723 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003724 final long elapsedRealtime = mClocks.elapsedRealtime();
3725 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003726 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
3727 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
3728 return;
3729 }
3730 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
3731 }
3732
3733 public void noteJobStartLocked(String name, int uid) {
3734 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003735 final long elapsedRealtime = mClocks.elapsedRealtime();
3736 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003737 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
3738 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
3739 return;
3740 }
3741 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
3742 }
3743
Dianne Hackborn94326cb2017-06-28 16:17:20 -07003744 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003745 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003746 final long elapsedRealtime = mClocks.elapsedRealtime();
3747 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07003748 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003749 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
3750 return;
3751 }
3752 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
3753 }
3754
Dianne Hackborn1e383822015-04-10 14:02:33 -07003755 public void noteAlarmStartLocked(String name, int uid) {
3756 if (!mRecordAllHistory) {
3757 return;
3758 }
3759 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003760 final long elapsedRealtime = mClocks.elapsedRealtime();
3761 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e383822015-04-10 14:02:33 -07003762 if (!mActiveEvents.updateState(HistoryItem.EVENT_ALARM_START, name, uid, 0)) {
3763 return;
3764 }
3765 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ALARM_START, name, uid);
3766 }
3767
3768 public void noteAlarmFinishLocked(String name, int uid) {
3769 if (!mRecordAllHistory) {
3770 return;
3771 }
3772 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003773 final long elapsedRealtime = mClocks.elapsedRealtime();
3774 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e383822015-04-10 14:02:33 -07003775 if (!mActiveEvents.updateState(HistoryItem.EVENT_ALARM_FINISH, name, uid, 0)) {
3776 return;
3777 }
3778 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ALARM_FINISH, name, uid);
3779 }
3780
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003781 private void requestWakelockCpuUpdate() {
3782 if (!mHandler.hasMessages(MSG_UPDATE_WAKELOCKS)) {
3783 Message m = mHandler.obtainMessage(MSG_UPDATE_WAKELOCKS);
3784 mHandler.sendMessageDelayed(m, DELAY_UPDATE_WAKELOCKS);
3785 }
3786 }
3787
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003788 private void requestImmediateCpuUpdate() {
3789 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
3790 mHandler.sendEmptyMessage(MSG_UPDATE_WAKELOCKS);
3791 }
3792
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003793 public void setRecordAllHistoryLocked(boolean enabled) {
3794 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003795 if (!enabled) {
3796 // Clear out any existing state.
3797 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003798 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003799 // Record the currently running processes as stopping, now that we are no
3800 // longer tracking them.
3801 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
3802 HistoryItem.EVENT_PROC);
3803 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08003804 long mSecRealtime = mClocks.elapsedRealtime();
3805 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003806 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
3807 SparseIntArray uids = ent.getValue();
3808 for (int j=0; j<uids.size(); j++) {
3809 addHistoryEventLocked(mSecRealtime, mSecUptime,
3810 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
3811 }
3812 }
3813 }
3814 } else {
3815 // Record the currently running processes as starting, now that we are tracking them.
3816 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
3817 HistoryItem.EVENT_PROC);
3818 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08003819 long mSecRealtime = mClocks.elapsedRealtime();
3820 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003821 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
3822 SparseIntArray uids = ent.getValue();
3823 for (int j=0; j<uids.size(); j++) {
3824 addHistoryEventLocked(mSecRealtime, mSecUptime,
3825 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
3826 }
3827 }
3828 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003829 }
3830 }
3831
Dianne Hackborn9a755432014-05-15 17:05:22 -07003832 public void setNoAutoReset(boolean enabled) {
3833 mNoAutoReset = enabled;
3834 }
3835
Amith Yamasani674c9bb2017-02-01 09:45:17 -08003836 public void setPretendScreenOff(boolean pretendScreenOff) {
3837 mPretendScreenOff = pretendScreenOff;
3838 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
3839 }
3840
Dianne Hackborn9a755432014-05-15 17:05:22 -07003841 private String mInitialAcquireWakeName;
3842 private int mInitialAcquireWakeUid = -1;
3843
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003844 public void noteStartWakeLocked(int uid, int pid, String name, String historyName, int type,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003845 boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003846 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003847 if (type == WAKE_TYPE_PARTIAL) {
3848 // Only care about partial wake locks, since full wake locks
3849 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003850 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07003851 if (historyName == null) {
3852 historyName = name;
3853 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003854 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07003855 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
3856 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07003857 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07003858 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07003859 }
3860 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003861 if (mWakeLockNesting == 0) {
3862 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
3863 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
3864 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003865 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003866 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07003867 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003868 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003869 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07003870 } else if (!mWakeLockImportant && !unimportantForLogging
3871 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003872 if (mHistoryLastWritten.wakelockTag != null) {
3873 // We'll try to update the last tag.
3874 mHistoryLastWritten.wakelockTag = null;
3875 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003876 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07003877 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003878 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003879 }
3880 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003881 }
3882 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003883 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003884 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07003885 if (mOnBatteryScreenOffTimeBase.isRunning()) {
3886 // We only update the cpu time when a wake lock is acquired if the screen is off.
3887 // If the screen is on, we don't distribute the power amongst partial wakelocks.
3888 if (DEBUG_ENERGY_CPU) {
3889 Slog.d(TAG, "Updating cpu time because of +wake_lock");
3890 }
3891 requestWakelockCpuUpdate();
3892 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08003893 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003894 }
3895 }
3896
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003897 public void noteStopWakeLocked(int uid, int pid, String name, String historyName, int type,
3898 long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003899 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003900 if (type == WAKE_TYPE_PARTIAL) {
3901 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003902 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07003903 if (historyName == null) {
3904 historyName = name;
3905 }
3906 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
3907 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07003908 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07003909 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07003910 }
3911 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003912 if (mWakeLockNesting == 0) {
3913 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
3914 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
3915 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07003916 mInitialAcquireWakeName = null;
3917 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003918 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003919 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003920 }
3921 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07003922 if (mOnBatteryScreenOffTimeBase.isRunning()) {
3923 if (DEBUG_ENERGY_CPU) {
3924 Slog.d(TAG, "Updating cpu time because of -wake_lock");
3925 }
3926 requestWakelockCpuUpdate();
3927 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08003928 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003929 }
3930 }
3931
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003932 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
3933 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08003934 final long elapsedRealtime = mClocks.elapsedRealtime();
3935 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003936 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003937 for (int i=0; i<N; i++) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003938 noteStartWakeLocked(ws.get(i), pid, name, historyName, type, unimportantForLogging,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003939 elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003940 }
3941 }
3942
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003943 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
3944 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003945 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08003946 final long elapsedRealtime = mClocks.elapsedRealtime();
3947 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003948 // For correct semantics, we start the need worksources first, so that we won't
3949 // make inappropriate history items as if all wake locks went away and new ones
3950 // appeared. This is okay because tracking of wake locks allows nesting.
Dianne Hackborn40c87252014-03-19 16:55:40 -07003951 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003952 for (int i=0; i<NN; i++) {
3953 noteStartWakeLocked(newWs.get(i), newPid, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003954 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003955 }
3956 final int NO = ws.size();
3957 for (int i=0; i<NO; i++) {
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003958 noteStopWakeLocked(ws.get(i), pid, name, historyName, type, elapsedRealtime, uptime);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003959 }
3960 }
3961
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003962 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
3963 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08003964 final long elapsedRealtime = mClocks.elapsedRealtime();
3965 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003966 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003967 for (int i=0; i<N; i++) {
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003968 noteStopWakeLocked(ws.get(i), pid, name, historyName, type, elapsedRealtime, uptime);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003969 }
3970 }
3971
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003972 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
3973 uid = mapUid(uid);
3974 final long elapsedRealtime = mClocks.elapsedRealtime();
3975 final long uptime = mClocks.uptimeMillis();
3976 if (historyName == null) {
3977 historyName = name;
3978 }
3979 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
3980 0)) {
3981 return;
3982 }
3983 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
3984 historyName, uid);
3985 }
3986
3987 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
3988 uid = mapUid(uid);
3989 final long elapsedRealtime = mClocks.elapsedRealtime();
3990 final long uptime = mClocks.uptimeMillis();
3991 if (historyName == null) {
3992 historyName = name;
3993 }
3994 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
3995 0)) {
3996 return;
3997 }
3998 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
3999 historyName, uid);
4000 }
4001
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004002 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
4003 if (mLastWakeupReason != null) {
4004 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004005 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07004006 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004007 mLastWakeupReason = null;
4008 }
4009 }
4010
4011 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08004012 final long elapsedRealtime = mClocks.elapsedRealtime();
4013 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07004014 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004015 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004016 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004017 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
4018 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004019 mHistoryCur.wakeReasonTag.uid = 0;
4020 mLastWakeupReason = reason;
4021 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07004022 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08004023 }
4024
Adam Lesinski72478f02015-06-17 15:39:43 -07004025 public boolean startAddingCpuLocked() {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004026 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
Adam Lesinski72478f02015-06-17 15:39:43 -07004027 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004028 }
4029
Adam Lesinski72478f02015-06-17 15:39:43 -07004030 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4031 int statSystemTime, int statIOWaitTime, int statIrqTime,
4032 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004033 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4034 + " user=" + statUserTime + " sys=" + statSystemTime
4035 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4036 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4037 mCurStepCpuUserTime += totalUTime;
4038 mCurStepCpuSystemTime += totalSTime;
4039 mCurStepStatUserTime += statUserTime;
4040 mCurStepStatSystemTime += statSystemTime;
4041 mCurStepStatIOWaitTime += statIOWaitTime;
4042 mCurStepStatIrqTime += statIrqTime;
4043 mCurStepStatSoftIrqTime += statSoftIrqTime;
4044 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004045 }
4046
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004047 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004048 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004049 Uid u = mUidStats.get(uid);
4050 if (u != null) {
4051 u.mPids.remove(pid);
4052 }
4053 }
4054
4055 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004056 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004057 Uid u = mUidStats.get(uid);
4058 if (u != null) {
4059 Uid.Pid p = u.mPids.get(pid);
4060 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004061 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004062 }
4063 }
4064 return 0;
4065 }
4066
Dianne Hackborn287952c2010-09-22 22:34:31 -07004067 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004068 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004069 Uid u = mUidStats.get(uid);
4070 if (u != null) {
4071 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4072 }
4073 }
4074
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004075 int mSensorNesting;
4076
4077 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004078 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004079 final long elapsedRealtime = mClocks.elapsedRealtime();
4080 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004081 if (mSensorNesting == 0) {
4082 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4083 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4084 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004085 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004086 }
4087 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004088 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004089 }
4090
4091 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004092 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004093 final long elapsedRealtime = mClocks.elapsedRealtime();
4094 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004095 mSensorNesting--;
4096 if (mSensorNesting == 0) {
4097 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4098 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4099 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004100 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004101 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004102 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004103 }
4104
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004105 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004106
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004107 public void noteStartGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004108 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004109 final long elapsedRealtime = mClocks.elapsedRealtime();
4110 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004111 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004112 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004113 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4114 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004115 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004116 }
4117 mGpsNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004118 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004120
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004121 public void noteStopGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004122 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004123 final long elapsedRealtime = mClocks.elapsedRealtime();
4124 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004125 mGpsNesting--;
4126 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004127 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004128 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4129 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004130 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004131 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004132 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004134
Jeff Browne95c3cd2014-05-02 16:59:26 -07004135 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004136 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004137
4138 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4139 // original 4 are mapped to one of the originals.
4140 if (state > MAX_TRACKED_SCREEN_STATE) {
4141 switch (state) {
4142 case Display.STATE_VR:
4143 state = Display.STATE_ON;
4144 break;
4145 default:
4146 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4147 break;
4148 }
4149 }
4150
Jeff Browne95c3cd2014-05-02 16:59:26 -07004151 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004152 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004153 final int oldState = mScreenState;
4154 mScreenState = state;
4155 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4156 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004157
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004158 if (state != Display.STATE_UNKNOWN) {
4159 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004160 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4161 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4162 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004163 } else {
4164 Slog.wtf(TAG, "Unexpected screen state: " + state);
4165 }
4166 }
4167
Jeff Browne95c3cd2014-05-02 16:59:26 -07004168 if (state == Display.STATE_ON) {
4169 // Screen turning on.
Joe Onoratoabded112016-02-08 16:49:39 -08004170 final long elapsedRealtime = mClocks.elapsedRealtime();
4171 final long uptime = mClocks.uptimeMillis();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004172 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4173 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4174 + Integer.toHexString(mHistoryCur.states));
4175 addHistoryRecordLocked(elapsedRealtime, uptime);
4176 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4177 if (mScreenBrightnessBin >= 0) {
4178 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4179 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004180
Jeff Browne95c3cd2014-05-02 16:59:26 -07004181 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), false,
Joe Onoratoabded112016-02-08 16:49:39 -08004182 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004183
Jeff Browne95c3cd2014-05-02 16:59:26 -07004184 // Fake a wake lock, so we consider the device waked as long
4185 // as the screen is on.
4186 noteStartWakeLocked(-1, -1, "screen", null, WAKE_TYPE_PARTIAL, false,
4187 elapsedRealtime, uptime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004188
Jeff Browne95c3cd2014-05-02 16:59:26 -07004189 // Update discharge amounts.
4190 if (mOnBatteryInternal) {
4191 updateDischargeScreenLevelsLocked(false, true);
4192 }
4193 } else if (oldState == Display.STATE_ON) {
4194 // Screen turning off or dozing.
Joe Onoratoabded112016-02-08 16:49:39 -08004195 final long elapsedRealtime = mClocks.elapsedRealtime();
4196 final long uptime = mClocks.uptimeMillis();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004197 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4198 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4199 + Integer.toHexString(mHistoryCur.states));
4200 addHistoryRecordLocked(elapsedRealtime, uptime);
4201 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4202 if (mScreenBrightnessBin >= 0) {
4203 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4204 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004205
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004206 noteStopWakeLocked(-1, -1, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004207 elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004208
Jeff Browne95c3cd2014-05-02 16:59:26 -07004209 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), true,
Joe Onoratoabded112016-02-08 16:49:39 -08004210 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004211
Jeff Browne95c3cd2014-05-02 16:59:26 -07004212 // Update discharge amounts.
4213 if (mOnBatteryInternal) {
4214 updateDischargeScreenLevelsLocked(true, false);
4215 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004216 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004217 }
4218 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004219
Dianne Hackborn617f8772009-03-31 15:04:46 -07004220 public void noteScreenBrightnessLocked(int brightness) {
4221 // Bin the brightness.
4222 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4223 if (bin < 0) bin = 0;
4224 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4225 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004226 final long elapsedRealtime = mClocks.elapsedRealtime();
4227 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004228 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4229 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004230 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4231 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004232 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004233 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004234 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004235 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004236 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004237 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004238 }
4239 mScreenBrightnessBin = bin;
4240 }
4241 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004242
Dianne Hackborn617f8772009-03-31 15:04:46 -07004243 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004244 if (mOnBatteryInternal) {
4245 uid = mapUid(uid);
4246 getUidStatsLocked(uid).noteUserActivityLocked(event);
4247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004249
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004250 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004251 final long elapsedRealtime = mClocks.elapsedRealtime();
4252 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004253 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4254 reason, reasonUid);
4255 }
4256
Jeff Browne95c3cd2014-05-02 16:59:26 -07004257 public void noteInteractiveLocked(boolean interactive) {
4258 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08004259 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004260 mInteractive = interactive;
4261 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
4262 if (interactive) {
4263 mInteractiveTimer.startRunningLocked(elapsedRealtime);
4264 } else {
4265 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
4266 }
4267 }
4268 }
4269
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004270 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004271 final long elapsedRealtime = mClocks.elapsedRealtime();
4272 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004273 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4274 extra, type);
4275 mNumConnectivityChange++;
4276 }
4277
Adam Lesinski5f056f62016-07-14 16:56:08 -07004278 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4279 final long uptimeMillis, int uid) {
4280 uid = mapUid(uid);
4281 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4282 uid);
4283 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4284 }
4285
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004286 /**
4287 * Updates the radio power state and returns true if an external stats collection should occur.
4288 */
4289 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004290 final long elapsedRealtime = mClocks.elapsedRealtime();
4291 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004292 if (mMobileRadioPowerState != powerState) {
4293 long realElapsedRealtimeMs;
4294 final boolean active =
4295 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4296 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4297 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004298 if (uid > 0) {
4299 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4300 }
4301
Adam Lesinski9acfd812016-04-19 18:29:50 -07004302 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004303 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4304 } else {
4305 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004306 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004307 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4308 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4309 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004310 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004311 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4312 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4313 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004314 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004315 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4316 }
4317 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4318 + Integer.toHexString(mHistoryCur.states));
4319 addHistoryRecordLocked(elapsedRealtime, uptime);
4320 mMobileRadioPowerState = powerState;
4321 if (active) {
4322 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4323 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4324 } else {
4325 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004326 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004327 // Tell the caller to collect radio network/power stats.
4328 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004329 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004330 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004331 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004332 }
4333
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004334 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004335 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004336 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4337 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4338 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004339 final long elapsedRealtime = mClocks.elapsedRealtime();
4340 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004341 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004342 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004343 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4344 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004345 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004346 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004347 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004348 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4349 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004350 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004351 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004352 }
4353 addHistoryRecordLocked(elapsedRealtime, uptime);
4354 }
4355 }
4356
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004357 public void noteDeviceIdleModeLocked(int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004358 final long elapsedRealtime = mClocks.elapsedRealtime();
4359 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004360 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004361 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004362 // We don't go out of general idling mode until explicitly taken out of
4363 // device idle through going active or significant motion.
4364 nowIdling = true;
4365 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004366 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
4367 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
4368 // We don't go out of general light idling mode until explicitly taken out of
4369 // device idle through going active or significant motion.
4370 nowLightIdling = true;
4371 }
4372 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
4373 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
4374 activeReason, activeUid);
4375 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004376 if (mDeviceIdling != nowIdling) {
4377 mDeviceIdling = nowIdling;
4378 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
4379 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
4380 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004381 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004382 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
4383 } else {
4384 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
4385 }
4386 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004387 if (mDeviceLightIdling != nowLightIdling) {
4388 mDeviceLightIdling = nowLightIdling;
4389 if (nowLightIdling) {
4390 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004391 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004392 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004393 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004394 }
4395 if (mDeviceIdleMode != mode) {
4396 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
4397 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
4398 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
4399 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004400 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004401 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
4402 mLastIdleTimeStart = elapsedRealtime;
4403 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
4404 if (lastDuration > mLongestLightIdleTime) {
4405 mLongestLightIdleTime = lastDuration;
4406 }
4407 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004408 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004409 if (lastDuration > mLongestFullIdleTime) {
4410 mLongestFullIdleTime = lastDuration;
4411 }
4412 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
4413 }
4414 if (mode == DEVICE_IDLE_MODE_LIGHT) {
4415 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004416 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004417 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
4418 }
4419 mDeviceIdleMode = mode;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004420 }
4421 }
4422
4423 public void notePackageInstalledLocked(String pkgName, int versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08004424 final long elapsedRealtime = mClocks.elapsedRealtime();
4425 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004426 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
4427 pkgName, versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004428 PackageChange pc = new PackageChange();
4429 pc.mPackageName = pkgName;
4430 pc.mUpdate = true;
4431 pc.mVersionCode = versionCode;
4432 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004433 }
4434
4435 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08004436 final long elapsedRealtime = mClocks.elapsedRealtime();
4437 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004438 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
4439 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004440 PackageChange pc = new PackageChange();
4441 pc.mPackageName = pkgName;
4442 pc.mUpdate = true;
4443 addPackageChange(pc);
4444 }
4445
4446 private void addPackageChange(PackageChange pc) {
4447 if (mDailyPackageChanges == null) {
4448 mDailyPackageChanges = new ArrayList<>();
4449 }
4450 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004451 }
4452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 public void notePhoneOnLocked() {
4454 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004455 final long elapsedRealtime = mClocks.elapsedRealtime();
4456 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004457 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004458 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
4459 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004460 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004462 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 }
4464 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 public void notePhoneOffLocked() {
4467 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004468 final long elapsedRealtime = mClocks.elapsedRealtime();
4469 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004470 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004471 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
4472 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004473 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004475 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 }
4477 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07004478
Dianne Hackborn3251b902014-06-20 14:40:53 -07004479 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08004480 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08004481 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004482 if (i == except) {
4483 continue;
4484 }
4485 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004486 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004487 }
4488 }
4489 }
4490
Dianne Hackborne4a59512010-12-07 11:08:07 -08004491 private int fixPhoneServiceState(int state, int signalBin) {
4492 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
4493 // In this case we will always be STATE_OUT_OF_SERVICE, so need
4494 // to infer that we are scanning from other data.
4495 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08004496 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004497 state = ServiceState.STATE_IN_SERVICE;
4498 }
4499 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004500
Dianne Hackborne4a59512010-12-07 11:08:07 -08004501 return state;
4502 }
4503
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004504 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004505 boolean scanning = false;
4506 boolean newHistory = false;
4507
4508 mPhoneServiceStateRaw = state;
4509 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004510 mPhoneSignalStrengthBinRaw = strengthBin;
4511
Joe Onoratoabded112016-02-08 16:49:39 -08004512 final long elapsedRealtime = mClocks.elapsedRealtime();
4513 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08004514
4515 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
4516 // In this case we will always be STATE_OUT_OF_SERVICE, so need
4517 // to infer that we are scanning from other data.
4518 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004519 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004520 state = ServiceState.STATE_IN_SERVICE;
4521 }
4522 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004523
4524 // If the phone is powered off, stop all timers.
4525 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004526 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07004527
Dianne Hackborne4a59512010-12-07 11:08:07 -08004528 // If we are in service, make sure the correct signal string timer is running.
4529 } else if (state == ServiceState.STATE_IN_SERVICE) {
4530 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004531
4532 // If we're out of service, we are in the lowest signal strength
4533 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07004534 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004535 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004536 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07004537 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004538 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08004539 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004540 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
4541 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004542 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07004543 }
4544 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004545
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004546 if (!scanning) {
4547 // If we are no longer scanning, then stop the scanning timer.
4548 if (mPhoneSignalScanningTimer.isRunningLocked()) {
4549 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
4550 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
4551 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08004552 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004553 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004554 }
4555 }
4556
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004557 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004558 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
4559 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004560 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004561 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08004562 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004563 mPhoneServiceState = state;
4564 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08004565
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004566 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004567 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004568 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004569 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004570 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004571 if (strengthBin >= 0) {
4572 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004573 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004574 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07004575 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
4576 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004577 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08004578 + Integer.toHexString(mHistoryCur.states));
4579 newHistory = true;
4580 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07004581 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004582 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004583 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08004584 }
4585
4586 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07004587 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004588 }
4589 }
4590
4591 /**
4592 * Telephony stack updates the phone state.
4593 * @param state phone state from ServiceState.getState()
4594 */
4595 public void notePhoneStateLocked(int state, int simState) {
4596 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07004597 }
4598
Wink Savillee9b06d72009-05-18 21:47:50 -07004599 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07004600 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08004601 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08004602 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004603 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004604
Dianne Hackborn627bba72009-03-24 22:32:56 -07004605 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
4606 int bin = DATA_CONNECTION_NONE;
4607 if (hasData) {
4608 switch (dataType) {
4609 case TelephonyManager.NETWORK_TYPE_EDGE:
4610 bin = DATA_CONNECTION_EDGE;
4611 break;
4612 case TelephonyManager.NETWORK_TYPE_GPRS:
4613 bin = DATA_CONNECTION_GPRS;
4614 break;
4615 case TelephonyManager.NETWORK_TYPE_UMTS:
4616 bin = DATA_CONNECTION_UMTS;
4617 break;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004618 case TelephonyManager.NETWORK_TYPE_CDMA:
4619 bin = DATA_CONNECTION_CDMA;
4620 break;
4621 case TelephonyManager.NETWORK_TYPE_EVDO_0:
4622 bin = DATA_CONNECTION_EVDO_0;
4623 break;
4624 case TelephonyManager.NETWORK_TYPE_EVDO_A:
4625 bin = DATA_CONNECTION_EVDO_A;
4626 break;
4627 case TelephonyManager.NETWORK_TYPE_1xRTT:
4628 bin = DATA_CONNECTION_1xRTT;
4629 break;
4630 case TelephonyManager.NETWORK_TYPE_HSDPA:
4631 bin = DATA_CONNECTION_HSDPA;
4632 break;
4633 case TelephonyManager.NETWORK_TYPE_HSUPA:
4634 bin = DATA_CONNECTION_HSUPA;
4635 break;
4636 case TelephonyManager.NETWORK_TYPE_HSPA:
4637 bin = DATA_CONNECTION_HSPA;
4638 break;
4639 case TelephonyManager.NETWORK_TYPE_IDEN:
4640 bin = DATA_CONNECTION_IDEN;
4641 break;
4642 case TelephonyManager.NETWORK_TYPE_EVDO_B:
4643 bin = DATA_CONNECTION_EVDO_B;
4644 break;
Robert Greenwalt962a9902010-11-02 11:10:25 -07004645 case TelephonyManager.NETWORK_TYPE_LTE:
4646 bin = DATA_CONNECTION_LTE;
4647 break;
4648 case TelephonyManager.NETWORK_TYPE_EHRPD:
4649 bin = DATA_CONNECTION_EHRPD;
4650 break;
Patrick Tjinb71703c2013-11-06 09:27:03 -08004651 case TelephonyManager.NETWORK_TYPE_HSPAP:
4652 bin = DATA_CONNECTION_HSPAP;
4653 break;
Dianne Hackborn627bba72009-03-24 22:32:56 -07004654 default:
4655 bin = DATA_CONNECTION_OTHER;
4656 break;
4657 }
4658 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004659 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004660 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004661 final long elapsedRealtime = mClocks.elapsedRealtime();
4662 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004663 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
4664 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004665 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
4666 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004667 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004668 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004669 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004670 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004671 }
4672 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004673 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004674 }
4675 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004676
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004677 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07004678 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004679 final long elapsedRealtime = mClocks.elapsedRealtime();
4680 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07004681 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004682 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
4683 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004684 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07004685 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004686 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004687 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07004688 }
4689 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004690
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004691 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08004692 final long elapsedRealtime = mClocks.elapsedRealtime();
4693 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07004694 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07004695 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004696 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
4697 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004698 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07004699 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004700 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004701 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07004702 }
4703 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004704
4705 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004706 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004707 final long elapsedRealtime = mClocks.elapsedRealtime();
4708 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004709 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004710 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004711 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
4712 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004713 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004714 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004715 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004716 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004717 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004718 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004719
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004720 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004721 if (mAudioOnNesting == 0) {
4722 return;
4723 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004724 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004725 final long elapsedRealtime = mClocks.elapsedRealtime();
4726 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004727 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004728 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004729 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
4730 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004731 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004732 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004733 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004734 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004735 }
4736
4737 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004738 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004739 final long elapsedRealtime = mClocks.elapsedRealtime();
4740 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004741 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004742 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004743 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
4744 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004745 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004746 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004747 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004748 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004749 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004750 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004751
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004752 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004753 if (mVideoOnNesting == 0) {
4754 return;
4755 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004756 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004757 final long elapsedRealtime = mClocks.elapsedRealtime();
4758 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004759 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004760 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004761 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
4762 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004763 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004764 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004765 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004766 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004767 }
4768
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004769 public void noteResetAudioLocked() {
4770 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004771 final long elapsedRealtime = mClocks.elapsedRealtime();
4772 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004773 mAudioOnNesting = 0;
4774 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
4775 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
4776 + Integer.toHexString(mHistoryCur.states));
4777 addHistoryRecordLocked(elapsedRealtime, uptime);
4778 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
4779 for (int i=0; i<mUidStats.size(); i++) {
4780 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4781 uid.noteResetAudioLocked(elapsedRealtime);
4782 }
4783 }
4784 }
4785
4786 public void noteResetVideoLocked() {
4787 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004788 final long elapsedRealtime = mClocks.elapsedRealtime();
4789 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004790 mAudioOnNesting = 0;
4791 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
4792 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
4793 + Integer.toHexString(mHistoryCur.states));
4794 addHistoryRecordLocked(elapsedRealtime, uptime);
4795 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
4796 for (int i=0; i<mUidStats.size(); i++) {
4797 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4798 uid.noteResetVideoLocked(elapsedRealtime);
4799 }
4800 }
4801 }
4802
Jeff Sharkey3e013e82013-04-25 14:48:19 -07004803 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004804 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004805 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07004806 }
4807
4808 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004809 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004810 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07004811 }
4812
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004813 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004814 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004815 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
4816 }
4817
4818 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004819 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004820 getUidStatsLocked(uid).noteVibratorOffLocked();
4821 }
4822
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004823 public void noteFlashlightOnLocked(int uid) {
4824 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004825 final long elapsedRealtime = mClocks.elapsedRealtime();
4826 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004827 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004828 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
4829 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004830 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004831 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004832 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
4833 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004834 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
4835 }
4836
4837 public void noteFlashlightOffLocked(int uid) {
4838 if (mFlashlightOnNesting == 0) {
4839 return;
4840 }
4841 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004842 final long elapsedRealtime = mClocks.elapsedRealtime();
4843 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004844 if (--mFlashlightOnNesting == 0) {
4845 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
4846 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
4847 + Integer.toHexString(mHistoryCur.states2));
4848 addHistoryRecordLocked(elapsedRealtime, uptime);
4849 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
4850 }
4851 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
4852 }
4853
4854 public void noteCameraOnLocked(int uid) {
4855 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004856 final long elapsedRealtime = mClocks.elapsedRealtime();
4857 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004858 if (mCameraOnNesting++ == 0) {
4859 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
4860 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
4861 + Integer.toHexString(mHistoryCur.states2));
4862 addHistoryRecordLocked(elapsedRealtime, uptime);
4863 mCameraOnTimer.startRunningLocked(elapsedRealtime);
4864 }
4865 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
4866 }
4867
4868 public void noteCameraOffLocked(int uid) {
4869 if (mCameraOnNesting == 0) {
4870 return;
4871 }
4872 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004873 final long elapsedRealtime = mClocks.elapsedRealtime();
4874 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004875 if (--mCameraOnNesting == 0) {
4876 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
4877 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
4878 + Integer.toHexString(mHistoryCur.states2));
4879 addHistoryRecordLocked(elapsedRealtime, uptime);
4880 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
4881 }
4882 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
4883 }
4884
4885 public void noteResetCameraLocked() {
4886 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004887 final long elapsedRealtime = mClocks.elapsedRealtime();
4888 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004889 mCameraOnNesting = 0;
4890 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
4891 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
4892 + Integer.toHexString(mHistoryCur.states2));
4893 addHistoryRecordLocked(elapsedRealtime, uptime);
4894 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
4895 for (int i=0; i<mUidStats.size(); i++) {
4896 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4897 uid.noteResetCameraLocked(elapsedRealtime);
4898 }
4899 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004900 }
4901
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004902 public void noteResetFlashlightLocked() {
4903 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004904 final long elapsedRealtime = mClocks.elapsedRealtime();
4905 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004906 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004907 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
4908 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004909 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004910 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004911 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
4912 for (int i=0; i<mUidStats.size(); i++) {
4913 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4914 uid.noteResetFlashlightLocked(elapsedRealtime);
4915 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004916 }
4917 }
4918
Bookatzb1f04f32017-05-19 13:57:32 -07004919 private void noteBluetoothScanStartedLocked(int uid, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004920 uid = mapUid(uid);
Bookatz867c0d72017-03-07 18:23:42 -08004921 final long elapsedRealtime = mClocks.elapsedRealtime();
4922 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004923 if (mBluetoothScanNesting == 0) {
4924 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
4925 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
4926 + Integer.toHexString(mHistoryCur.states2));
4927 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07004928 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004929 }
4930 mBluetoothScanNesting++;
Bookatzb1f04f32017-05-19 13:57:32 -07004931 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004932 }
4933
Bookatzb1f04f32017-05-19 13:57:32 -07004934 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004935 final int N = ws.size();
4936 for (int i = 0; i < N; i++) {
Bookatzb1f04f32017-05-19 13:57:32 -07004937 noteBluetoothScanStartedLocked(ws.get(i), isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004938 }
4939 }
4940
Bookatz94c5a312017-07-11 16:49:17 -07004941 private void noteBluetoothScanStoppedLocked(int uid, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004942 uid = mapUid(uid);
Bookatz867c0d72017-03-07 18:23:42 -08004943 final long elapsedRealtime = mClocks.elapsedRealtime();
4944 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004945 mBluetoothScanNesting--;
4946 if (mBluetoothScanNesting == 0) {
4947 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
4948 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
4949 + Integer.toHexString(mHistoryCur.states2));
4950 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07004951 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004952 }
Bookatz94c5a312017-07-11 16:49:17 -07004953 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004954 }
4955
Bookatz94c5a312017-07-11 16:49:17 -07004956 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004957 final int N = ws.size();
4958 for (int i = 0; i < N; i++) {
Bookatz94c5a312017-07-11 16:49:17 -07004959 noteBluetoothScanStoppedLocked(ws.get(i), isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004960 }
4961 }
4962
4963 public void noteResetBluetoothScanLocked() {
4964 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08004965 final long elapsedRealtime = mClocks.elapsedRealtime();
4966 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004967 mBluetoothScanNesting = 0;
4968 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
4969 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
4970 + Integer.toHexString(mHistoryCur.states2));
4971 addHistoryRecordLocked(elapsedRealtime, uptime);
4972 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
4973 for (int i=0; i<mUidStats.size(); i++) {
4974 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4975 uid.noteResetBluetoothScanLocked(elapsedRealtime);
4976 }
4977 }
4978 }
4979
Bookatz4ebc0642017-05-11 12:21:19 -07004980 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07004981 final int N = ws.size();
4982 for (int i = 0; i < N; i++) {
4983 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07004984 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07004985 }
4986 }
4987
Adam Lesinski5f056f62016-07-14 16:56:08 -07004988 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
4989 final long uptimeMillis, int uid) {
4990 uid = mapUid(uid);
4991 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4992 uid);
4993 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
4994 }
4995
4996 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004997 final long elapsedRealtime = mClocks.elapsedRealtime();
4998 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004999 if (mWifiRadioPowerState != powerState) {
5000 final boolean active =
5001 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
5002 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
5003 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07005004 if (uid > 0) {
5005 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
5006 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07005007 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
5008 } else {
5009 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
5010 }
5011 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
5012 + Integer.toHexString(mHistoryCur.states));
5013 addHistoryRecordLocked(elapsedRealtime, uptime);
5014 mWifiRadioPowerState = powerState;
5015 }
5016 }
5017
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005018 public void noteWifiRunningLocked(WorkSource ws) {
5019 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005020 final long elapsedRealtime = mClocks.elapsedRealtime();
5021 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005022 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005023 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5024 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005025 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005026 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005027 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005028 int N = ws.size();
5029 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005030 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005031 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005032 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005033 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005034 } else {
5035 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005036 }
5037 }
5038
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005039 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5040 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005041 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005042 int N = oldWs.size();
5043 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005044 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005045 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005046 }
5047 N = newWs.size();
5048 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005049 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005050 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005051 }
5052 } else {
5053 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5054 }
5055 }
5056
5057 public void noteWifiStoppedLocked(WorkSource ws) {
5058 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005059 final long elapsedRealtime = mClocks.elapsedRealtime();
5060 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005061 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005062 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5063 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005064 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005065 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005066 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005067 int N = ws.size();
5068 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005069 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005070 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005071 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005072 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005073 } else {
5074 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005075 }
5076 }
5077
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005078 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5079 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5080 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005081 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005082 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005083 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005084 }
5085 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005086 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005087 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005088 }
5089 }
5090
Dianne Hackborn3251b902014-06-20 14:40:53 -07005091 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5092 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5093 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005094 final long elapsedRealtime = mClocks.elapsedRealtime();
5095 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005096 if (mWifiSupplState >= 0) {
5097 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5098 }
5099 mWifiSupplState = supplState;
5100 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5101 mHistoryCur.states2 =
5102 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5103 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5104 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5105 + Integer.toHexString(mHistoryCur.states2));
5106 addHistoryRecordLocked(elapsedRealtime, uptime);
5107 }
5108 }
5109
5110 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005111 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005112 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5113 if (i == except) {
5114 continue;
5115 }
5116 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5117 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5118 }
5119 }
5120 }
5121
5122 public void noteWifiRssiChangedLocked(int newRssi) {
5123 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5124 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5125 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005126 final long elapsedRealtime = mClocks.elapsedRealtime();
5127 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005128 if (mWifiSignalStrengthBin >= 0) {
5129 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5130 elapsedRealtime);
5131 }
5132 if (strengthBin >= 0) {
5133 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5134 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
5135 }
5136 mHistoryCur.states2 =
5137 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5138 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5139 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5140 + Integer.toHexString(mHistoryCur.states2));
5141 addHistoryRecordLocked(elapsedRealtime, uptime);
5142 } else {
5143 stopAllWifiSignalStrengthTimersLocked(-1);
5144 }
5145 mWifiSignalStrengthBin = strengthBin;
5146 }
5147 }
5148
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005149 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005150
The Android Open Source Project10592532009-03-18 17:39:46 -07005151 public void noteFullWifiLockAcquiredLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005152 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005153 final long elapsedRealtime = mClocks.elapsedRealtime();
5154 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005155 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005156 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005157 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5158 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005159 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005160 }
5161 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005162 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005163 }
5164
5165 public void noteFullWifiLockReleasedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005166 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005167 final long elapsedRealtime = mClocks.elapsedRealtime();
5168 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005169 mWifiFullLockNesting--;
5170 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005171 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005172 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
5173 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005174 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005175 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005176 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005177 }
5178
Nick Pelly6ccaa542012-06-15 15:22:47 -07005179 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005180
Nick Pelly6ccaa542012-06-15 15:22:47 -07005181 public void noteWifiScanStartedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005182 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005183 final long elapsedRealtime = mClocks.elapsedRealtime();
5184 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005185 if (mWifiScanNesting == 0) {
5186 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
5187 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005188 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005189 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005190 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07005191 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005192 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005193 }
5194
Nick Pelly6ccaa542012-06-15 15:22:47 -07005195 public void noteWifiScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005196 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005197 final long elapsedRealtime = mClocks.elapsedRealtime();
5198 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005199 mWifiScanNesting--;
5200 if (mWifiScanNesting == 0) {
5201 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
5202 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005203 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005204 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005205 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005206 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005207 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005208
Robert Greenwalta029ea12013-09-25 16:38:12 -07005209 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005210 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005211 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005212 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005213 }
5214
5215 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005216 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005217 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005218 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005219 }
5220
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005221 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005222
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005223 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005224 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005225 final long elapsedRealtime = mClocks.elapsedRealtime();
5226 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005227 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005228 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005229 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
5230 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005231 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005232 }
5233 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005234 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005235 }
5236
5237 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005238 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005239 final long elapsedRealtime = mClocks.elapsedRealtime();
5240 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005241 mWifiMulticastNesting--;
5242 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005243 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005244 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
5245 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005246 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005247 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005248 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005249 }
5250
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005251 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
5252 int N = ws.size();
5253 for (int i=0; i<N; i++) {
5254 noteFullWifiLockAcquiredLocked(ws.get(i));
5255 }
5256 }
5257
5258 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
5259 int N = ws.size();
5260 for (int i=0; i<N; i++) {
5261 noteFullWifiLockReleasedLocked(ws.get(i));
5262 }
5263 }
5264
Nick Pelly6ccaa542012-06-15 15:22:47 -07005265 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005266 int N = ws.size();
5267 for (int i=0; i<N; i++) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005268 noteWifiScanStartedLocked(ws.get(i));
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005269 }
5270 }
5271
Nick Pelly6ccaa542012-06-15 15:22:47 -07005272 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005273 int N = ws.size();
5274 for (int i=0; i<N; i++) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005275 noteWifiScanStoppedLocked(ws.get(i));
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005276 }
5277 }
5278
Robert Greenwalta029ea12013-09-25 16:38:12 -07005279 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
5280 int N = ws.size();
5281 for (int i=0; i<N; i++) {
5282 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
5283 }
5284 }
5285
5286 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
5287 int N = ws.size();
5288 for (int i=0; i<N; i++) {
5289 noteWifiBatchedScanStoppedLocked(ws.get(i));
5290 }
5291 }
5292
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005293 public void noteWifiMulticastEnabledFromSourceLocked(WorkSource ws) {
5294 int N = ws.size();
5295 for (int i=0; i<N; i++) {
5296 noteWifiMulticastEnabledLocked(ws.get(i));
5297 }
5298 }
5299
5300 public void noteWifiMulticastDisabledFromSourceLocked(WorkSource ws) {
5301 int N = ws.size();
5302 for (int i=0; i<N; i++) {
5303 noteWifiMulticastDisabledLocked(ws.get(i));
5304 }
5305 }
5306
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08005307 private static String[] includeInStringArray(String[] array, String str) {
5308 if (ArrayUtils.indexOf(array, str) >= 0) {
5309 return array;
5310 }
5311 String[] newArray = new String[array.length+1];
5312 System.arraycopy(array, 0, newArray, 0, array.length);
5313 newArray[array.length] = str;
5314 return newArray;
5315 }
5316
5317 private static String[] excludeFromStringArray(String[] array, String str) {
5318 int index = ArrayUtils.indexOf(array, str);
5319 if (index >= 0) {
5320 String[] newArray = new String[array.length-1];
5321 if (index > 0) {
5322 System.arraycopy(array, 0, newArray, 0, index);
5323 }
5324 if (index < array.length-1) {
5325 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
5326 }
5327 return newArray;
5328 }
5329 return array;
5330 }
5331
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07005332 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07005333 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005334
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005335 synchronized (mModemNetworkLock) {
5336 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
5337 mModemIfaces = includeInStringArray(mModemIfaces, iface);
5338 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
5339 } else {
5340 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
5341 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
5342 }
5343 }
5344
5345 synchronized (mWifiNetworkLock) {
5346 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
5347 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
5348 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
5349 } else {
5350 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
5351 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
5352 }
5353 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07005354 }
5355
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005356 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
5357 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005358 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005359
Dianne Hackborn77b987f2014-02-26 16:20:52 -08005360 @Override public int getScreenOnCount(int which) {
5361 return mScreenOnTimer.getCountLocked(which);
5362 }
5363
Dianne Hackborn617f8772009-03-31 15:04:46 -07005364 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005365 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005366 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005367 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005368 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005369
Jeff Browne95c3cd2014-05-02 16:59:26 -07005370 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
5371 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005372 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005373
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005374 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
5375 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005376 }
5377
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005378 @Override public int getPowerSaveModeEnabledCount(int which) {
5379 return mPowerSaveModeEnabledTimer.getCountLocked(which);
5380 }
5381
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005382 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
5383 int which) {
5384 switch (mode) {
5385 case DEVICE_IDLE_MODE_LIGHT:
5386 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005387 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005388 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5389 }
5390 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005391 }
5392
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005393 @Override public int getDeviceIdleModeCount(int mode, int which) {
5394 switch (mode) {
5395 case DEVICE_IDLE_MODE_LIGHT:
5396 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005397 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005398 return mDeviceIdleModeFullTimer.getCountLocked(which);
5399 }
5400 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005401 }
5402
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005403 @Override public long getLongestDeviceIdleModeTime(int mode) {
5404 switch (mode) {
5405 case DEVICE_IDLE_MODE_LIGHT:
5406 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005407 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005408 return mLongestFullIdleTime;
5409 }
5410 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005411 }
5412
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005413 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
5414 switch (mode) {
5415 case DEVICE_IDLE_MODE_LIGHT:
5416 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005417 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005418 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5419 }
5420 return 0;
5421 }
5422
5423 @Override public int getDeviceIdlingCount(int mode, int which) {
5424 switch (mode) {
5425 case DEVICE_IDLE_MODE_LIGHT:
5426 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005427 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005428 return mDeviceIdlingTimer.getCountLocked(which);
5429 }
5430 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005431 }
5432
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005433 @Override public int getNumConnectivityChange(int which) {
5434 int val = mNumConnectivityChange;
5435 if (which == STATS_CURRENT) {
5436 val -= mLoadedNumConnectivityChange;
5437 } else if (which == STATS_SINCE_UNPLUGGED) {
5438 val -= mUnpluggedNumConnectivityChange;
5439 }
5440 return val;
5441 }
5442
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005443 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
5444 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005446
Dianne Hackborn77b987f2014-02-26 16:20:52 -08005447 @Override public int getPhoneOnCount(int which) {
5448 return mPhoneOnTimer.getCountLocked(which);
5449 }
5450
Dianne Hackborn627bba72009-03-24 22:32:56 -07005451 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005452 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005453 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005454 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005455 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07005456
5457 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005458 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07005459 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005460 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005461 }
5462
Catherine Liufb900812012-07-17 14:12:56 -05005463 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
5464 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005465 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005466
Dianne Hackborn627bba72009-03-24 22:32:56 -07005467 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005468 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005469 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005470 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005471 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005472
Dianne Hackborn617f8772009-03-31 15:04:46 -07005473 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005474 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005475 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005476
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005477 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
5478 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005479 }
5480
Dianne Hackbornd45665b2014-02-26 12:35:32 -08005481 @Override public int getMobileRadioActiveCount(int which) {
5482 return mMobileRadioActiveTimer.getCountLocked(which);
5483 }
5484
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005485 @Override public long getMobileRadioActiveAdjustedTime(int which) {
5486 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
5487 }
5488
Dianne Hackbornd45665b2014-02-26 12:35:32 -08005489 @Override public long getMobileRadioActiveUnknownTime(int which) {
5490 return mMobileRadioActiveUnknownTime.getCountLocked(which);
5491 }
5492
5493 @Override public int getMobileRadioActiveUnknownCount(int which) {
5494 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
5495 }
5496
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005497 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
5498 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07005499 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005500
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005501 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
5502 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005503 }
5504
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005505 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005506 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005507 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005508 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005509 }
5510
5511 @Override public int getWifiStateCount(int wifiState, int which) {
5512 return mWifiStateTimer[wifiState].getCountLocked(which);
5513 }
5514
Dianne Hackborn3251b902014-06-20 14:40:53 -07005515 @Override public long getWifiSupplStateTime(int state,
5516 long elapsedRealtimeUs, int which) {
5517 return mWifiSupplStateTimer[state].getTotalTimeLocked(
5518 elapsedRealtimeUs, which);
5519 }
5520
5521 @Override public int getWifiSupplStateCount(int state, int which) {
5522 return mWifiSupplStateTimer[state].getCountLocked(which);
5523 }
5524
5525 @Override public long getWifiSignalStrengthTime(int strengthBin,
5526 long elapsedRealtimeUs, int which) {
5527 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
5528 elapsedRealtimeUs, which);
5529 }
5530
5531 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
5532 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
5533 }
5534
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005535 @Override
5536 public ControllerActivityCounter getBluetoothControllerActivity() {
5537 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07005538 }
5539
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005540 @Override
5541 public ControllerActivityCounter getWifiControllerActivity() {
5542 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07005543 }
5544
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005545 @Override
5546 public ControllerActivityCounter getModemControllerActivity() {
5547 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07005548 }
5549
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005550 @Override
5551 public boolean hasBluetoothActivityReporting() {
5552 return mHasBluetoothReporting;
5553 }
5554
5555 @Override
5556 public boolean hasWifiActivityReporting() {
5557 return mHasWifiReporting;
5558 }
5559
5560 @Override
5561 public boolean hasModemActivityReporting() {
5562 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07005563 }
5564
Ruben Brunk5b1308f2015-06-03 18:49:27 -07005565 @Override
5566 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005567 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5568 }
5569
Ruben Brunk5b1308f2015-06-03 18:49:27 -07005570 @Override
5571 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005572 return mFlashlightOnTimer.getCountLocked(which);
5573 }
5574
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005575 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07005576 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
5577 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5578 }
5579
5580 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005581 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
5582 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5583 }
5584
5585 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08005586 public long getNetworkActivityBytes(int type, int which) {
5587 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
5588 return mNetworkByteActivityCounters[type].getCountLocked(which);
5589 } else {
5590 return 0;
5591 }
5592 }
5593
5594 @Override
5595 public long getNetworkActivityPackets(int type, int which) {
5596 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
5597 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005598 } else {
5599 return 0;
5600 }
5601 }
5602
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08005603 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07005604 final long currentTime = System.currentTimeMillis();
5605 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08005606 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
5607 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07005608 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08005609 return mStartClockTime;
5610 }
5611
Dianne Hackborncd0e3352014-08-07 17:08:09 -07005612 @Override public String getStartPlatformVersion() {
5613 return mStartPlatformVersion;
5614 }
5615
5616 @Override public String getEndPlatformVersion() {
5617 return mEndPlatformVersion;
5618 }
5619
5620 @Override public int getParcelVersion() {
5621 return VERSION;
5622 }
5623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 @Override public boolean getIsOnBattery() {
5625 return mOnBattery;
5626 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005628 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
5629 return mUidStats;
5630 }
5631
Adam Lesinski5f056f62016-07-14 16:56:08 -07005632 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
5633 if (timer != null) {
5634 timer.detach();
5635 }
5636 }
5637
5638 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
5639 boolean detachIfReset) {
5640 if (timer != null) {
5641 return timer.reset(detachIfReset);
5642 }
5643 return true;
5644 }
5645
Bookatz867c0d72017-03-07 18:23:42 -08005646 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
5647 if (timer != null) {
5648 return timer.reset(detachIfReset);
5649 }
5650 return true;
5651 }
5652
Adam Lesinski5f056f62016-07-14 16:56:08 -07005653 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
5654 if (counter != null) {
5655 counter.detach();
5656 }
5657 }
5658
5659 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
5660 boolean detachIfReset) {
5661 if (counter != null) {
5662 counter.reset(detachIfReset);
5663 }
5664 }
5665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 /**
5667 * The statistics associated with a particular uid.
5668 */
Joe Onoratoabded112016-02-08 16:49:39 -08005669 public static class Uid extends BatteryStats.Uid {
5670 /**
5671 * BatteryStatsImpl that we are associated with.
5672 */
5673 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005676
Bookatz867c0d72017-03-07 18:23:42 -08005677 /** TimeBase for when uid is in background and device is on battery. */
5678 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
5679 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07005680 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
5681 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08005682
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005683 boolean mWifiRunning;
5684 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005685
The Android Open Source Project10592532009-03-18 17:39:46 -07005686 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07005687 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005688
Nick Pelly6ccaa542012-06-15 15:22:47 -07005689 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08005690 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005691
Dianne Hackborn61659e52014-07-09 16:13:01 -07005692 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07005693 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
5694 StopwatchTimer[] mWifiBatchedScanTimer;
5695
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005696 boolean mWifiMulticastEnabled;
5697 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005698
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005699 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005700 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005701 StopwatchTimer mFlashlightTurnedOnTimer;
5702 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005703 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07005704 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07005705 /** Total time spent by the uid holding any partial wakelocks. */
5706 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08005707 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07005708 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07005709 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07005710 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005711
Dianne Hackborna8d10942015-11-19 17:55:19 -08005712 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07005713 StopwatchTimer[] mProcessStateTimer;
5714
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07005715 boolean mInForegroundService = false;
5716
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005717 BatchTimer mVibratorOnTimer;
5718
Dianne Hackborn617f8772009-03-31 15:04:46 -07005719 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005720
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08005721 LongSamplingCounter[] mNetworkByteActivityCounters;
5722 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08005723 LongSamplingCounter mMobileRadioActiveTime;
5724 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07005727 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
5728 */
5729 private LongSamplingCounter mMobileRadioApWakeupCount;
5730
5731 /**
5732 * How many times this UID woke up the Application Processor due to a Wifi packet.
5733 */
5734 private LongSamplingCounter mWifiRadioApWakeupCount;
5735
5736 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07005737 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005738 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07005739 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005740 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07005741
5742 /**
5743 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005744 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07005745 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005746 private ControllerActivityCounterImpl mBluetoothControllerActivity;
5747
5748 /**
5749 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
5750 * Can be null if the UID has had no such activity.
5751 */
5752 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07005753
5754 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08005755 * The CPU times we had at the last history details update.
5756 */
5757 long mLastStepUserTime;
5758 long mLastStepSystemTime;
5759 long mCurStepUserTime;
5760 long mCurStepSystemTime;
5761
Joe Onoratoabded112016-02-08 16:49:39 -08005762 LongSamplingCounter mUserCpuTime;
5763 LongSamplingCounter mSystemCpuTime;
Sudheer Shanka71f34b32017-07-21 00:14:24 -07005764 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07005765
Sudheer Shanka9b735c52017-05-09 18:26:18 -07005766 LongSamplingCounterArray mCpuFreqTimeMs;
5767 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
5768
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08005769 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 * The statistics we have collected for this uid's wake locks.
5771 */
Joe Onoratoabded112016-02-08 16:49:39 -08005772 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773
5774 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005775 * The statistics we have collected for this uid's syncs.
5776 */
Bookatz2bffb5b2017-04-13 11:59:33 -07005777 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005778
5779 /**
5780 * The statistics we have collected for this uid's jobs.
5781 */
Bookatzaa4594a2017-03-24 12:39:56 -07005782 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005783
5784 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07005785 * Count of the jobs that have completed and the reasons why they completed.
5786 */
5787 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
5788
5789 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 * The statistics we have collected for this uid's sensor activations.
5791 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005792 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005793
5794 /**
5795 * The statistics we have collected for this uid's processes.
5796 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005797 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798
5799 /**
5800 * The statistics we have collected for this uid's processes.
5801 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005802 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005803
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005804 /**
5805 * The transient wake stats we have collected for this uid's pids.
5806 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005807 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005808
Joe Onoratoabded112016-02-08 16:49:39 -08005809 public Uid(BatteryStatsImpl bsi, int uid) {
5810 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08005812
Bookatz867c0d72017-03-07 18:23:42 -08005813 mOnBatteryBackgroundTimeBase = new TimeBase();
5814 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
5815 mBsi.mClocks.elapsedRealtime() * 1000);
5816
Bookatzc8c44962017-05-11 12:12:54 -07005817 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
5818 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
5819 mBsi.mClocks.elapsedRealtime() * 1000);
5820
Joe Onoratoabded112016-02-08 16:49:39 -08005821 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
5822 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08005823
Dianne Hackborn657153b2016-07-29 14:54:14 -07005824 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005825 @Override public Wakelock instantiateObject() {
5826 return new Wakelock(mBsi, Uid.this);
5827 }
5828 };
Bookatz2bffb5b2017-04-13 11:59:33 -07005829 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
5830 @Override public DualTimer instantiateObject() {
5831 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
5832 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08005833 }
5834 };
Bookatzaa4594a2017-03-24 12:39:56 -07005835 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
5836 @Override public DualTimer instantiateObject() {
5837 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
5838 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08005839 }
5840 };
5841
5842 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
5843 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
5844 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
5845 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08005846 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
5847 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005848 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08005849 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
5850 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07005851 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 }
5853
5854 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07005855 public long[] getCpuFreqTimes(int which) {
5856 if (mCpuFreqTimeMs == null) {
5857 return null;
5858 }
5859 final long[] cpuFreqTimes = mCpuFreqTimeMs.getCountsLocked(which);
5860 if (cpuFreqTimes == null) {
5861 return null;
5862 }
5863 // Return cpuFreqTimes only if atleast one of the elements in non-zero.
5864 for (int i = 0; i < cpuFreqTimes.length; ++i) {
5865 if (cpuFreqTimes[i] != 0) {
5866 return cpuFreqTimes;
5867 }
5868 }
5869 return null;
5870 }
5871
5872 @Override
5873 public long[] getScreenOffCpuFreqTimes(int which) {
5874 if (mScreenOffCpuFreqTimeMs == null) {
5875 return null;
5876 }
5877 final long[] cpuFreqTimes = mScreenOffCpuFreqTimeMs.getCountsLocked(which);
5878 if (cpuFreqTimes == null) {
5879 return null;
5880 }
5881 // Return cpuFreqTimes only if atleast one of the elements in non-zero.
5882 for (int i = 0; i < cpuFreqTimes.length; ++i) {
5883 if (cpuFreqTimes[i] != 0) {
5884 return cpuFreqTimes;
5885 }
5886 }
5887 return null;
5888 }
5889
5890 @Override
Bookatzc8c44962017-05-11 12:12:54 -07005891 public Timer getAggregatedPartialWakelockTimer() {
5892 return mAggregatedPartialWakelockTimer;
5893 }
5894
5895 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005896 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07005897 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005898 }
5899
5900 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005901 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07005902 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005903 }
5904
5905 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005906 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07005907 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005908 }
5909
5910 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07005911 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
5912 return mJobCompletions;
5913 }
5914
5915 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07005916 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 return mSensorStats;
5918 }
5919
5920 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005921 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005922 return mProcessStats;
5923 }
5924
5925 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005926 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927 return mPackageStats;
5928 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07005929
5930 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 public int getUid() {
5932 return mUid;
5933 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07005934
5935 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005936 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005937 if (!mWifiRunning) {
5938 mWifiRunning = true;
5939 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005940 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
5941 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005942 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005943 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005944 }
5945 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005946
Dianne Hackborn617f8772009-03-31 15:04:46 -07005947 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005948 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005949 if (mWifiRunning) {
5950 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005951 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005952 }
5953 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005954
Dianne Hackborn617f8772009-03-31 15:04:46 -07005955 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005956 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005957 if (!mFullWifiLockOut) {
5958 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005959 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005960 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
5961 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005962 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005963 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07005964 }
5965 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005966
The Android Open Source Project10592532009-03-18 17:39:46 -07005967 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005968 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005969 if (mFullWifiLockOut) {
5970 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005971 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07005972 }
5973 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005974
The Android Open Source Project10592532009-03-18 17:39:46 -07005975 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005976 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005977 if (!mWifiScanStarted) {
5978 mWifiScanStarted = true;
5979 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08005980 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
5981 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
5982 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005983 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005984 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07005985 }
5986 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005987
The Android Open Source Project10592532009-03-18 17:39:46 -07005988 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005989 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005990 if (mWifiScanStarted) {
5991 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005992 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07005993 }
5994 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005995
5996 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005997 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07005998 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07005999 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006000 csph = csph >> 3;
6001 bin++;
6002 }
6003
6004 if (mWifiBatchedScanBinStarted == bin) return;
6005
6006 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
6007 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006008 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006009 }
6010 mWifiBatchedScanBinStarted = bin;
6011 if (mWifiBatchedScanTimer[bin] == null) {
6012 makeWifiBatchedScanBin(bin, null);
6013 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006014 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006015 }
6016
6017 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006018 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006019 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
6020 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006021 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006022 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
6023 }
6024 }
6025
6026 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006027 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006028 if (!mWifiMulticastEnabled) {
6029 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006030 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006031 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6032 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006033 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006034 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006035 }
6036 }
6037
6038 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006039 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006040 if (mWifiMulticastEnabled) {
6041 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006042 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006043 }
6044 }
6045
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006046 @Override
6047 public ControllerActivityCounter getWifiControllerActivity() {
6048 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006049 }
6050
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006051 @Override
6052 public ControllerActivityCounter getBluetoothControllerActivity() {
6053 return mBluetoothControllerActivity;
6054 }
6055
6056 @Override
6057 public ControllerActivityCounter getModemControllerActivity() {
6058 return mModemControllerActivity;
6059 }
6060
6061 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
6062 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006063 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006064 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08006065 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006066 return mWifiControllerActivity;
6067 }
6068
6069 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
6070 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006071 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006072 NUM_BT_TX_LEVELS);
6073 }
6074 return mBluetoothControllerActivity;
6075 }
6076
6077 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
6078 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006079 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006080 ModemActivityInfo.TX_POWER_LEVELS);
6081 }
6082 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08006083 }
6084
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006085 public StopwatchTimer createAudioTurnedOnTimerLocked() {
6086 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006087 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
6088 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006089 }
6090 return mAudioTurnedOnTimer;
6091 }
6092
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006093 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006094 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
6095 }
6096
6097 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
6098 if (mAudioTurnedOnTimer != null) {
6099 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006100 }
6101 }
6102
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006103 public void noteResetAudioLocked(long elapsedRealtimeMs) {
6104 if (mAudioTurnedOnTimer != null) {
6105 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006106 }
6107 }
6108
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006109 public StopwatchTimer createVideoTurnedOnTimerLocked() {
6110 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006111 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
6112 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006113 }
6114 return mVideoTurnedOnTimer;
6115 }
6116
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006117 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006118 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
6119 }
6120
6121 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
6122 if (mVideoTurnedOnTimer != null) {
6123 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006124 }
6125 }
6126
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006127 public void noteResetVideoLocked(long elapsedRealtimeMs) {
6128 if (mVideoTurnedOnTimer != null) {
6129 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006130 }
6131 }
6132
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006133 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
6134 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006135 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6136 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006137 }
6138 return mFlashlightTurnedOnTimer;
6139 }
6140
6141 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
6142 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
6143 }
6144
6145 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
6146 if (mFlashlightTurnedOnTimer != null) {
6147 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
6148 }
6149 }
6150
6151 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
6152 if (mFlashlightTurnedOnTimer != null) {
6153 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
6154 }
6155 }
6156
6157 public StopwatchTimer createCameraTurnedOnTimerLocked() {
6158 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006159 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
6160 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006161 }
6162 return mCameraTurnedOnTimer;
6163 }
6164
6165 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
6166 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
6167 }
6168
6169 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
6170 if (mCameraTurnedOnTimer != null) {
6171 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
6172 }
6173 }
6174
6175 public void noteResetCameraLocked(long elapsedRealtimeMs) {
6176 if (mCameraTurnedOnTimer != null) {
6177 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
6178 }
6179 }
6180
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006181 public StopwatchTimer createForegroundActivityTimerLocked() {
6182 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006183 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6184 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006185 }
6186 return mForegroundActivityTimer;
6187 }
6188
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006189 public StopwatchTimer createForegroundServiceTimerLocked() {
6190 if (mForegroundServiceTimer == null) {
6191 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6192 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
6193 }
6194 return mForegroundServiceTimer;
6195 }
6196
Bookatzc8c44962017-05-11 12:12:54 -07006197 public DualTimer createAggregatedPartialWakelockTimerLocked() {
6198 if (mAggregatedPartialWakelockTimer == null) {
6199 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
6200 AGGREGATED_WAKE_TYPE_PARTIAL, null,
6201 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
6202 }
6203 return mAggregatedPartialWakelockTimer;
6204 }
6205
Bookatz867c0d72017-03-07 18:23:42 -08006206 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006207 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006208 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
6209 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
6210 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006211 }
6212 return mBluetoothScanTimer;
6213 }
6214
Bookatzb1f04f32017-05-19 13:57:32 -07006215 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
6216 if (mBluetoothUnoptimizedScanTimer == null) {
6217 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
6218 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
6219 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
6220 }
6221 return mBluetoothUnoptimizedScanTimer;
6222 }
6223
6224 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006225 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07006226 if (isUnoptimized) {
6227 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
6228 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006229 }
6230
Bookatz94c5a312017-07-11 16:49:17 -07006231 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006232 if (mBluetoothScanTimer != null) {
6233 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
6234 }
Bookatz94c5a312017-07-11 16:49:17 -07006235 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07006236 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
6237 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006238 }
6239
6240 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
6241 if (mBluetoothScanTimer != null) {
6242 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
6243 }
Bookatzb1f04f32017-05-19 13:57:32 -07006244 if (mBluetoothUnoptimizedScanTimer != null) {
6245 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
6246 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006247 }
6248
Bookatz956f36bf2017-04-28 09:48:17 -07006249 public Counter createBluetoothScanResultCounterLocked() {
6250 if (mBluetoothScanResultCounter == null) {
6251 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
6252 }
6253 return mBluetoothScanResultCounter;
6254 }
6255
Bookatzb1f04f32017-05-19 13:57:32 -07006256 public Counter createBluetoothScanResultBgCounterLocked() {
6257 if (mBluetoothScanResultBgCounter == null) {
6258 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
6259 }
6260 return mBluetoothScanResultBgCounter;
6261 }
6262
Bookatz4ebc0642017-05-11 12:21:19 -07006263 public void noteBluetoothScanResultsLocked(int numNewResults) {
6264 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07006265 // Uses background timebase, so the count will only be incremented if uid in background.
6266 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07006267 }
6268
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006269 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006270 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006271 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006272 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006273 }
6274
6275 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006276 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006277 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006278 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006279 }
6280 }
6281
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006282 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
6283 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
6284 }
6285
6286 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
6287 if (mForegroundServiceTimer != null) {
6288 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
6289 }
6290 }
6291
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006292 public BatchTimer createVibratorOnTimerLocked() {
6293 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006294 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
6295 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006296 }
6297 return mVibratorOnTimer;
6298 }
6299
6300 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08006301 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006302 }
6303
6304 public void noteVibratorOffLocked() {
6305 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006306 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006307 }
6308 }
6309
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006310 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006311 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006312 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006313 return 0;
6314 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006315 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006316 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006317
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006318 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006319 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006320 if (mFullWifiLockTimer == null) {
6321 return 0;
6322 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006323 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006324 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006325
6326 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006327 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006328 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006329 return 0;
6330 }
Bookatzaa4594a2017-03-24 12:39:56 -07006331 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006332 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006333
6334 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07006335 public int getWifiScanCount(int which) {
6336 if (mWifiScanTimer == null) {
6337 return 0;
6338 }
Bookatzaa4594a2017-03-24 12:39:56 -07006339 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08006340 }
6341
6342 @Override
6343 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07006344 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006345 return 0;
6346 }
6347 return mWifiScanTimer.getSubTimer().getCountLocked(which);
6348 }
6349
6350 @Override
6351 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
6352 if (mWifiScanTimer == null) {
6353 return 0;
6354 }
6355 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07006356 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08006357 }
6358
6359 @Override
6360 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07006361 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006362 return 0;
6363 }
6364 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
6365 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07006366 }
6367
6368 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006369 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006370 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
6371 if (mWifiBatchedScanTimer[csphBin] == null) {
6372 return 0;
6373 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006374 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006375 }
6376
6377 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07006378 public int getWifiBatchedScanCount(int csphBin, int which) {
6379 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
6380 if (mWifiBatchedScanTimer[csphBin] == null) {
6381 return 0;
6382 }
6383 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
6384 }
6385
6386 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006387 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006388 if (mWifiMulticastTimer == null) {
6389 return 0;
6390 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006391 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006392 }
6393
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006394 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006395 public Timer getAudioTurnedOnTimer() {
6396 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006397 }
6398
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006399 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006400 public Timer getVideoTurnedOnTimer() {
6401 return mVideoTurnedOnTimer;
6402 }
6403
6404 @Override
6405 public Timer getFlashlightTurnedOnTimer() {
6406 return mFlashlightTurnedOnTimer;
6407 }
6408
6409 @Override
6410 public Timer getCameraTurnedOnTimer() {
6411 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006412 }
6413
Dianne Hackborn617f8772009-03-31 15:04:46 -07006414 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006415 public Timer getForegroundActivityTimer() {
6416 return mForegroundActivityTimer;
6417 }
6418
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006419 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006420 public Timer getForegroundServiceTimer() {
6421 return mForegroundServiceTimer;
6422 }
6423
6424 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006425 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07006426 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006427 }
6428
6429 @Override
6430 public Timer getBluetoothScanBackgroundTimer() {
6431 if (mBluetoothScanTimer == null) {
6432 return null;
6433 }
6434 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006435 }
6436
Bookatz956f36bf2017-04-28 09:48:17 -07006437 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07006438 public Timer getBluetoothUnoptimizedScanTimer() {
6439 return mBluetoothUnoptimizedScanTimer;
6440 }
6441
6442 @Override
6443 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
6444 if (mBluetoothUnoptimizedScanTimer == null) {
6445 return null;
6446 }
6447 return mBluetoothUnoptimizedScanTimer.getSubTimer();
6448 }
6449
6450 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07006451 public Counter getBluetoothScanResultCounter() {
6452 return mBluetoothScanResultCounter;
6453 }
6454
Bookatzb1f04f32017-05-19 13:57:32 -07006455 @Override
6456 public Counter getBluetoothScanResultBgCounter() {
6457 return mBluetoothScanResultBgCounter;
6458 }
6459
Dianne Hackborn61659e52014-07-09 16:13:01 -07006460 void makeProcessState(int i, Parcel in) {
6461 if (i < 0 || i >= NUM_PROCESS_STATE) return;
6462
6463 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006464 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
6465 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006466 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08006467 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
6468 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006469 }
6470 }
6471
6472 @Override
6473 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
6474 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
6475 if (mProcessStateTimer[state] == null) {
6476 return 0;
6477 }
6478 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
6479 }
6480
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006481 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08006482 public Timer getProcessStateTimer(int state) {
6483 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
6484 return mProcessStateTimer[state];
6485 }
6486
6487 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006488 public Timer getVibratorOnTimer() {
6489 return mVibratorOnTimer;
6490 }
6491
6492 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07006493 public void noteUserActivityLocked(int type) {
6494 if (mUserActivityCounters == null) {
6495 initUserActivityLocked();
6496 }
Jeff Browndf693de2012-07-27 12:03:38 -07006497 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
6498 mUserActivityCounters[type].stepAtomic();
6499 } else {
6500 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
6501 new Throwable());
6502 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07006503 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006504
Dianne Hackborn617f8772009-03-31 15:04:46 -07006505 @Override
6506 public boolean hasUserActivity() {
6507 return mUserActivityCounters != null;
6508 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006509
Dianne Hackborn617f8772009-03-31 15:04:46 -07006510 @Override
6511 public int getUserActivityCount(int type, int which) {
6512 if (mUserActivityCounters == null) {
6513 return 0;
6514 }
Evan Millarc64edde2009-04-18 12:26:32 -07006515 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006516 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006517
Robert Greenwalta029ea12013-09-25 16:38:12 -07006518 void makeWifiBatchedScanBin(int i, Parcel in) {
6519 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
6520
Joe Onoratoabded112016-02-08 16:49:39 -08006521 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006522 if (collected == null) {
6523 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08006524 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006525 }
6526 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006527 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
6528 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006529 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08006530 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
6531 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006532 }
6533 }
6534
6535
Dianne Hackborn617f8772009-03-31 15:04:46 -07006536 void initUserActivityLocked() {
6537 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
6538 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08006539 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006540 }
6541 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006542
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006543 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
6544 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006545 initNetworkActivityLocked();
6546 }
6547 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006548 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
6549 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006550 } else {
6551 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
6552 new Throwable());
6553 }
6554 }
6555
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006556 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
6557 if (mNetworkByteActivityCounters == null) {
6558 initNetworkActivityLocked();
6559 }
6560 mMobileRadioActiveTime.addCountLocked(batteryUptime);
6561 mMobileRadioActiveCount.addCountLocked(1);
6562 }
6563
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006564 @Override
6565 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006566 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006567 }
6568
6569 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006570 public long getNetworkActivityBytes(int type, int which) {
6571 if (mNetworkByteActivityCounters != null && type >= 0
6572 && type < mNetworkByteActivityCounters.length) {
6573 return mNetworkByteActivityCounters[type].getCountLocked(which);
6574 } else {
6575 return 0;
6576 }
6577 }
6578
6579 @Override
6580 public long getNetworkActivityPackets(int type, int which) {
6581 if (mNetworkPacketActivityCounters != null && type >= 0
6582 && type < mNetworkPacketActivityCounters.length) {
6583 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006584 } else {
6585 return 0;
6586 }
6587 }
6588
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006589 @Override
6590 public long getMobileRadioActiveTime(int which) {
6591 return mMobileRadioActiveTime != null
6592 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
6593 }
6594
6595 @Override
6596 public int getMobileRadioActiveCount(int which) {
6597 return mMobileRadioActiveCount != null
6598 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
6599 }
6600
Adam Lesinskie08af192015-03-25 16:42:59 -07006601 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006602 public long getUserCpuTimeUs(int which) {
6603 return mUserCpuTime.getCountLocked(which);
6604 }
6605
6606 @Override
6607 public long getSystemCpuTimeUs(int which) {
6608 return mSystemCpuTime.getCountLocked(which);
6609 }
6610
6611 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07006612 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shanka71f34b32017-07-21 00:14:24 -07006613 if (mCpuClusterSpeedTimesUs != null) {
6614 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
6615 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
6616 if (cpuSpeedTimesUs != null) {
6617 if (step >= 0 && step < cpuSpeedTimesUs.length) {
6618 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07006619 if (c != null) {
6620 return c.getCountLocked(which);
6621 }
6622 }
6623 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006624 }
6625 }
6626 return 0;
6627 }
6628
Adam Lesinski5f056f62016-07-14 16:56:08 -07006629 public void noteMobileRadioApWakeupLocked() {
6630 if (mMobileRadioApWakeupCount == null) {
6631 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6632 }
6633 mMobileRadioApWakeupCount.addCountLocked(1);
6634 }
6635
6636 @Override
6637 public long getMobileRadioApWakeupCount(int which) {
6638 if (mMobileRadioApWakeupCount != null) {
6639 return mMobileRadioApWakeupCount.getCountLocked(which);
6640 }
6641 return 0;
6642 }
6643
6644 public void noteWifiRadioApWakeupLocked() {
6645 if (mWifiRadioApWakeupCount == null) {
6646 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6647 }
6648 mWifiRadioApWakeupCount.addCountLocked(1);
6649 }
6650
6651 @Override
6652 public long getWifiRadioApWakeupCount(int which) {
6653 if (mWifiRadioApWakeupCount != null) {
6654 return mWifiRadioApWakeupCount.getCountLocked(which);
6655 }
6656 return 0;
6657 }
6658
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006659 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006660 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
6661 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006662 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08006663 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6664 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006665 }
Joe Onoratoabded112016-02-08 16:49:39 -08006666 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6667 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006669
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006670 /**
6671 * Clear all stats for this uid. Returns true if the uid is completely
6672 * inactive so can be dropped.
6673 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07006674 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07006675 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006676 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006677
Bookatz993a0be2017-07-21 09:03:23 -07006678 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
6679 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
6680
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006681 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006682 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006683 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006684 }
6685 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006686 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006687 active |= mFullWifiLockOut;
6688 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006689 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006690 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07006691 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006692 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006693 if (mWifiBatchedScanTimer != null) {
6694 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
6695 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006696 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006697 }
6698 }
6699 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
6700 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006701 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006702 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006703 active |= mWifiMulticastEnabled;
6704 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006705
6706 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
6707 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
6708 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
6709 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
6710 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006711 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07006712 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07006713 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07006714 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07006715 if (mBluetoothScanResultCounter != null) {
6716 mBluetoothScanResultCounter.reset(false);
6717 }
Bookatzb1f04f32017-05-19 13:57:32 -07006718 if (mBluetoothScanResultBgCounter != null) {
6719 mBluetoothScanResultBgCounter.reset(false);
6720 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006721
Dianne Hackborn61659e52014-07-09 16:13:01 -07006722 if (mProcessStateTimer != null) {
6723 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
6724 if (mProcessStateTimer[i] != null) {
6725 active |= !mProcessStateTimer[i].reset(false);
6726 }
6727 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08006728 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006729 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006730 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006731 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006732 mVibratorOnTimer.detach();
6733 mVibratorOnTimer = null;
6734 } else {
6735 active = true;
6736 }
6737 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006738
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006739 if (mUserActivityCounters != null) {
6740 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
6741 mUserActivityCounters[i].reset(false);
6742 }
6743 }
6744
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006745 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006746 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006747 mNetworkByteActivityCounters[i].reset(false);
6748 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006749 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006750 mMobileRadioActiveTime.reset(false);
6751 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006752 }
6753
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006754 if (mWifiControllerActivity != null) {
6755 mWifiControllerActivity.reset(false);
6756 }
Adam Lesinskie08af192015-03-25 16:42:59 -07006757
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07006758 if (mBluetoothControllerActivity != null) {
6759 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006760 }
6761
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07006762 if (mModemControllerActivity != null) {
6763 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07006764 }
6765
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006766 mUserCpuTime.reset(false);
6767 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07006768
Sudheer Shanka71f34b32017-07-21 00:14:24 -07006769 if (mCpuClusterSpeedTimesUs != null) {
6770 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07006771 if (speeds != null) {
6772 for (LongSamplingCounter speed : speeds) {
6773 if (speed != null) {
6774 speed.reset(false);
6775 }
6776 }
6777 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006778 }
6779 }
6780
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006781 if (mCpuFreqTimeMs != null) {
6782 mCpuFreqTimeMs.reset(false);
6783 }
6784 if (mScreenOffCpuFreqTimeMs != null) {
6785 mScreenOffCpuFreqTimeMs.reset(false);
6786 }
6787
Adam Lesinski5f056f62016-07-14 16:56:08 -07006788 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
6789 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
6790
Dianne Hackbornd953c532014-08-16 18:17:38 -07006791 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
6792 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
6793 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006794 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006795 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006796 } else {
6797 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006798 }
6799 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07006800 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07006801 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07006802 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07006803 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006804 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006805 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006806 timer.detach();
6807 } else {
6808 active = true;
6809 }
6810 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07006811 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07006812 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07006813 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07006814 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006815 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006816 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006817 timer.detach();
6818 } else {
6819 active = true;
6820 }
6821 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07006822 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006823 mJobCompletions.clear();
Dianne Hackborn61659e52014-07-09 16:13:01 -07006824 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
6825 Sensor s = mSensorStats.valueAt(ise);
6826 if (s.reset()) {
6827 mSensorStats.removeAt(ise);
6828 } else {
6829 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006830 }
6831 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07006832 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
6833 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08006834 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006835 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08006836 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006837 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006838 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006839 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006840 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006841 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006842 } else {
6843 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006844 }
6845 }
6846 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006847 if (mPackageStats.size() > 0) {
6848 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
6849 while (it.hasNext()) {
6850 Map.Entry<String, Pkg> pkgEntry = it.next();
6851 Pkg p = pkgEntry.getValue();
6852 p.detach();
6853 if (p.mServiceStats.size() > 0) {
6854 Iterator<Map.Entry<String, Pkg.Serv>> it2
6855 = p.mServiceStats.entrySet().iterator();
6856 while (it2.hasNext()) {
6857 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
6858 servEntry.getValue().detach();
6859 }
6860 }
6861 }
6862 mPackageStats.clear();
6863 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006864
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006865 mLastStepUserTime = mLastStepSystemTime = 0;
6866 mCurStepUserTime = mCurStepSystemTime = 0;
6867
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006868 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006869 if (mWifiRunningTimer != null) {
6870 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006871 }
6872 if (mFullWifiLockTimer != null) {
6873 mFullWifiLockTimer.detach();
6874 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006875 if (mWifiScanTimer != null) {
6876 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006877 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006878 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
6879 if (mWifiBatchedScanTimer[i] != null) {
6880 mWifiBatchedScanTimer[i].detach();
6881 }
6882 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006883 if (mWifiMulticastTimer != null) {
6884 mWifiMulticastTimer.detach();
6885 }
6886 if (mAudioTurnedOnTimer != null) {
6887 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006888 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006889 }
6890 if (mVideoTurnedOnTimer != null) {
6891 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006892 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006893 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006894 if (mFlashlightTurnedOnTimer != null) {
6895 mFlashlightTurnedOnTimer.detach();
6896 mFlashlightTurnedOnTimer = null;
6897 }
6898 if (mCameraTurnedOnTimer != null) {
6899 mCameraTurnedOnTimer.detach();
6900 mCameraTurnedOnTimer = null;
6901 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006902 if (mForegroundActivityTimer != null) {
6903 mForegroundActivityTimer.detach();
6904 mForegroundActivityTimer = null;
6905 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006906 if (mForegroundServiceTimer != null) {
6907 mForegroundServiceTimer.detach();
6908 mForegroundServiceTimer = null;
6909 }
Bookatzc8c44962017-05-11 12:12:54 -07006910 if (mAggregatedPartialWakelockTimer != null) {
6911 mAggregatedPartialWakelockTimer.detach();
6912 mAggregatedPartialWakelockTimer = null;
6913 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006914 if (mBluetoothScanTimer != null) {
6915 mBluetoothScanTimer.detach();
6916 mBluetoothScanTimer = null;
6917 }
Bookatzb1f04f32017-05-19 13:57:32 -07006918 if (mBluetoothUnoptimizedScanTimer != null) {
6919 mBluetoothUnoptimizedScanTimer.detach();
6920 mBluetoothUnoptimizedScanTimer = null;
6921 }
Bookatz956f36bf2017-04-28 09:48:17 -07006922 if (mBluetoothScanResultCounter != null) {
6923 mBluetoothScanResultCounter.detach();
6924 mBluetoothScanResultCounter = null;
6925 }
Bookatzb1f04f32017-05-19 13:57:32 -07006926 if (mBluetoothScanResultBgCounter != null) {
6927 mBluetoothScanResultBgCounter.detach();
6928 mBluetoothScanResultBgCounter = null;
6929 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006930 if (mUserActivityCounters != null) {
6931 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
6932 mUserActivityCounters[i].detach();
6933 }
6934 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006935 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006936 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006937 mNetworkByteActivityCounters[i].detach();
6938 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006939 }
6940 }
Adam Lesinskie08af192015-03-25 16:42:59 -07006941
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006942 if (mWifiControllerActivity != null) {
6943 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07006944 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006945
6946 if (mBluetoothControllerActivity != null) {
6947 mBluetoothControllerActivity.detach();
6948 }
6949
6950 if (mModemControllerActivity != null) {
6951 mModemControllerActivity.detach();
6952 }
6953
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006954 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006955
6956 mUserCpuTime.detach();
6957 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07006958
Sudheer Shanka71f34b32017-07-21 00:14:24 -07006959 if (mCpuClusterSpeedTimesUs != null) {
6960 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07006961 if (cpuSpeeds != null) {
6962 for (LongSamplingCounter c : cpuSpeeds) {
6963 if (c != null) {
6964 c.detach();
6965 }
6966 }
6967 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006968 }
6969 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006970
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006971 if (mCpuFreqTimeMs != null) {
6972 mCpuFreqTimeMs.detach();
6973 }
6974 if (mScreenOffCpuFreqTimeMs != null) {
6975 mScreenOffCpuFreqTimeMs.detach();
6976 }
6977
Adam Lesinski5f056f62016-07-14 16:56:08 -07006978 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
6979 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006980 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006981
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006982 return !active;
6983 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006984
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006985 void writeJobCompletionsToParcelLocked(Parcel out) {
6986 int NJC = mJobCompletions.size();
6987 out.writeInt(NJC);
6988 for (int ijc=0; ijc<NJC; ijc++) {
6989 out.writeString(mJobCompletions.keyAt(ijc));
6990 SparseIntArray types = mJobCompletions.valueAt(ijc);
6991 int NT = types.size();
6992 out.writeInt(NT);
6993 for (int it=0; it<NT; it++) {
6994 out.writeInt(types.keyAt(it));
6995 out.writeInt(types.valueAt(it));
6996 }
6997 }
6998 }
6999
Bookatz867c0d72017-03-07 18:23:42 -08007000 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
7001 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07007002 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08007003
Dianne Hackbornd953c532014-08-16 18:17:38 -07007004 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
7005 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07007006 out.writeInt(NW);
7007 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007008 out.writeString(wakeStats.keyAt(iw));
7009 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007010 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 }
7012
Bookatz2bffb5b2017-04-13 11:59:33 -07007013 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007014 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007015 out.writeInt(NS);
7016 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007017 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07007018 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007019 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
7020 }
7021
Bookatzaa4594a2017-03-24 12:39:56 -07007022 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07007023 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007024 out.writeInt(NJ);
7025 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007026 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07007027 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007028 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
7029 }
7030
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007031 writeJobCompletionsToParcelLocked(out);
7032
Dianne Hackborn61659e52014-07-09 16:13:01 -07007033 int NSE = mSensorStats.size();
7034 out.writeInt(NSE);
7035 for (int ise=0; ise<NSE; ise++) {
7036 out.writeInt(mSensorStats.keyAt(ise));
7037 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007038 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007039 }
7040
Dianne Hackborn61659e52014-07-09 16:13:01 -07007041 int NP = mProcessStats.size();
7042 out.writeInt(NP);
7043 for (int ip=0; ip<NP; ip++) {
7044 out.writeString(mProcessStats.keyAt(ip));
7045 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007046 proc.writeToParcelLocked(out);
7047 }
7048
7049 out.writeInt(mPackageStats.size());
7050 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
7051 out.writeString(pkgEntry.getKey());
7052 Uid.Pkg pkg = pkgEntry.getValue();
7053 pkg.writeToParcelLocked(out);
7054 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007055
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007056 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007057 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007058 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007059 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007060 out.writeInt(0);
7061 }
7062 if (mFullWifiLockTimer != null) {
7063 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007064 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007065 } else {
7066 out.writeInt(0);
7067 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007068 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007069 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007070 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007071 } else {
7072 out.writeInt(0);
7073 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007074 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7075 if (mWifiBatchedScanTimer[i] != null) {
7076 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007077 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007078 } else {
7079 out.writeInt(0);
7080 }
7081 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007082 if (mWifiMulticastTimer != null) {
7083 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007084 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007085 } else {
7086 out.writeInt(0);
7087 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007088
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007089 if (mAudioTurnedOnTimer != null) {
7090 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007091 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007092 } else {
7093 out.writeInt(0);
7094 }
7095 if (mVideoTurnedOnTimer != null) {
7096 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007097 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007098 } else {
7099 out.writeInt(0);
7100 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007101 if (mFlashlightTurnedOnTimer != null) {
7102 out.writeInt(1);
7103 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
7104 } else {
7105 out.writeInt(0);
7106 }
7107 if (mCameraTurnedOnTimer != null) {
7108 out.writeInt(1);
7109 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
7110 } else {
7111 out.writeInt(0);
7112 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007113 if (mForegroundActivityTimer != null) {
7114 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007115 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007116 } else {
7117 out.writeInt(0);
7118 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007119 if (mForegroundServiceTimer != null) {
7120 out.writeInt(1);
7121 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
7122 } else {
7123 out.writeInt(0);
7124 }
Bookatzc8c44962017-05-11 12:12:54 -07007125 if (mAggregatedPartialWakelockTimer != null) {
7126 out.writeInt(1);
7127 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
7128 } else {
7129 out.writeInt(0);
7130 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007131 if (mBluetoothScanTimer != null) {
7132 out.writeInt(1);
7133 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
7134 } else {
7135 out.writeInt(0);
7136 }
Bookatzb1f04f32017-05-19 13:57:32 -07007137 if (mBluetoothUnoptimizedScanTimer != null) {
7138 out.writeInt(1);
7139 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
7140 } else {
7141 out.writeInt(0);
7142 }
Bookatz956f36bf2017-04-28 09:48:17 -07007143 if (mBluetoothScanResultCounter != null) {
7144 out.writeInt(1);
7145 mBluetoothScanResultCounter.writeToParcel(out);
7146 } else {
7147 out.writeInt(0);
7148 }
Bookatzb1f04f32017-05-19 13:57:32 -07007149 if (mBluetoothScanResultBgCounter != null) {
7150 out.writeInt(1);
7151 mBluetoothScanResultBgCounter.writeToParcel(out);
7152 } else {
7153 out.writeInt(0);
7154 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07007155 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7156 if (mProcessStateTimer[i] != null) {
7157 out.writeInt(1);
7158 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
7159 } else {
7160 out.writeInt(0);
7161 }
7162 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007163 if (mVibratorOnTimer != null) {
7164 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007165 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007166 } else {
7167 out.writeInt(0);
7168 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007169 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07007170 out.writeInt(1);
7171 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7172 mUserActivityCounters[i].writeToParcel(out);
7173 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007174 } else {
7175 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007176 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007177 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007178 out.writeInt(1);
7179 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007180 mNetworkByteActivityCounters[i].writeToParcel(out);
7181 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007182 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007183 mMobileRadioActiveTime.writeToParcel(out);
7184 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007185 } else {
7186 out.writeInt(0);
7187 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007188
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007189 if (mWifiControllerActivity != null) {
7190 out.writeInt(1);
7191 mWifiControllerActivity.writeToParcel(out, 0);
7192 } else {
7193 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07007194 }
7195
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007196 if (mBluetoothControllerActivity != null) {
7197 out.writeInt(1);
7198 mBluetoothControllerActivity.writeToParcel(out, 0);
7199 } else {
7200 out.writeInt(0);
7201 }
7202
7203 if (mModemControllerActivity != null) {
7204 out.writeInt(1);
7205 mModemControllerActivity.writeToParcel(out, 0);
7206 } else {
7207 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07007208 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007209
7210 mUserCpuTime.writeToParcel(out);
7211 mSystemCpuTime.writeToParcel(out);
7212
Sudheer Shanka71f34b32017-07-21 00:14:24 -07007213 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007214 out.writeInt(1);
Sudheer Shanka71f34b32017-07-21 00:14:24 -07007215 out.writeInt(mCpuClusterSpeedTimesUs.length);
7216 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007217 if (cpuSpeeds != null) {
7218 out.writeInt(1);
7219 out.writeInt(cpuSpeeds.length);
7220 for (LongSamplingCounter c : cpuSpeeds) {
7221 if (c != null) {
7222 out.writeInt(1);
7223 c.writeToParcel(out);
7224 } else {
7225 out.writeInt(0);
7226 }
7227 }
7228 } else {
7229 out.writeInt(0);
7230 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007231 }
Adam Lesinski6832f392015-09-05 18:05:40 -07007232 } else {
7233 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007234 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007235
Sudheer Shanka59f5c002017-05-15 10:57:15 -07007236 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
7237 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007238
Adam Lesinski5f056f62016-07-14 16:56:08 -07007239 if (mMobileRadioApWakeupCount != null) {
7240 out.writeInt(1);
7241 mMobileRadioApWakeupCount.writeToParcel(out);
7242 } else {
7243 out.writeInt(0);
7244 }
7245
7246 if (mWifiRadioApWakeupCount != null) {
7247 out.writeInt(1);
7248 mWifiRadioApWakeupCount.writeToParcel(out);
7249 } else {
7250 out.writeInt(0);
7251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007252 }
7253
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007254 void readJobCompletionsFromParcelLocked(Parcel in) {
7255 int numJobCompletions = in.readInt();
7256 mJobCompletions.clear();
7257 for (int j = 0; j < numJobCompletions; j++) {
7258 String jobName = in.readString();
7259 int numTypes = in.readInt();
7260 if (numTypes > 0) {
7261 SparseIntArray types = new SparseIntArray();
7262 for (int k = 0; k < numTypes; k++) {
7263 int type = in.readInt();
7264 int count = in.readInt();
7265 types.put(type, count);
7266 }
7267 mJobCompletions.put(jobName, types);
7268 }
7269 }
7270 }
7271
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007272 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08007273 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07007274 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08007275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007276 int numWakelocks = in.readInt();
7277 mWakelockStats.clear();
7278 for (int j = 0; j < numWakelocks; j++) {
7279 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08007280 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07007281 wakelock.readFromParcelLocked(
7282 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07007283 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 }
7285
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007286 int numSyncs = in.readInt();
7287 mSyncStats.clear();
7288 for (int j = 0; j < numSyncs; j++) {
7289 String syncName = in.readString();
7290 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07007291 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
7292 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007293 }
7294 }
7295
7296 int numJobs = in.readInt();
7297 mJobStats.clear();
7298 for (int j = 0; j < numJobs; j++) {
7299 String jobName = in.readString();
7300 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07007301 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
7302 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007303 }
7304 }
7305
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007306 readJobCompletionsFromParcelLocked(in);
7307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007308 int numSensors = in.readInt();
7309 mSensorStats.clear();
7310 for (int k = 0; k < numSensors; k++) {
7311 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08007312 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08007313 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
7314 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007315 mSensorStats.put(sensorNumber, sensor);
7316 }
7317
7318 int numProcs = in.readInt();
7319 mProcessStats.clear();
7320 for (int k = 0; k < numProcs; k++) {
7321 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08007322 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007323 proc.readFromParcelLocked(in);
7324 mProcessStats.put(processName, proc);
7325 }
7326
7327 int numPkgs = in.readInt();
7328 mPackageStats.clear();
7329 for (int l = 0; l < numPkgs; l++) {
7330 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08007331 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007332 pkg.readFromParcelLocked(in);
7333 mPackageStats.put(packageName, pkg);
7334 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007335
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007336 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007337 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007338 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7339 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007340 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007341 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007342 }
7343 mFullWifiLockOut = false;
7344 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007345 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7346 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007347 } else {
7348 mFullWifiLockTimer = null;
7349 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007350 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007351 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08007352 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7353 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
7354 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007355 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007356 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007357 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007358 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7359 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7360 if (in.readInt() != 0) {
7361 makeWifiBatchedScanBin(i, in);
7362 } else {
7363 mWifiBatchedScanTimer[i] = null;
7364 }
7365 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007366 mWifiMulticastEnabled = false;
7367 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007368 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
7369 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007370 } else {
7371 mWifiMulticastTimer = null;
7372 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007373 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007374 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7375 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007376 } else {
7377 mAudioTurnedOnTimer = null;
7378 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007379 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007380 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7381 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007382 } else {
7383 mVideoTurnedOnTimer = null;
7384 }
7385 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007386 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7387 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007388 } else {
7389 mFlashlightTurnedOnTimer = null;
7390 }
7391 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007392 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7393 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007394 } else {
7395 mCameraTurnedOnTimer = null;
7396 }
7397 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007398 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7399 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007400 } else {
7401 mForegroundActivityTimer = null;
7402 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007403 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007404 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7405 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
7406 } else {
7407 mForegroundServiceTimer = null;
7408 }
7409 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07007410 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7411 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7412 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
7413 in);
7414 } else {
7415 mAggregatedPartialWakelockTimer = null;
7416 }
7417 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08007418 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7419 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7420 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007421 } else {
7422 mBluetoothScanTimer = null;
7423 }
Bookatz956f36bf2017-04-28 09:48:17 -07007424 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07007425 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7426 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7427 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
7428 } else {
7429 mBluetoothUnoptimizedScanTimer = null;
7430 }
7431 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07007432 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
7433 } else {
7434 mBluetoothScanResultCounter = null;
7435 }
Bookatzb1f04f32017-05-19 13:57:32 -07007436 if (in.readInt() != 0) {
7437 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
7438 } else {
7439 mBluetoothScanResultBgCounter = null;
7440 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007441 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07007442 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7443 if (in.readInt() != 0) {
7444 makeProcessState(i, in);
7445 } else {
7446 mProcessStateTimer[i] = null;
7447 }
7448 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007449 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007450 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7451 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007452 } else {
7453 mVibratorOnTimer = null;
7454 }
7455 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07007456 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7457 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007458 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007459 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007460 } else {
7461 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07007462 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007463 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007464 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7465 mNetworkPacketActivityCounters
7466 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007467 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007468 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08007469 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007470 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08007471 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007472 }
Joe Onoratoabded112016-02-08 16:49:39 -08007473 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
7474 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007475 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007476 mNetworkByteActivityCounters = null;
7477 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007478 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007479
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007480 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007481 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007482 NUM_WIFI_TX_LEVELS, in);
7483 } else {
7484 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07007485 }
7486
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007487 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007488 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007489 NUM_BT_TX_LEVELS, in);
7490 } else {
7491 mBluetoothControllerActivity = null;
7492 }
7493
7494 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007495 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007496 ModemActivityInfo.TX_POWER_LEVELS, in);
7497 } else {
7498 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07007499 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007500
Joe Onoratoabded112016-02-08 16:49:39 -08007501 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
7502 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007503
Adam Lesinski6832f392015-09-05 18:05:40 -07007504 if (in.readInt() != 0) {
7505 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08007506 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007507 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007508 }
Adam Lesinski6832f392015-09-05 18:05:40 -07007509
Sudheer Shanka71f34b32017-07-21 00:14:24 -07007510 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07007511 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
7512 if (in.readInt() != 0) {
7513 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08007514 if (mBsi.mPowerProfile != null &&
7515 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007516 throw new ParcelFormatException("Incompatible number of cpu speeds");
7517 }
7518
7519 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shanka71f34b32017-07-21 00:14:24 -07007520 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07007521 for (int speed = 0; speed < numSpeeds; speed++) {
7522 if (in.readInt() != 0) {
Sudheer Shanka71f34b32017-07-21 00:14:24 -07007523 cpuSpeeds[speed] = new LongSamplingCounter(
7524 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07007525 }
7526 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07007527 } else {
Sudheer Shanka71f34b32017-07-21 00:14:24 -07007528 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07007529 }
7530 }
7531 } else {
Sudheer Shanka71f34b32017-07-21 00:14:24 -07007532 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007533 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007534
Sudheer Shanka59f5c002017-05-15 10:57:15 -07007535 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
7536 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
7537 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007538
7539 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07007540 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
7541 } else {
7542 mMobileRadioApWakeupCount = null;
7543 }
7544
7545 if (in.readInt() != 0) {
7546 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
7547 } else {
7548 mWifiRadioApWakeupCount = null;
7549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007550 }
7551
7552 /**
7553 * The statistics associated with a particular wake lock.
7554 */
Joe Onoratoabded112016-02-08 16:49:39 -08007555 public static class Wakelock extends BatteryStats.Uid.Wakelock {
7556 /**
7557 * BatteryStatsImpl that we are associated with.
7558 */
7559 protected BatteryStatsImpl mBsi;
7560
7561 /**
7562 * BatteryStatsImpl that we are associated with.
7563 */
7564 protected Uid mUid;
7565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007566 /**
7567 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07007568 * 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 -08007569 */
Bookatz5b5ec322017-05-26 09:40:38 -07007570 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007571
7572 /**
7573 * How long (in ms) this uid has been keeping the device fully awake.
7574 */
Evan Millarc64edde2009-04-18 12:26:32 -07007575 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007576
7577 /**
7578 * How long (in ms) this uid has had a window keeping the device awake.
7579 */
Evan Millarc64edde2009-04-18 12:26:32 -07007580 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581
7582 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007583 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07007584 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007585 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07007586
Joe Onoratoabded112016-02-08 16:49:39 -08007587 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
7588 mBsi = bsi;
7589 mUid = uid;
7590 }
7591
Adam Lesinski9425fe22015-06-19 12:02:13 -07007592 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007593 * Reads a possibly null Timer from a Parcel. The timer is associated with the
7594 * proper timer pool from the given BatteryStatsImpl object.
7595 *
7596 * @param in the Parcel to be read from.
7597 * return a new Timer, or null.
7598 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07007599 private StopwatchTimer readStopwatchTimerFromParcel(int type,
7600 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601 if (in.readInt() == 0) {
7602 return null;
7603 }
7604
Joe Onoratoabded112016-02-08 16:49:39 -08007605 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007606 }
7607
Joe Onorato92fd23f2016-07-25 11:18:42 -07007608 /**
7609 * Reads a possibly null Timer from a Parcel. The timer is associated with the
7610 * proper timer pool from the given BatteryStatsImpl object.
7611 *
7612 * @param in the Parcel to be read from.
7613 * return a new Timer, or null.
7614 */
Bookatz5b5ec322017-05-26 09:40:38 -07007615 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
7616 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07007617 if (in.readInt() == 0) {
7618 return null;
7619 }
7620
Bookatz5b5ec322017-05-26 09:40:38 -07007621 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07007622 }
7623
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007624 boolean reset() {
7625 boolean wlactive = false;
7626 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007627 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007628 }
7629 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007630 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007631 }
7632 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007633 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007634 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007635 if (mTimerDraw != null) {
7636 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07007637 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007638 if (!wlactive) {
7639 if (mTimerFull != null) {
7640 mTimerFull.detach();
7641 mTimerFull = null;
7642 }
7643 if (mTimerPartial != null) {
7644 mTimerPartial.detach();
7645 mTimerPartial = null;
7646 }
7647 if (mTimerWindow != null) {
7648 mTimerWindow.detach();
7649 mTimerWindow = null;
7650 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007651 if (mTimerDraw != null) {
7652 mTimerDraw.detach();
7653 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07007654 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007655 }
7656 return !wlactive;
7657 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007658
Bookatz5b5ec322017-05-26 09:40:38 -07007659 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
7660 TimeBase screenOffBgTimeBase, Parcel in) {
7661 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
7662 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07007663 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
7664 mBsi.mFullTimers, timeBase, in);
7665 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
7666 mBsi.mWindowTimers, timeBase, in);
7667 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
7668 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 }
7670
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007671 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
7672 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
7673 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
7674 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007675 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007676 }
7677
7678 @Override
7679 public Timer getWakeTime(int type) {
7680 switch (type) {
7681 case WAKE_TYPE_FULL: return mTimerFull;
7682 case WAKE_TYPE_PARTIAL: return mTimerPartial;
7683 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007684 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007685 default: throw new IllegalArgumentException("type = " + type);
7686 }
7687 }
7688 }
7689
Joe Onoratoabded112016-02-08 16:49:39 -08007690 public static class Sensor extends BatteryStats.Uid.Sensor {
7691 /**
7692 * BatteryStatsImpl that we are associated with.
7693 */
7694 protected BatteryStatsImpl mBsi;
7695
7696 /**
Bookatz867c0d72017-03-07 18:23:42 -08007697 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08007698 */
7699 protected Uid mUid;
7700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007701 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08007702 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08007703
Joe Onoratoabded112016-02-08 16:49:39 -08007704 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
7705 mBsi = bsi;
7706 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 mHandle = handle;
7708 }
7709
Bookatz867c0d72017-03-07 18:23:42 -08007710 private DualTimer readTimersFromParcel(
7711 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 if (in.readInt() == 0) {
7713 return null;
7714 }
7715
Joe Onoratoabded112016-02-08 16:49:39 -08007716 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007717 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07007718 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007719 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007720 }
Bookatz867c0d72017-03-07 18:23:42 -08007721 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08007722 }
7723
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007724 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007725 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007726 mTimer = null;
7727 return true;
7728 }
7729 return false;
7730 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007731
Bookatz867c0d72017-03-07 18:23:42 -08007732 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
7733 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007734 }
7735
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007736 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007737 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 }
7739
7740 @Override
7741 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07007742 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007744
7745 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007746 public Timer getSensorBackgroundTime() {
7747 if (mTimer == null) {
7748 return null;
7749 }
7750 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08007751 }
7752
7753 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007754 public int getHandle() {
7755 return mHandle;
7756 }
7757 }
7758
7759 /**
7760 * The statistics associated with a particular process.
7761 */
Joe Onoratoabded112016-02-08 16:49:39 -08007762 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
7763 /**
7764 * BatteryStatsImpl that we are associated with.
7765 */
7766 protected BatteryStatsImpl mBsi;
7767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007768 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07007769 * The name of this process.
7770 */
7771 final String mName;
7772
7773 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08007774 * Remains true until removed from the stats.
7775 */
7776 boolean mActive = true;
7777
7778 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07007779 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 */
7781 long mUserTime;
7782
7783 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07007784 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 */
7786 long mSystemTime;
7787
7788 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07007789 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007790 */
7791 long mForegroundTime;
7792
7793 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007794 * Number of times the process has been started.
7795 */
7796 int mStarts;
7797
7798 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007799 * Number of times the process has crashed.
7800 */
7801 int mNumCrashes;
7802
7803 /**
7804 * Number of times the process has had an ANR.
7805 */
7806 int mNumAnrs;
7807
7808 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 * The amount of user time loaded from a previous save.
7810 */
7811 long mLoadedUserTime;
7812
7813 /**
7814 * The amount of system time loaded from a previous save.
7815 */
7816 long mLoadedSystemTime;
7817
7818 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007819 * The amount of foreground time loaded from a previous save.
7820 */
7821 long mLoadedForegroundTime;
7822
7823 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007824 * The number of times the process has started from a previous save.
7825 */
7826 int mLoadedStarts;
7827
7828 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007829 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007830 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007831 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007832
7833 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007834 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007835 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007836 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007837
7838 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007839 * The amount of user time when last unplugged.
7840 */
7841 long mUnpluggedUserTime;
7842
7843 /**
7844 * The amount of system time when last unplugged.
7845 */
7846 long mUnpluggedSystemTime;
7847
7848 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007849 * The amount of foreground time since unplugged.
7850 */
7851 long mUnpluggedForegroundTime;
7852
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007853 /**
7854 * The number of times the process has started before unplugged.
7855 */
7856 int mUnpluggedStarts;
7857
Dianne Hackborn61659e52014-07-09 16:13:01 -07007858 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007859 * Number of times the process has crashed before unplugged.
7860 */
7861 int mUnpluggedNumCrashes;
7862
7863 /**
7864 * Number of times the process has had an ANR before unplugged.
7865 */
7866 int mUnpluggedNumAnrs;
7867
Dianne Hackborn287952c2010-09-22 22:34:31 -07007868 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007869
Joe Onoratoabded112016-02-08 16:49:39 -08007870 public Proc(BatteryStatsImpl bsi, String name) {
7871 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07007872 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08007873 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07007875
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007876 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007877 mUnpluggedUserTime = mUserTime;
7878 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007879 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007880 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007881 mUnpluggedNumCrashes = mNumCrashes;
7882 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 }
7884
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007885 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007886 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007887
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007888 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08007889 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08007890 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007891 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007892
Dianne Hackborn287952c2010-09-22 22:34:31 -07007893 public int countExcessivePowers() {
7894 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007895 }
7896
Dianne Hackborn287952c2010-09-22 22:34:31 -07007897 public ExcessivePower getExcessivePower(int i) {
7898 if (mExcessivePower != null) {
7899 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007900 }
7901 return null;
7902 }
7903
Dianne Hackborn287952c2010-09-22 22:34:31 -07007904 public void addExcessiveCpu(long overTime, long usedTime) {
7905 if (mExcessivePower == null) {
7906 mExcessivePower = new ArrayList<ExcessivePower>();
7907 }
7908 ExcessivePower ew = new ExcessivePower();
7909 ew.type = ExcessivePower.TYPE_CPU;
7910 ew.overTime = overTime;
7911 ew.usedTime = usedTime;
7912 mExcessivePower.add(ew);
7913 }
7914
7915 void writeExcessivePowerToParcelLocked(Parcel out) {
7916 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007917 out.writeInt(0);
7918 return;
7919 }
7920
Dianne Hackborn287952c2010-09-22 22:34:31 -07007921 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007922 out.writeInt(N);
7923 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07007924 ExcessivePower ew = mExcessivePower.get(i);
7925 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007926 out.writeLong(ew.overTime);
7927 out.writeLong(ew.usedTime);
7928 }
7929 }
7930
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07007931 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007932 final int N = in.readInt();
7933 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07007934 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07007935 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007936 }
7937
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08007938 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07007939 throw new ParcelFormatException(
7940 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08007941 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07007942
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07007943 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007944 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07007945 ExcessivePower ew = new ExcessivePower();
7946 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007947 ew.overTime = in.readLong();
7948 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07007949 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007950 }
7951 }
7952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 void writeToParcelLocked(Parcel out) {
7954 out.writeLong(mUserTime);
7955 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007956 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007958 out.writeInt(mNumCrashes);
7959 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 out.writeLong(mLoadedUserTime);
7961 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007962 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007963 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007964 out.writeInt(mLoadedNumCrashes);
7965 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 out.writeLong(mUnpluggedUserTime);
7967 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007968 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007969 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007970 out.writeInt(mUnpluggedNumCrashes);
7971 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07007972 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973 }
7974
7975 void readFromParcelLocked(Parcel in) {
7976 mUserTime = in.readLong();
7977 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007978 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007980 mNumCrashes = in.readInt();
7981 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 mLoadedUserTime = in.readLong();
7983 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007984 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007985 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007986 mLoadedNumCrashes = in.readInt();
7987 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007988 mUnpluggedUserTime = in.readLong();
7989 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007990 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007992 mUnpluggedNumCrashes = in.readInt();
7993 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07007994 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007995 }
7996
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007997 public void addCpuTimeLocked(int utime, int stime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 mUserTime += utime;
7999 mSystemTime += stime;
8000 }
8001
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008002 public void addForegroundTimeLocked(long ttime) {
8003 mForegroundTime += ttime;
8004 }
8005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008006 public void incStartsLocked() {
8007 mStarts++;
8008 }
8009
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008010 public void incNumCrashesLocked() {
8011 mNumCrashes++;
8012 }
8013
8014 public void incNumAnrsLocked() {
8015 mNumAnrs++;
8016 }
8017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008018 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08008019 public boolean isActive() {
8020 return mActive;
8021 }
8022
8023 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008025 long val = mUserTime;
8026 if (which == STATS_CURRENT) {
8027 val -= mLoadedUserTime;
8028 } else if (which == STATS_SINCE_UNPLUGGED) {
8029 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008030 }
8031 return val;
8032 }
8033
8034 @Override
8035 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008036 long val = mSystemTime;
8037 if (which == STATS_CURRENT) {
8038 val -= mLoadedSystemTime;
8039 } else if (which == STATS_SINCE_UNPLUGGED) {
8040 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008041 }
8042 return val;
8043 }
8044
8045 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008046 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008047 long val = mForegroundTime;
8048 if (which == STATS_CURRENT) {
8049 val -= mLoadedForegroundTime;
8050 } else if (which == STATS_SINCE_UNPLUGGED) {
8051 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008052 }
8053 return val;
8054 }
8055
8056 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008058 int val = mStarts;
8059 if (which == STATS_CURRENT) {
8060 val -= mLoadedStarts;
8061 } else if (which == STATS_SINCE_UNPLUGGED) {
8062 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008063 }
8064 return val;
8065 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07008066
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008067 @Override
8068 public int getNumCrashes(int which) {
8069 int val = mNumCrashes;
8070 if (which == STATS_CURRENT) {
8071 val -= mLoadedNumCrashes;
8072 } else if (which == STATS_SINCE_UNPLUGGED) {
8073 val -= mUnpluggedNumCrashes;
8074 }
8075 return val;
8076 }
8077
8078 @Override
8079 public int getNumAnrs(int which) {
8080 int val = mNumAnrs;
8081 if (which == STATS_CURRENT) {
8082 val -= mLoadedNumAnrs;
8083 } else if (which == STATS_SINCE_UNPLUGGED) {
8084 val -= mUnpluggedNumAnrs;
8085 }
8086 return val;
8087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008088 }
8089
8090 /**
8091 * The statistics associated with a particular package.
8092 */
Joe Onoratoabded112016-02-08 16:49:39 -08008093 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
8094 /**
8095 * BatteryStatsImpl that we are associated with.
8096 */
8097 protected BatteryStatsImpl mBsi;
8098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008100 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07008101 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008102 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008103 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008104
8105 /**
8106 * The statics we have collected for this package's services.
8107 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008108 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109
Joe Onoratoabded112016-02-08 16:49:39 -08008110 public Pkg(BatteryStatsImpl bsi) {
8111 mBsi = bsi;
8112 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008114
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008115 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008116 }
8117
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008118 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008119 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008120
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008121 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08008122 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008123 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008125 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008126 int numWA = in.readInt();
8127 mWakeupAlarms.clear();
8128 for (int i=0; i<numWA; i++) {
8129 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07008130 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008132
8133 int numServs = in.readInt();
8134 mServiceStats.clear();
8135 for (int m = 0; m < numServs; m++) {
8136 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008137 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 mServiceStats.put(serviceName, serv);
8139
8140 serv.readFromParcelLocked(in);
8141 }
8142 }
8143
8144 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008145 int numWA = mWakeupAlarms.size();
8146 out.writeInt(numWA);
8147 for (int i=0; i<numWA; i++) {
8148 out.writeString(mWakeupAlarms.keyAt(i));
8149 mWakeupAlarms.valueAt(i).writeToParcel(out);
8150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008152 final int NS = mServiceStats.size();
8153 out.writeInt(NS);
8154 for (int i=0; i<NS; i++) {
8155 out.writeString(mServiceStats.keyAt(i));
8156 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 serv.writeToParcelLocked(out);
8158 }
8159 }
8160
8161 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008162 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
8163 return mWakeupAlarms;
8164 }
8165
8166 public void noteWakeupAlarmLocked(String tag) {
8167 Counter c = mWakeupAlarms.get(tag);
8168 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07008169 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008170 mWakeupAlarms.put(tag, c);
8171 }
8172 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 }
8174
8175 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008176 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
8177 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008178 }
8179
8180 /**
8181 * The statistics associated with a particular service.
8182 */
Joe Onoratoabded112016-02-08 16:49:39 -08008183 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
8184 /**
8185 * BatteryStatsImpl that we are associated with.
8186 */
8187 protected BatteryStatsImpl mBsi;
8188
8189 /**
8190 * The android package in which this service resides.
8191 */
8192 protected Pkg mPkg;
8193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008194 /**
8195 * Total time (ms in battery uptime) the service has been left started.
8196 */
Joe Onoratoabded112016-02-08 16:49:39 -08008197 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008198
8199 /**
8200 * If service has been started and not yet stopped, this is
8201 * when it was started.
8202 */
Joe Onoratoabded112016-02-08 16:49:39 -08008203 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008204
8205 /**
8206 * True if we are currently running.
8207 */
Joe Onoratoabded112016-02-08 16:49:39 -08008208 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008209
8210 /**
8211 * Total number of times startService() has been called.
8212 */
Joe Onoratoabded112016-02-08 16:49:39 -08008213 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008214
8215 /**
8216 * Total time (ms in battery uptime) the service has been left launched.
8217 */
Joe Onoratoabded112016-02-08 16:49:39 -08008218 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008219
8220 /**
8221 * If service has been launched and not yet exited, this is
8222 * when it was launched (ms in battery uptime).
8223 */
Joe Onoratoabded112016-02-08 16:49:39 -08008224 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225
8226 /**
8227 * True if we are currently launched.
8228 */
Joe Onoratoabded112016-02-08 16:49:39 -08008229 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008230
8231 /**
8232 * Total number times the service has been launched.
8233 */
Joe Onoratoabded112016-02-08 16:49:39 -08008234 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008235
8236 /**
8237 * The amount of time spent started loaded from a previous save
8238 * (ms in battery uptime).
8239 */
Joe Onoratoabded112016-02-08 16:49:39 -08008240 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008241
8242 /**
8243 * The number of starts loaded from a previous save.
8244 */
Joe Onoratoabded112016-02-08 16:49:39 -08008245 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008246
8247 /**
8248 * The number of launches loaded from a previous save.
8249 */
Joe Onoratoabded112016-02-08 16:49:39 -08008250 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008251
8252 /**
8253 * The amount of time spent started as of the last run (ms
8254 * in battery uptime).
8255 */
Joe Onoratoabded112016-02-08 16:49:39 -08008256 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008257
8258 /**
8259 * The number of starts as of the last run.
8260 */
Joe Onoratoabded112016-02-08 16:49:39 -08008261 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008262
8263 /**
8264 * The number of launches as of the last run.
8265 */
Joe Onoratoabded112016-02-08 16:49:39 -08008266 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267
8268 /**
8269 * The amount of time spent started when last unplugged (ms
8270 * in battery uptime).
8271 */
Joe Onoratoabded112016-02-08 16:49:39 -08008272 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008273
8274 /**
8275 * The number of starts when last unplugged.
8276 */
Joe Onoratoabded112016-02-08 16:49:39 -08008277 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008278
8279 /**
8280 * The number of launches when last unplugged.
8281 */
Joe Onoratoabded112016-02-08 16:49:39 -08008282 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008283
Joe Onoratoabded112016-02-08 16:49:39 -08008284 /**
8285 * Construct a Serv. Also adds it to the on-battery time base as a listener.
8286 */
8287 public Serv(BatteryStatsImpl bsi) {
8288 mBsi = bsi;
8289 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008291
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008292 public void onTimeStarted(long elapsedRealtime, long baseUptime,
8293 long baseRealtime) {
8294 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008295 mUnpluggedStarts = mStarts;
8296 mUnpluggedLaunches = mLaunches;
8297 }
8298
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008299 public void onTimeStopped(long elapsedRealtime, long baseUptime,
8300 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008301 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008302
Joe Onoratoabded112016-02-08 16:49:39 -08008303 /**
8304 * Remove this Serv as a listener from the time base.
8305 */
8306 public void detach() {
8307 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008308 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008309
Joe Onoratoabded112016-02-08 16:49:39 -08008310 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008311 mStartTime = in.readLong();
8312 mRunningSince = in.readLong();
8313 mRunning = in.readInt() != 0;
8314 mStarts = in.readInt();
8315 mLaunchedTime = in.readLong();
8316 mLaunchedSince = in.readLong();
8317 mLaunched = in.readInt() != 0;
8318 mLaunches = in.readInt();
8319 mLoadedStartTime = in.readLong();
8320 mLoadedStarts = in.readInt();
8321 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07008322 mLastStartTime = 0;
8323 mLastStarts = 0;
8324 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008325 mUnpluggedStartTime = in.readLong();
8326 mUnpluggedStarts = in.readInt();
8327 mUnpluggedLaunches = in.readInt();
8328 }
8329
Joe Onoratoabded112016-02-08 16:49:39 -08008330 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008331 out.writeLong(mStartTime);
8332 out.writeLong(mRunningSince);
8333 out.writeInt(mRunning ? 1 : 0);
8334 out.writeInt(mStarts);
8335 out.writeLong(mLaunchedTime);
8336 out.writeLong(mLaunchedSince);
8337 out.writeInt(mLaunched ? 1 : 0);
8338 out.writeInt(mLaunches);
8339 out.writeLong(mLoadedStartTime);
8340 out.writeInt(mLoadedStarts);
8341 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008342 out.writeLong(mUnpluggedStartTime);
8343 out.writeInt(mUnpluggedStarts);
8344 out.writeInt(mUnpluggedLaunches);
8345 }
8346
Joe Onoratoabded112016-02-08 16:49:39 -08008347 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008348 if (!mLaunched) return mLaunchedTime;
8349 return mLaunchedTime + batteryUptime - mLaunchedSince;
8350 }
8351
Joe Onoratoabded112016-02-08 16:49:39 -08008352 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008353 if (!mRunning) return mStartTime;
8354 return mStartTime + batteryUptime - mRunningSince;
8355 }
8356
8357 public void startLaunchedLocked() {
8358 if (!mLaunched) {
8359 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08008360 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008361 mLaunched = true;
8362 }
8363 }
8364
8365 public void stopLaunchedLocked() {
8366 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08008367 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008368 if (time > 0) {
8369 mLaunchedTime += time;
8370 } else {
8371 mLaunches--;
8372 }
8373 mLaunched = false;
8374 }
8375 }
8376
8377 public void startRunningLocked() {
8378 if (!mRunning) {
8379 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08008380 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008381 mRunning = true;
8382 }
8383 }
8384
8385 public void stopRunningLocked() {
8386 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08008387 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008388 if (time > 0) {
8389 mStartTime += time;
8390 } else {
8391 mStarts--;
8392 }
8393 mRunning = false;
8394 }
8395 }
8396
8397 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08008398 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008399 }
8400
8401 @Override
8402 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008403 int val = mLaunches;
8404 if (which == STATS_CURRENT) {
8405 val -= mLoadedLaunches;
8406 } else if (which == STATS_SINCE_UNPLUGGED) {
8407 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 return val;
8410 }
8411
8412 @Override
8413 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008414 long val = getStartTimeToNowLocked(now);
8415 if (which == STATS_CURRENT) {
8416 val -= mLoadedStartTime;
8417 } else if (which == STATS_SINCE_UNPLUGGED) {
8418 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008420 return val;
8421 }
8422
8423 @Override
8424 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008425 int val = mStarts;
8426 if (which == STATS_CURRENT) {
8427 val -= mLoadedStarts;
8428 } else if (which == STATS_SINCE_UNPLUGGED) {
8429 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008430 }
8431
8432 return val;
8433 }
8434 }
8435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008436 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08008437 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008438 }
8439 }
8440
8441 /**
8442 * Retrieve the statistics object for a particular process, creating
8443 * if needed.
8444 */
8445 public Proc getProcessStatsLocked(String name) {
8446 Proc ps = mProcessStats.get(name);
8447 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08008448 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008449 mProcessStats.put(name, ps);
8450 }
8451
8452 return ps;
8453 }
8454
Dianne Hackborna8d10942015-11-19 17:55:19 -08008455 public void updateUidProcessStateLocked(int procState) {
8456 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008457 // Make special note of Foreground Services
8458 final boolean userAwareService =
8459 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008460 if (procState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
8461 uidRunningState = ActivityManager.PROCESS_STATE_NONEXISTENT;
8462 } else if (procState == ActivityManager.PROCESS_STATE_TOP) {
8463 uidRunningState = PROCESS_STATE_TOP;
8464 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
8465 // Persistent and other foreground states go here.
8466 uidRunningState = PROCESS_STATE_FOREGROUND_SERVICE;
8467 } else if (procState <= ActivityManager.PROCESS_STATE_TOP_SLEEPING) {
8468 uidRunningState = PROCESS_STATE_TOP_SLEEPING;
8469 } else if (procState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
8470 // Persistent and other foreground states go here.
8471 uidRunningState = PROCESS_STATE_FOREGROUND;
8472 } else if (procState <= ActivityManager.PROCESS_STATE_RECEIVER) {
8473 uidRunningState = PROCESS_STATE_BACKGROUND;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008474 } else {
Dianne Hackborna8d10942015-11-19 17:55:19 -08008475 uidRunningState = PROCESS_STATE_CACHED;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008476 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008477
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008478 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
8479 return;
8480 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008481
Bookatz867c0d72017-03-07 18:23:42 -08008482 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008483 if (mProcessState != uidRunningState) {
8484 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08008485
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008486 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
8487 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008488 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008489 mProcessState = uidRunningState;
8490 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
8491 if (mProcessStateTimer[uidRunningState] == null) {
8492 makeProcessState(uidRunningState, null);
8493 }
8494 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
8495 }
8496
8497 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
8498 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008499 }
Bookatz867c0d72017-03-07 18:23:42 -08008500
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008501 if (userAwareService != mInForegroundService) {
8502 if (userAwareService) {
8503 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
8504 } else {
8505 noteForegroundServicePausedLocked(elapsedRealtimeMs);
8506 }
8507 mInForegroundService = userAwareService;
8508 }
Bookatz867c0d72017-03-07 18:23:42 -08008509 }
8510
Bookatzc8c44962017-05-11 12:12:54 -07008511 /** Whether to consider Uid to be in the background for background timebase purposes. */
8512 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08008513 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
8514 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07008515 return mProcessState >= PROCESS_STATE_BACKGROUND;
8516 }
8517
8518 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
8519 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
8520 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
8521 }
8522
8523 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
8524 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
8525 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008526 }
8527
Dianne Hackbornb5e31652010-09-07 12:13:55 -07008528 public SparseArray<? extends Pid> getPidStats() {
8529 return mPids;
8530 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008531
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008532 public Pid getPidStatsLocked(int pid) {
8533 Pid p = mPids.get(pid);
8534 if (p == null) {
8535 p = new Pid();
8536 mPids.put(pid, p);
8537 }
8538 return p;
8539 }
8540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 /**
8542 * Retrieve the statistics object for a particular service, creating
8543 * if needed.
8544 */
8545 public Pkg getPackageStatsLocked(String name) {
8546 Pkg ps = mPackageStats.get(name);
8547 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08008548 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008549 mPackageStats.put(name, ps);
8550 }
8551
8552 return ps;
8553 }
8554
8555 /**
8556 * Retrieve the statistics object for a particular service, creating
8557 * if needed.
8558 */
8559 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
8560 Pkg ps = getPackageStatsLocked(pkg);
8561 Pkg.Serv ss = ps.mServiceStats.get(serv);
8562 if (ss == null) {
8563 ss = ps.newServiceStatsLocked();
8564 ps.mServiceStats.put(serv, ss);
8565 }
8566
8567 return ss;
8568 }
8569
Dianne Hackbornd953c532014-08-16 18:17:38 -07008570 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008571 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008572 timer.readSummaryFromParcelLocked(in);
8573 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008574 }
8575
Dianne Hackbornd953c532014-08-16 18:17:38 -07008576 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07008577 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008578 timer.readSummaryFromParcelLocked(in);
8579 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008580 }
8581
Dianne Hackbornd953c532014-08-16 18:17:38 -07008582 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08008583 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008584 mWakelockStats.add(wlName, wl);
8585 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07008586 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008588 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07008589 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008590 }
8591 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07008592 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07008594 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07008595 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008597 }
8598
Bookatz867c0d72017-03-07 18:23:42 -08008599 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008600 Sensor se = mSensorStats.get(sensor);
8601 if (se == null) {
8602 if (!create) {
8603 return null;
8604 }
Joe Onoratoabded112016-02-08 16:49:39 -08008605 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008606 mSensorStats.put(sensor, se);
8607 }
Bookatz867c0d72017-03-07 18:23:42 -08008608 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008609 if (t != null) {
8610 return t;
8611 }
Joe Onoratoabded112016-02-08 16:49:39 -08008612 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07008614 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08008615 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008616 }
Bookatz867c0d72017-03-07 18:23:42 -08008617 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
8618 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008619 se.mTimer = t;
8620 return t;
8621 }
8622
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008623 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008624 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008625 if (t != null) {
8626 t.startRunningLocked(elapsedRealtimeMs);
8627 }
8628 }
8629
8630 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008631 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008632 if (t != null) {
8633 t.stopRunningLocked(elapsedRealtimeMs);
8634 }
8635 }
8636
8637 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07008638 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008639 if (t != null) {
8640 t.startRunningLocked(elapsedRealtimeMs);
8641 }
8642 }
8643
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008644 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07008645 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008646 if (t != null) {
8647 t.stopRunningLocked(elapsedRealtimeMs);
8648 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008649 if (mBsi.mOnBatteryTimeBase.isRunning()) {
8650 SparseIntArray types = mJobCompletions.get(name);
8651 if (types == null) {
8652 types = new SparseIntArray();
8653 mJobCompletions.put(name, types);
8654 }
8655 int last = types.get(stopReason, 0);
8656 types.put(stopReason, last + 1);
8657 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008658 }
8659
Bookatz5b5ec322017-05-26 09:40:38 -07008660 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
8661 if (wl == null) {
8662 return null;
8663 }
8664 switch (type) {
8665 case WAKE_TYPE_PARTIAL: {
8666 DualTimer t = wl.mTimerPartial;
8667 if (t == null) {
8668 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
8669 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
8670 mOnBatteryScreenOffBackgroundTimeBase);
8671 wl.mTimerPartial = t;
8672 }
8673 return t;
8674 }
8675 case WAKE_TYPE_FULL: {
8676 StopwatchTimer t = wl.mTimerFull;
8677 if (t == null) {
8678 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
8679 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
8680 wl.mTimerFull = t;
8681 }
8682 return t;
8683 }
8684 case WAKE_TYPE_WINDOW: {
8685 StopwatchTimer t = wl.mTimerWindow;
8686 if (t == null) {
8687 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
8688 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
8689 wl.mTimerWindow = t;
8690 }
8691 return t;
8692 }
8693 case WAKE_TYPE_DRAW: {
8694 StopwatchTimer t = wl.mTimerDraw;
8695 if (t == null) {
8696 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
8697 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
8698 wl.mTimerDraw = t;
8699 }
8700 return t;
8701 }
8702 default:
8703 throw new IllegalArgumentException("type=" + type);
8704 }
8705 }
8706
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008707 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008708 Wakelock wl = mWakelockStats.startObject(name);
8709 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07008710 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 }
Bookatzc8c44962017-05-11 12:12:54 -07008712 if (type == WAKE_TYPE_PARTIAL) {
8713 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
8714 if (pid >= 0) {
8715 Pid p = getPidStatsLocked(pid);
8716 if (p.mWakeNesting++ == 0) {
8717 p.mWakeStartMs = elapsedRealtimeMs;
8718 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -07008719 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008721 }
8722
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008723 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008724 Wakelock wl = mWakelockStats.stopObject(name);
8725 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07008726 getWakelockTimerLocked(wl, type).stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008727 }
Bookatzc8c44962017-05-11 12:12:54 -07008728 if (type == WAKE_TYPE_PARTIAL) {
8729 if (mAggregatedPartialWakelockTimer != null) {
8730 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
8731 }
8732 if (pid >= 0) {
8733 Pid p = mPids.get(pid);
8734 if (p != null && p.mWakeNesting > 0) {
8735 if (p.mWakeNesting-- == 1) {
8736 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
8737 p.mWakeStartMs = 0;
8738 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008739 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008740 }
8741 }
8742 }
8743
Dianne Hackborn287952c2010-09-22 22:34:31 -07008744 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
8745 Proc p = getProcessStatsLocked(proc);
8746 if (p != null) {
8747 p.addExcessiveCpu(overTime, usedTime);
8748 }
8749 }
8750
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008751 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08008752 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -08008753 t.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008754 }
8755
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008756 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008757 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -08008758 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008759 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008760 t.stopRunningLocked(elapsedRealtimeMs);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008762 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008763
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008764 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08008765 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008767
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008768 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08008769 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008770 }
8771
8772 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08008773 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 }
8775 }
8776
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008777 public long[] getCpuFreqs() {
8778 return mCpuFreqs;
8779 }
8780
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07008781 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
8782 UserInfoProvider userInfoProvider) {
8783 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07008784 }
8785
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07008786 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
8787 PlatformIdleStateCallback cb,
8788 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -08008789 init(clocks);
8790
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07008791 if (systemDir != null) {
8792 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
8793 new File(systemDir, "batterystats.bin.tmp"));
8794 } else {
8795 mFile = null;
8796 }
8797 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008798 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -08008799 mHandler = new MyHandler(handler.getLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008800 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -08008801 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008802 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008803 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008804 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07008805 }
Joe Onoratoabded112016-02-08 16:49:39 -08008806 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
8807 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
8808 mOnBatteryTimeBase);
8809 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
8810 mOnBatteryTimeBase);
8811 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
8812 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
8813 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
8814 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
8815 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
8816 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
8817 mOnBatteryTimeBase);
8818 }
8819 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
8820 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07008821 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008822 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008823 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07008824 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008825 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008826 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
8827 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008828 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008829 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
8830 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
8831 NUM_BT_TX_LEVELS);
8832 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
8833 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -08008834 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
8835 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
8836 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07008837 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008838 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
8839 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08008840 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
8841 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08008842 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008843 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -07008844 mOnBatteryTimeBase);
8845 }
Joe Onoratoabded112016-02-08 16:49:39 -08008846 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
8847 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
8848 mOnBatteryTimeBase);
8849 }
8850 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
8851 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
8852 mOnBatteryTimeBase);
8853 }
8854 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
8855 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
8856 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
8857 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
8858 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07008859 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
8860 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008861 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -08008862 long uptime = mClocks.uptimeMillis() * 1000;
8863 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008864 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008865 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -07008866 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008867 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07008868 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -07008869 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07008870 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08008871 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008872 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008873 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07008874 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07008875 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008876 }
8877
8878 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -08008879 this(new SystemClocks(), p);
8880 }
8881
8882 public BatteryStatsImpl(Clocks clocks, Parcel p) {
8883 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008884 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07008885 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008886 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07008887 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07008888 mExternalSync = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008889 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008890 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07008891 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 }
8893
Adam Lesinski14ae39a2017-05-26 11:50:40 -07008894 public void setPowerProfileLocked(PowerProfile profile) {
8895 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -07008896
Adam Lesinski14ae39a2017-05-26 11:50:40 -07008897 // We need to initialize the KernelCpuSpeedReaders to read from
8898 // the first cpu of each core. Once we have the PowerProfile, we have access to this
8899 // information.
8900 final int numClusters = mPowerProfile.getNumCpuClusters();
8901 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
8902 int firstCpuOfCluster = 0;
8903 for (int i = 0; i < numClusters; i++) {
8904 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
8905 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
8906 numSpeedSteps);
8907 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
8908 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -07008909
Adam Lesinski14ae39a2017-05-26 11:50:40 -07008910 if (mEstimatedBatteryCapacity == -1) {
8911 // Initialize the estimated battery capacity to a known preset one.
8912 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -07008913 }
8914 }
8915
Dianne Hackborn0d903a82010-09-07 23:51:03 -07008916 public void setCallback(BatteryCallback cb) {
8917 mCallback = cb;
8918 }
8919
Adam Lesinski14ae39a2017-05-26 11:50:40 -07008920 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07008921 if (mPhoneSignalScanningTimer != null) {
8922 mPhoneSignalScanningTimer.setTimeout(timeout);
8923 }
8924 }
8925
Adam Lesinskib3a1bad2017-05-26 11:50:40 -07008926 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
8927 mExternalSync = sync;
8928 }
8929
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008930 public void updateDailyDeadlineLocked() {
8931 // Get the current time.
8932 long currentTime = mDailyStartTime = System.currentTimeMillis();
8933 Calendar calDeadline = Calendar.getInstance();
8934 calDeadline.setTimeInMillis(currentTime);
8935
8936 // Move time up to the next day, ranging from 1am to 3pm.
8937 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
8938 calDeadline.set(Calendar.MILLISECOND, 0);
8939 calDeadline.set(Calendar.SECOND, 0);
8940 calDeadline.set(Calendar.MINUTE, 0);
8941 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
8942 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
8943 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
8944 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
8945 }
8946
8947 public void recordDailyStatsIfNeededLocked(boolean settled) {
8948 long currentTime = System.currentTimeMillis();
8949 if (currentTime >= mNextMaxDailyDeadline) {
8950 recordDailyStatsLocked();
8951 } else if (settled && currentTime >= mNextMinDailyDeadline) {
8952 recordDailyStatsLocked();
8953 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
8954 recordDailyStatsLocked();
8955 }
8956 }
8957
8958 public void recordDailyStatsLocked() {
8959 DailyItem item = new DailyItem();
8960 item.mStartTime = mDailyStartTime;
8961 item.mEndTime = System.currentTimeMillis();
8962 boolean hasData = false;
8963 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
8964 hasData = true;
8965 item.mDischargeSteps = new LevelStepTracker(
8966 mDailyDischargeStepTracker.mNumStepDurations,
8967 mDailyDischargeStepTracker.mStepDurations);
8968 }
8969 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
8970 hasData = true;
8971 item.mChargeSteps = new LevelStepTracker(
8972 mDailyChargeStepTracker.mNumStepDurations,
8973 mDailyChargeStepTracker.mStepDurations);
8974 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07008975 if (mDailyPackageChanges != null) {
8976 hasData = true;
8977 item.mPackageChanges = mDailyPackageChanges;
8978 mDailyPackageChanges = null;
8979 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008980 mDailyDischargeStepTracker.init();
8981 mDailyChargeStepTracker.init();
8982 updateDailyDeadlineLocked();
8983
8984 if (hasData) {
8985 mDailyItems.add(item);
8986 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
8987 mDailyItems.remove(0);
8988 }
8989 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
8990 try {
8991 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01008992 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008993 writeDailyItemsLocked(out);
8994 BackgroundThread.getHandler().post(new Runnable() {
8995 @Override
8996 public void run() {
8997 synchronized (mCheckinFile) {
8998 FileOutputStream stream = null;
8999 try {
9000 stream = mDailyFile.startWrite();
9001 memStream.writeTo(stream);
9002 stream.flush();
9003 FileUtils.sync(stream);
9004 stream.close();
9005 mDailyFile.finishWrite(stream);
9006 } catch (IOException e) {
9007 Slog.w("BatteryStats",
9008 "Error writing battery daily items", e);
9009 mDailyFile.failWrite(stream);
9010 }
9011 }
9012 }
9013 });
9014 } catch (IOException e) {
9015 }
9016 }
9017 }
9018
9019 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
9020 StringBuilder sb = new StringBuilder(64);
9021 out.startDocument(null, true);
9022 out.startTag(null, "daily-items");
9023 for (int i=0; i<mDailyItems.size(); i++) {
9024 final DailyItem dit = mDailyItems.get(i);
9025 out.startTag(null, "item");
9026 out.attribute(null, "start", Long.toString(dit.mStartTime));
9027 out.attribute(null, "end", Long.toString(dit.mEndTime));
9028 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
9029 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07009030 if (dit.mPackageChanges != null) {
9031 for (int j=0; j<dit.mPackageChanges.size(); j++) {
9032 PackageChange pc = dit.mPackageChanges.get(j);
9033 if (pc.mUpdate) {
9034 out.startTag(null, "upd");
9035 out.attribute(null, "pkg", pc.mPackageName);
9036 out.attribute(null, "ver", Integer.toString(pc.mVersionCode));
9037 out.endTag(null, "upd");
9038 } else {
9039 out.startTag(null, "rem");
9040 out.attribute(null, "pkg", pc.mPackageName);
9041 out.endTag(null, "rem");
9042 }
9043 }
9044 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009045 out.endTag(null, "item");
9046 }
9047 out.endTag(null, "daily-items");
9048 out.endDocument();
9049 }
9050
9051 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
9052 StringBuilder tmpBuilder) throws IOException {
9053 if (steps != null) {
9054 out.startTag(null, tag);
9055 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
9056 for (int i=0; i<steps.mNumStepDurations; i++) {
9057 out.startTag(null, "s");
9058 tmpBuilder.setLength(0);
9059 steps.encodeEntryAt(i, tmpBuilder);
9060 out.attribute(null, "v", tmpBuilder.toString());
9061 out.endTag(null, "s");
9062 }
9063 out.endTag(null, tag);
9064 }
9065 }
9066
9067 public void readDailyStatsLocked() {
9068 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
9069 mDailyItems.clear();
9070 FileInputStream stream;
9071 try {
9072 stream = mDailyFile.openRead();
9073 } catch (FileNotFoundException e) {
9074 return;
9075 }
9076 try {
9077 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01009078 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009079 readDailyItemsLocked(parser);
9080 } catch (XmlPullParserException e) {
9081 } finally {
9082 try {
9083 stream.close();
9084 } catch (IOException e) {
9085 }
9086 }
9087 }
9088
9089 private void readDailyItemsLocked(XmlPullParser parser) {
9090 try {
9091 int type;
9092 while ((type = parser.next()) != XmlPullParser.START_TAG
9093 && type != XmlPullParser.END_DOCUMENT) {
9094 ;
9095 }
9096
9097 if (type != XmlPullParser.START_TAG) {
9098 throw new IllegalStateException("no start tag found");
9099 }
9100
9101 int outerDepth = parser.getDepth();
9102 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
9103 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
9104 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
9105 continue;
9106 }
9107
9108 String tagName = parser.getName();
9109 if (tagName.equals("item")) {
9110 readDailyItemTagLocked(parser);
9111 } else {
9112 Slog.w(TAG, "Unknown element under <daily-items>: "
9113 + parser.getName());
9114 XmlUtils.skipCurrentTag(parser);
9115 }
9116 }
9117
9118 } catch (IllegalStateException e) {
9119 Slog.w(TAG, "Failed parsing daily " + e);
9120 } catch (NullPointerException e) {
9121 Slog.w(TAG, "Failed parsing daily " + e);
9122 } catch (NumberFormatException e) {
9123 Slog.w(TAG, "Failed parsing daily " + e);
9124 } catch (XmlPullParserException e) {
9125 Slog.w(TAG, "Failed parsing daily " + e);
9126 } catch (IOException e) {
9127 Slog.w(TAG, "Failed parsing daily " + e);
9128 } catch (IndexOutOfBoundsException e) {
9129 Slog.w(TAG, "Failed parsing daily " + e);
9130 }
9131 }
9132
9133 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
9134 XmlPullParserException, IOException {
9135 DailyItem dit = new DailyItem();
9136 String attr = parser.getAttributeValue(null, "start");
9137 if (attr != null) {
9138 dit.mStartTime = Long.parseLong(attr);
9139 }
9140 attr = parser.getAttributeValue(null, "end");
9141 if (attr != null) {
9142 dit.mEndTime = Long.parseLong(attr);
9143 }
9144 int outerDepth = parser.getDepth();
9145 int type;
9146 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
9147 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
9148 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
9149 continue;
9150 }
9151
9152 String tagName = parser.getName();
9153 if (tagName.equals("dis")) {
9154 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
9155 } else if (tagName.equals("chg")) {
9156 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -07009157 } else if (tagName.equals("upd")) {
9158 if (dit.mPackageChanges == null) {
9159 dit.mPackageChanges = new ArrayList<>();
9160 }
9161 PackageChange pc = new PackageChange();
9162 pc.mUpdate = true;
9163 pc.mPackageName = parser.getAttributeValue(null, "pkg");
9164 String verStr = parser.getAttributeValue(null, "ver");
9165 pc.mVersionCode = verStr != null ? Integer.parseInt(verStr) : 0;
9166 dit.mPackageChanges.add(pc);
9167 XmlUtils.skipCurrentTag(parser);
9168 } else if (tagName.equals("rem")) {
9169 if (dit.mPackageChanges == null) {
9170 dit.mPackageChanges = new ArrayList<>();
9171 }
9172 PackageChange pc = new PackageChange();
9173 pc.mUpdate = false;
9174 pc.mPackageName = parser.getAttributeValue(null, "pkg");
9175 dit.mPackageChanges.add(pc);
9176 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009177 } else {
9178 Slog.w(TAG, "Unknown element under <item>: "
9179 + parser.getName());
9180 XmlUtils.skipCurrentTag(parser);
9181 }
9182 }
9183 mDailyItems.add(dit);
9184 }
9185
9186 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
9187 String tag)
9188 throws NumberFormatException, XmlPullParserException, IOException {
9189 final String numAttr = parser.getAttributeValue(null, "n");
9190 if (numAttr == null) {
9191 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
9192 XmlUtils.skipCurrentTag(parser);
9193 return;
9194 }
9195 final int num = Integer.parseInt(numAttr);
9196 LevelStepTracker steps = new LevelStepTracker(num);
9197 if (isCharge) {
9198 dit.mChargeSteps = steps;
9199 } else {
9200 dit.mDischargeSteps = steps;
9201 }
9202 int i = 0;
9203 int outerDepth = parser.getDepth();
9204 int type;
9205 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
9206 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
9207 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
9208 continue;
9209 }
9210
9211 String tagName = parser.getName();
9212 if ("s".equals(tagName)) {
9213 if (i < num) {
9214 String valueAttr = parser.getAttributeValue(null, "v");
9215 if (valueAttr != null) {
9216 steps.decodeEntryAt(i, valueAttr);
9217 i++;
9218 }
9219 }
9220 } else {
9221 Slog.w(TAG, "Unknown element under <" + tag + ">: "
9222 + parser.getName());
9223 XmlUtils.skipCurrentTag(parser);
9224 }
9225 }
9226 steps.mNumStepDurations = i;
9227 }
9228
9229 @Override
9230 public DailyItem getDailyItemLocked(int daysAgo) {
9231 int index = mDailyItems.size()-1-daysAgo;
9232 return index >= 0 ? mDailyItems.get(index) : null;
9233 }
9234
9235 @Override
9236 public long getCurrentDailyStartTime() {
9237 return mDailyStartTime;
9238 }
9239
9240 @Override
9241 public long getNextMinDailyDeadline() {
9242 return mNextMinDailyDeadline;
9243 }
9244
9245 @Override
9246 public long getNextMaxDailyDeadline() {
9247 return mNextMaxDailyDeadline;
9248 }
9249
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009250 @Override
9251 public boolean startIteratingOldHistoryLocked() {
9252 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
9253 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009254 if ((mHistoryIterator = mHistory) == null) {
9255 return false;
9256 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009257 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -07009258 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009259 mReadOverflow = false;
9260 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009261 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07009262 }
9263
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009264 @Override
9265 public boolean getNextOldHistoryLocked(HistoryItem out) {
9266 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
9267 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08009268 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -07009269 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009270 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -07009271 HistoryItem cur = mHistoryIterator;
9272 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009273 if (!mReadOverflow && !end) {
9274 Slog.w(TAG, "Old history ends before new history!");
9275 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -07009276 return false;
9277 }
9278 out.setTo(cur);
9279 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009280 if (!mReadOverflow) {
9281 if (end) {
9282 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -07009283 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07009284 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009285 pw.println("Histories differ!");
9286 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -07009287 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009288 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -07009289 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
9290 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -07009291 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009292 }
9293 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -07009294 return true;
9295 }
9296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009297 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009298 public void finishIteratingOldHistoryLocked() {
9299 mIteratingHistory = false;
9300 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009301 mHistoryIterator = null;
9302 }
9303
9304 public int getHistoryTotalSize() {
9305 return MAX_HISTORY_BUFFER;
9306 }
9307
9308 public int getHistoryUsedSize() {
9309 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009310 }
9311
9312 @Override
9313 public boolean startIteratingHistoryLocked() {
9314 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
9315 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009316 if (mHistoryBuffer.dataSize() <= 0) {
9317 return false;
9318 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009319 mHistoryBuffer.setDataPosition(0);
9320 mReadOverflow = false;
9321 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009322 mReadHistoryStrings = new String[mHistoryTagPool.size()];
9323 mReadHistoryUids = new int[mHistoryTagPool.size()];
9324 mReadHistoryChars = 0;
9325 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
9326 final HistoryTag tag = ent.getKey();
9327 final int idx = ent.getValue();
9328 mReadHistoryStrings[idx] = tag.string;
9329 mReadHistoryUids[idx] = tag.uid;
9330 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -08009331 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009332 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009333 }
9334
9335 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009336 public int getHistoryStringPoolSize() {
9337 return mReadHistoryStrings.length;
9338 }
9339
9340 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009341 public int getHistoryStringPoolBytes() {
9342 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
9343 // Each string character is 2 bytes.
9344 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
9345 }
9346
9347 @Override
9348 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009349 return mReadHistoryStrings[index];
9350 }
9351
9352 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009353 public int getHistoryTagPoolUid(int index) {
9354 return mReadHistoryUids[index];
9355 }
9356
9357 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009358 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -07009359 final int pos = mHistoryBuffer.dataPosition();
9360 if (pos == 0) {
9361 out.clear();
9362 }
9363 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009364 if (end) {
9365 return false;
9366 }
9367
Dianne Hackborn99009ea2014-04-18 16:23:42 -07009368 final long lastRealtime = out.time;
9369 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08009370 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -07009371 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
9372 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -07009373 out.currentTime = lastWalltime + (out.time - lastRealtime);
9374 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009375 return true;
9376 }
9377
9378 @Override
9379 public void finishIteratingHistoryLocked() {
9380 mIteratingHistory = false;
9381 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -08009382 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009383 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009384
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009385 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009386 public long getHistoryBaseTime() {
9387 return mHistoryBaseTime;
9388 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009389
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009390 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009391 public int getStartCount() {
9392 return mStartCount;
9393 }
9394
9395 public boolean isOnBattery() {
9396 return mOnBattery;
9397 }
9398
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07009399 public boolean isCharging() {
9400 return mCharging;
9401 }
9402
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009403 public boolean isScreenOn() {
Jeff Browne95c3cd2014-05-02 16:59:26 -07009404 return mScreenState == Display.STATE_ON;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009405 }
9406
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009407 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08009408 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009409 mOnBatteryTimeBase.init(uptime, realtime);
9410 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -07009411 mRealtime = 0;
9412 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009413 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -07009414 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009415 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009416
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009417 void initDischarge() {
9418 mLowDischargeAmountSinceCharge = 0;
9419 mHighDischargeAmountSinceCharge = 0;
9420 mDischargeAmountScreenOn = 0;
9421 mDischargeAmountScreenOnSinceCharge = 0;
9422 mDischargeAmountScreenOff = 0;
9423 mDischargeAmountScreenOffSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009424 mDischargeStepTracker.init();
9425 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009426 mDischargeScreenOffCounter.reset(false);
9427 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009428 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009429
9430 public void resetAllStatsCmdLocked() {
9431 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -08009432 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07009433 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -08009434 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009435 long realtime = mSecRealtime * 1000;
9436 mDischargeStartLevel = mHistoryCur.batteryLevel;
9437 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -07009438 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009439 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
9440 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009441 mOnBatteryTimeBase.reset(uptime, realtime);
9442 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
9443 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07009444 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009445 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
9446 mDischargeScreenOffUnplugLevel = 0;
9447 } else {
9448 mDischargeScreenOnUnplugLevel = 0;
9449 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
9450 }
9451 mDischargeAmountScreenOn = 0;
9452 mDischargeAmountScreenOff = 0;
9453 }
Dianne Hackborn40c87252014-03-19 16:55:40 -07009454 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009455 }
9456
9457 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -07009458 final long uptimeMillis = mClocks.uptimeMillis();
9459 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009460 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -07009461 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009462 mScreenOnTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009463 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009464 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009465 }
Adam Lesinski1a76a622016-06-22 10:28:47 -07009466
9467 if (mPowerProfile != null) {
9468 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
9469 } else {
9470 mEstimatedBatteryCapacity = -1;
9471 }
Jocelyn Dangc627d102017-04-14 13:15:14 -07009472 mMinLearnedBatteryCapacity = -1;
9473 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -07009474 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07009475 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -07009476 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07009477 mLongestLightIdleTime = 0;
9478 mLongestFullIdleTime = 0;
9479 mDeviceIdleModeLightTimer.reset(false);
9480 mDeviceIdleModeFullTimer.reset(false);
9481 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07009482 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009483 mPhoneOnTimer.reset(false);
9484 mAudioOnTimer.reset(false);
9485 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07009486 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07009487 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08009488 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -08009489 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009490 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009491 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009492 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009493 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009494 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009495 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009496 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08009497 mNetworkByteActivityCounters[i].reset(false);
9498 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009499 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009500 mMobileRadioActiveTimer.reset(false);
9501 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009502 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08009503 mMobileRadioActiveUnknownTime.reset(false);
9504 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009505 mWifiOnTimer.reset(false);
9506 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08009507 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009508 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08009509 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07009510 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9511 mWifiSupplStateTimer[i].reset(false);
9512 }
9513 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9514 mWifiSignalStrengthsTimer[i].reset(false);
9515 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009516 mWifiActivity.reset(false);
9517 mBluetoothActivity.reset(false);
9518 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009519 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009520
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009521 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -07009522 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009523 mUidStats.remove(mUidStats.keyAt(i));
9524 i--;
9525 }
9526 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009527
Bookatz50df7112017-08-04 14:53:26 -07009528 if (mRpmStats.size() > 0) {
9529 for (SamplingTimer timer : mRpmStats.values()) {
9530 mOnBatteryTimeBase.remove(timer);
9531 }
9532 mRpmStats.clear();
9533 }
9534 if (mScreenOffRpmStats.size() > 0) {
9535 for (SamplingTimer timer : mScreenOffRpmStats.values()) {
9536 mOnBatteryScreenOffTimeBase.remove(timer);
9537 }
9538 mScreenOffRpmStats.clear();
9539 }
9540
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009541 if (mKernelWakelockStats.size() > 0) {
9542 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009543 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009544 }
9545 mKernelWakelockStats.clear();
9546 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009547
James Carr3a226052016-07-01 14:49:52 -07009548 if (mKernelMemoryStats.size() > 0) {
9549 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
9550 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
9551 }
9552 mKernelMemoryStats.clear();
9553 }
9554
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009555 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07009556 for (SamplingTimer timer : mWakeupReasonStats.values()) {
9557 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009558 }
9559 mWakeupReasonStats.clear();
9560 }
9561
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08009562 mLastHistoryStepDetails = null;
9563 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
9564 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
9565 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
9566 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
9567 mLastStepStatUserTime = mCurStepStatUserTime = 0;
9568 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
9569 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
9570 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
9571 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
9572 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
9573
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009574 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009575
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009576 clearHistoryLocked();
9577 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009578
Dianne Hackborn40c87252014-03-19 16:55:40 -07009579 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009580 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009581 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
9582 // Not recording process starts/stops.
9583 continue;
9584 }
Dianne Hackborn37de0982014-05-09 09:32:18 -07009585 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009586 if (active == null) {
9587 continue;
9588 }
Dianne Hackborn37de0982014-05-09 09:32:18 -07009589 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
9590 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009591 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -07009592 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
9593 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009594 }
9595 }
9596 }
9597 }
9598
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009599 void updateDischargeScreenLevelsLocked(boolean oldScreenOn, boolean newScreenOn) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009600 if (oldScreenOn) {
9601 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
9602 if (diff > 0) {
9603 mDischargeAmountScreenOn += diff;
9604 mDischargeAmountScreenOnSinceCharge += diff;
9605 }
9606 } else {
9607 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
9608 if (diff > 0) {
9609 mDischargeAmountScreenOff += diff;
9610 mDischargeAmountScreenOffSinceCharge += diff;
9611 }
9612 }
9613 if (newScreenOn) {
9614 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
9615 mDischargeScreenOffUnplugLevel = 0;
9616 } else {
9617 mDischargeScreenOnUnplugLevel = 0;
9618 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
9619 }
9620 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009621
Dianne Hackborna7c837f2014-01-15 16:20:44 -08009622 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08009623 if (mOnBatteryInternal) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07009624 final boolean screenOn = mScreenState == Display.STATE_ON;
9625 updateDischargeScreenLevelsLocked(screenOn, screenOn);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08009626 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -08009627 }
9628
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009629 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
9630 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
9631
9632 private final Object mWifiNetworkLock = new Object();
9633
9634 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009635 private String[] mWifiIfaces = EmptyArray.STRING;
9636
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009637 @GuardedBy("mWifiNetworkLock")
9638 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009639
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009640 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009641
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009642 @GuardedBy("mModemNetworkLock")
9643 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009644
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009645 @GuardedBy("mModemNetworkLock")
9646 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
9647
9648 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
9649 try {
9650 if (!ArrayUtils.isEmpty(ifaces)) {
9651 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
9652 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
9653 }
9654 } catch (IOException e) {
9655 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009656 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009657 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009658 }
9659
9660 /**
9661 * Distribute WiFi energy info and network traffic to apps.
9662 * @param info The energy information from the WiFi controller.
9663 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009664 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009665 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009666 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009667 }
9668
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009669 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -07009670 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009671 synchronized (mWifiNetworkLock) {
9672 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
9673 if (latestStats != null) {
9674 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
9675 mNetworkStatsPool.acquire());
9676 mNetworkStatsPool.release(mLastWifiNetworkStats);
9677 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -07009678 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009679 }
9680
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009681 synchronized (this) {
9682 if (!mOnBatteryInternal) {
9683 if (delta != null) {
9684 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009685 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009686 return;
9687 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009688
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009689 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
9690 SparseLongArray rxPackets = new SparseLongArray();
9691 SparseLongArray txPackets = new SparseLongArray();
9692 long totalTxPackets = 0;
9693 long totalRxPackets = 0;
9694 if (delta != null) {
9695 NetworkStats.Entry entry = new NetworkStats.Entry();
9696 final int size = delta.size();
9697 for (int i = 0; i < size; i++) {
9698 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009699
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009700 if (DEBUG_ENERGY) {
9701 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
9702 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
9703 + " txPackets=" + entry.txPackets);
9704 }
9705
9706 if (entry.rxBytes == 0 && entry.txBytes == 0) {
9707 // Skip the lookup below since there is no work to do.
9708 continue;
9709 }
9710
9711 final Uid u = getUidStatsLocked(mapUid(entry.uid));
9712 if (entry.rxBytes != 0) {
9713 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -08009714 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009715 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
9716 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
9717 entry.rxPackets);
9718 }
9719 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
9720 entry.rxBytes);
9721 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
9722 entry.rxPackets);
9723
9724 rxPackets.put(u.getUid(), entry.rxPackets);
9725
9726 // Sum the total number of packets so that the Rx Power can
9727 // be evenly distributed amongst the apps.
9728 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -08009729 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009730
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009731 if (entry.txBytes != 0) {
9732 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -08009733 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009734 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
9735 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
9736 entry.txPackets);
9737 }
9738 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
9739 entry.txBytes);
9740 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
9741 entry.txPackets);
9742
9743 txPackets.put(u.getUid(), entry.txPackets);
9744
9745 // Sum the total number of packets so that the Tx Power can
9746 // be evenly distributed amongst the apps.
9747 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -08009748 }
Adam Lesinskiba88e682015-12-08 12:06:55 -08009749 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009750 mNetworkStatsPool.release(delta);
9751 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07009752 }
9753
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009754 if (info != null) {
9755 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -07009756
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009757 // Measured in mAms
9758 final long txTimeMs = info.getControllerTxTimeMillis();
9759 final long rxTimeMs = info.getControllerRxTimeMillis();
9760 final long idleTimeMs = info.getControllerIdleTimeMillis();
9761 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -07009762
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009763 long leftOverRxTimeMs = rxTimeMs;
9764 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -07009765
Adam Lesinskie08af192015-03-25 16:42:59 -07009766 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009767 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
9768 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
9769 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
9770 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
9771 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -07009772 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009773
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009774 long totalWifiLockTimeMs = 0;
9775 long totalScanTimeMs = 0;
9776
9777 // On the first pass, collect some totals so that we can normalize power
9778 // calculations if we need to.
9779 final int uidStatsSize = mUidStats.size();
9780 for (int i = 0; i < uidStatsSize; i++) {
9781 final Uid uid = mUidStats.valueAt(i);
9782
9783 // Sum the total scan power for all apps.
9784 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
9785 elapsedRealtimeMs * 1000) / 1000;
9786
9787 // Sum the total time holding wifi lock for all apps.
9788 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
9789 elapsedRealtimeMs * 1000) / 1000;
9790 }
9791
9792 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
9793 Slog.d(TAG,
9794 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
9795 + rxTimeMs + " ms). Normalizing scan time.");
9796 }
9797 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
9798 Slog.d(TAG,
9799 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
9800 + txTimeMs + " ms). Normalizing scan time.");
9801 }
9802
9803 // Actually assign and distribute power usage to apps.
9804 for (int i = 0; i < uidStatsSize; i++) {
9805 final Uid uid = mUidStats.valueAt(i);
9806
9807 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
9808 elapsedRealtimeMs * 1000) / 1000;
9809 if (scanTimeSinceMarkMs > 0) {
9810 // Set the new mark so that next time we get new data since this point.
9811 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
9812
9813 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
9814 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
9815
9816 // Our total scan time is more than the reported Tx/Rx time.
9817 // This is possible because the cost of a scan is approximate.
9818 // Let's normalize the result so that we evenly blame each app
9819 // scanning.
9820 //
9821 // This means that we may have apps that transmitted/received packets not be
9822 // blamed for this, but this is fine as scans are relatively more expensive.
9823 if (totalScanTimeMs > rxTimeMs) {
9824 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
9825 totalScanTimeMs;
9826 }
9827 if (totalScanTimeMs > txTimeMs) {
9828 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
9829 totalScanTimeMs;
9830 }
9831
9832 if (DEBUG_ENERGY) {
9833 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
9834 + scanRxTimeSinceMarkMs + " ms Tx:"
9835 + scanTxTimeSinceMarkMs + " ms)");
9836 }
9837
9838 ControllerActivityCounterImpl activityCounter =
9839 uid.getOrCreateWifiControllerActivityLocked();
9840 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
9841 activityCounter.getTxTimeCounters()[0].addCountLocked(
9842 scanTxTimeSinceMarkMs);
9843 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
9844 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
9845 }
9846
9847 // Distribute evenly the power consumed while Idle to each app holding a WiFi
9848 // lock.
9849 final long wifiLockTimeSinceMarkMs =
9850 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
9851 elapsedRealtimeMs * 1000) / 1000;
9852 if (wifiLockTimeSinceMarkMs > 0) {
9853 // Set the new mark so that next time we get new data since this point.
9854 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
9855
9856 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
9857 / totalWifiLockTimeMs;
9858 if (DEBUG_ENERGY) {
9859 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
9860 + myIdleTimeMs + " ms");
9861 }
9862 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
9863 .addCountLocked(myIdleTimeMs);
9864 }
9865 }
9866
Adam Lesinskie08af192015-03-25 16:42:59 -07009867 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009868 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
9869 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -07009870 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009871
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009872 // Distribute the remaining Tx power appropriately between all apps that transmitted
9873 // packets.
9874 for (int i = 0; i < txPackets.size(); i++) {
9875 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
9876 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
9877 / totalTxPackets;
9878 if (DEBUG_ENERGY) {
9879 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
9880 }
9881 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
9882 .addCountLocked(myTxTimeMs);
9883 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009884
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009885 // Distribute the remaining Rx power appropriately between all apps that received
9886 // packets.
9887 for (int i = 0; i < rxPackets.size(); i++) {
9888 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
9889 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
9890 / totalRxPackets;
9891 if (DEBUG_ENERGY) {
9892 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
9893 }
9894 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
9895 .addCountLocked(myRxTimeMs);
9896 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009897
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009898 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
9899
9900
9901 // Update WiFi controller stats.
9902 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
9903 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
9904 info.getControllerTxTimeMillis());
9905 mWifiActivity.getIdleTimeCounter().addCountLocked(
9906 info.getControllerIdleTimeMillis());
9907
9908 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
9909 final double opVolt = mPowerProfile.getAveragePower(
9910 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
9911 if (opVolt != 0) {
9912 // We store the power drain as mAms.
9913 mWifiActivity.getPowerCounter().addCountLocked(
9914 (long) (info.getControllerEnergyUsed() / opVolt));
9915 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009916 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009917 }
9918 }
9919
9920 /**
9921 * Distribute Cell radio energy info and network traffic to apps.
9922 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009923 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009924 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009925 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009926 }
9927
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009928 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -07009929 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009930 synchronized (mModemNetworkLock) {
9931 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
9932 if (latestStats != null) {
9933 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
9934 mNetworkStatsPool.acquire());
9935 mNetworkStatsPool.release(mLastModemNetworkStats);
9936 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -07009937 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009938 }
9939
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009940 synchronized (this) {
9941 if (!mOnBatteryInternal) {
9942 if (delta != null) {
9943 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009944 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009945 return;
Adam Lesinskie08af192015-03-25 16:42:59 -07009946 }
9947
Adam Lesinskib3a1bad2017-05-26 11:50:40 -07009948 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009949 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
9950 elapsedRealtimeMs * 1000);
9951 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
9952
9953 long totalRxPackets = 0;
9954 long totalTxPackets = 0;
9955 if (delta != null) {
9956 NetworkStats.Entry entry = new NetworkStats.Entry();
9957 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009958 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009959 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009960 if (entry.rxPackets == 0 && entry.txPackets == 0) {
9961 continue;
9962 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009963
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009964 if (DEBUG_ENERGY) {
9965 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
9966 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
9967 + " txPackets=" + entry.txPackets);
9968 }
9969
9970 totalRxPackets += entry.rxPackets;
9971 totalTxPackets += entry.txPackets;
9972
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009973 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009974 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
9975 entry.rxPackets);
9976 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
9977 entry.txPackets);
9978 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
9979 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
9980 entry.rxBytes, entry.rxPackets);
9981 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
9982 entry.txBytes, entry.txPackets);
9983 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009984
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009985 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
9986 entry.rxBytes);
9987 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
9988 entry.txBytes);
9989 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
9990 entry.rxPackets);
9991 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
9992 entry.txPackets);
9993 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009994
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009995 // Now distribute proportional blame to the apps that did networking.
9996 long totalPackets = totalRxPackets + totalTxPackets;
9997 if (totalPackets > 0) {
9998 for (int i = 0; i < size; i++) {
9999 entry = delta.getValues(i, entry);
10000 if (entry.rxPackets == 0 && entry.txPackets == 0) {
10001 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010002 }
10003
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010004 final Uid u = getUidStatsLocked(mapUid(entry.uid));
10005
10006 // Distribute total radio active time in to this app.
10007 final long appPackets = entry.rxPackets + entry.txPackets;
10008 final long appRadioTime = (radioTime * appPackets) / totalPackets;
10009 u.noteMobileRadioActiveTimeLocked(appRadioTime);
10010
10011 // Remove this app from the totals, so that we don't lose any time
10012 // due to rounding.
10013 radioTime -= appRadioTime;
10014 totalPackets -= appPackets;
10015
10016 if (activityInfo != null) {
10017 ControllerActivityCounterImpl activityCounter =
10018 u.getOrCreateModemControllerActivityLocked();
10019 if (totalRxPackets > 0 && entry.rxPackets > 0) {
10020 final long rxMs = (entry.rxPackets * activityInfo.getRxTimeMillis())
10021 / totalRxPackets;
10022 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
10023 }
10024
10025 if (totalTxPackets > 0 && entry.txPackets > 0) {
10026 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
10027 long txMs =
10028 entry.txPackets * activityInfo.getTxTimeMillis()[lvl];
10029 txMs /= totalTxPackets;
10030 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
10031 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010032 }
10033 }
10034 }
10035 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010036
10037 if (radioTime > 0) {
10038 // Whoops, there is some radio time we can't blame on an app!
10039 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
10040 mMobileRadioActiveUnknownCount.addCountLocked(1);
10041 }
10042
10043 mNetworkStatsPool.release(delta);
10044 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010045 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010046
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010047 if (activityInfo != null) {
10048 mHasModemReporting = true;
10049 mModemActivity.getIdleTimeCounter().addCountLocked(
10050 activityInfo.getIdleTimeMillis());
10051 mModemActivity.getRxTimeCounter().addCountLocked(activityInfo.getRxTimeMillis());
10052 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
10053 mModemActivity.getTxTimeCounters()[lvl]
10054 .addCountLocked(activityInfo.getTxTimeMillis()[lvl]);
10055 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010056
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010057 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
10058 final double opVolt = mPowerProfile.getAveragePower(
10059 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
10060 if (opVolt != 0) {
10061 // We store the power drain as mAms.
10062 mModemActivity.getPowerCounter().addCountLocked(
10063 (long) (activityInfo.getEnergyUsed() / opVolt));
10064 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010065 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010066 }
10067 }
10068
10069 /**
10070 * Distribute Bluetooth energy info and network traffic to apps.
10071 * @param info The energy information from the bluetooth controller.
10072 */
10073 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010074 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080010075 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010076 }
10077
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010078 if (info == null || !mOnBatteryInternal) {
10079 return;
10080 }
Adam Lesinskie283d332015-04-16 12:29:25 -070010081
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010082 mHasBluetoothReporting = true;
10083
Bookatz867c0d72017-03-07 18:23:42 -080010084 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010085 final long rxTimeMs = info.getControllerRxTimeMillis();
10086 final long txTimeMs = info.getControllerTxTimeMillis();
10087
10088 if (DEBUG_ENERGY) {
10089 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
10090 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
10091 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
10092 Slog.d(TAG, " Idle Time: " + info.getControllerIdleTimeMillis() + " ms");
10093 }
10094
10095 long totalScanTimeMs = 0;
10096
10097 final int uidCount = mUidStats.size();
10098 for (int i = 0; i < uidCount; i++) {
10099 final Uid u = mUidStats.valueAt(i);
10100 if (u.mBluetoothScanTimer == null) {
10101 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070010102 }
Adam Lesinski50e47602015-12-04 17:04:54 -080010103
Bookatzaa4594a2017-03-24 12:39:56 -070010104 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010105 elapsedRealtimeMs * 1000) / 1000;
10106 }
10107
10108 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
10109 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
10110
10111 if (DEBUG_ENERGY) {
10112 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
10113 + " TX=" + normalizeScanTxTime);
10114 }
10115
10116 long leftOverRxTimeMs = rxTimeMs;
10117 long leftOverTxTimeMs = txTimeMs;
10118
10119 for (int i = 0; i < uidCount; i++) {
10120 final Uid u = mUidStats.valueAt(i);
10121 if (u.mBluetoothScanTimer == null) {
10122 continue;
10123 }
10124
Bookatzaa4594a2017-03-24 12:39:56 -070010125 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010126 elapsedRealtimeMs * 1000) / 1000;
10127 if (scanTimeSinceMarkMs > 0) {
10128 // Set the new mark so that next time we get new data since this point.
10129 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
10130
10131 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
10132 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
10133
10134 if (normalizeScanRxTime) {
10135 // Scan time is longer than the total rx time in the controller,
10136 // so distribute the scan time proportionately. This means regular traffic
10137 // will not blamed, but scans are more expensive anyways.
10138 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
10139 }
10140
10141 if (normalizeScanTxTime) {
10142 // Scan time is longer than the total tx time in the controller,
10143 // so distribute the scan time proportionately. This means regular traffic
10144 // will not blamed, but scans are more expensive anyways.
10145 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
10146 }
10147
10148 final ControllerActivityCounterImpl counter =
10149 u.getOrCreateBluetoothControllerActivityLocked();
10150 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
10151 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
10152
10153 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
10154 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
10155 }
10156 }
10157
10158 if (DEBUG_ENERGY) {
10159 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs
10160 + " TX=" + leftOverTxTimeMs);
10161 }
10162
10163 //
10164 // Now distribute blame to apps that did bluetooth traffic.
10165 //
10166
10167 long totalTxBytes = 0;
10168 long totalRxBytes = 0;
10169
10170 final UidTraffic[] uidTraffic = info.getUidTraffic();
10171 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
10172 for (int i = 0; i < numUids; i++) {
10173 final UidTraffic traffic = uidTraffic[i];
10174
10175 // Add to the global counters.
10176 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(
10177 traffic.getRxBytes());
10178 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(
10179 traffic.getTxBytes());
10180
10181 // Add to the UID counters.
10182 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
10183 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, traffic.getRxBytes(), 0);
10184 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, traffic.getTxBytes(), 0);
10185
10186 // Calculate the total traffic.
10187 totalTxBytes += traffic.getTxBytes();
10188 totalRxBytes += traffic.getRxBytes();
10189 }
10190
10191 if ((totalTxBytes != 0 || totalRxBytes != 0) &&
10192 (leftOverRxTimeMs != 0 || leftOverTxTimeMs != 0)) {
Adam Lesinski50e47602015-12-04 17:04:54 -080010193 for (int i = 0; i < numUids; i++) {
10194 final UidTraffic traffic = uidTraffic[i];
10195
Adam Lesinski50e47602015-12-04 17:04:54 -080010196 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010197 final ControllerActivityCounterImpl counter =
10198 u.getOrCreateBluetoothControllerActivityLocked();
10199
10200 if (totalRxBytes > 0 && traffic.getRxBytes() > 0) {
10201 final long timeRxMs = (leftOverRxTimeMs * traffic.getRxBytes()) / totalRxBytes;
10202
10203 if (DEBUG_ENERGY) {
10204 Slog.d(TAG, "UID=" + traffic.getUid() + " rx_bytes=" + traffic.getRxBytes()
10205 + " rx_time=" + timeRxMs);
10206 }
10207 counter.getRxTimeCounter().addCountLocked(timeRxMs);
10208 leftOverRxTimeMs -= timeRxMs;
10209 }
10210
10211 if (totalTxBytes > 0 && traffic.getTxBytes() > 0) {
10212 final long timeTxMs = (leftOverTxTimeMs * traffic.getTxBytes()) / totalTxBytes;
10213
10214 if (DEBUG_ENERGY) {
10215 Slog.d(TAG, "UID=" + traffic.getUid() + " tx_bytes=" + traffic.getTxBytes()
10216 + " tx_time=" + timeTxMs);
10217 }
10218
10219 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
10220 leftOverTxTimeMs -= timeTxMs;
10221 }
Adam Lesinski50e47602015-12-04 17:04:54 -080010222 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010223 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010224
10225 mBluetoothActivity.getRxTimeCounter().addCountLocked(
10226 info.getControllerRxTimeMillis());
10227 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(
10228 info.getControllerTxTimeMillis());
10229 mBluetoothActivity.getIdleTimeCounter().addCountLocked(
10230 info.getControllerIdleTimeMillis());
10231
10232 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
10233 final double opVolt = mPowerProfile.getAveragePower(
10234 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
10235 if (opVolt != 0) {
10236 // We store the power drain as mAms.
10237 mBluetoothActivity.getPowerCounter().addCountLocked(
10238 (long) (info.getControllerEnergyUsed() / opVolt));
10239 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010240 }
10241
10242 /**
Bookatz50df7112017-08-04 14:53:26 -070010243 * Read and record Resource Power Manager state and voter times.
10244 */
10245 public void updateRpmStatsLocked() {
10246 if (mPlatformIdleStateCallback == null) return;
10247 mPlatformIdleStateCallback.fillLowPowerStats(mTmpRpmStats);
10248
10249 for (Map.Entry<String, RpmStats.PowerStatePlatformSleepState> pstate
10250 : mTmpRpmStats.mPlatformLowPowerStats.entrySet()) {
10251
10252 // Update values for this platform state.
10253 final String pName = pstate.getKey();
10254 final long pTimeUs = pstate.getValue().mTimeMs * 1000;
10255 final int pCount = pstate.getValue().mCount;
10256 getRpmTimerLocked(pName).update(pTimeUs, pCount);
10257 getScreenOffRpmTimerLocked(pName).update(pTimeUs, pCount);
10258
10259 // Update values for each voter of this platform state.
10260 for (Map.Entry<String, RpmStats.PowerStateElement> voter
10261 : pstate.getValue().mVoters.entrySet()) {
10262 final String vName = pName + "." + voter.getKey();
10263 final long vTimeUs = voter.getValue().mTimeMs * 1000;
10264 final int vCount = voter.getValue().mCount;
10265 getRpmTimerLocked(vName).update(vTimeUs, vCount);
10266 getScreenOffRpmTimerLocked(vName).update(vTimeUs, vCount);
10267 }
10268 }
10269
10270 for (Map.Entry<String, RpmStats.PowerStateSubsystem> subsys
10271 : mTmpRpmStats.mSubsystemLowPowerStats.entrySet()) {
10272
10273 final String subsysName = subsys.getKey();
10274 for (Map.Entry<String, RpmStats.PowerStateElement> sstate
10275 : subsys.getValue().mStates.entrySet()) {
10276 final String name = subsysName + "." + sstate.getKey();
10277 final long timeUs = sstate.getValue().mTimeMs * 1000;
10278 final int count = sstate.getValue().mCount;
10279 getRpmTimerLocked(name).update(timeUs, count);
10280 getScreenOffRpmTimerLocked(name).update(timeUs, count);
10281 }
10282 }
10283 }
10284
10285 /**
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010286 * Read and distribute kernel wake lock use across apps.
10287 */
10288 public void updateKernelWakelocksLocked() {
10289 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
10290 mTmpWakelockStats);
10291 if (wakelockStats == null) {
10292 // Not crashing might make board bringup easier.
10293 Slog.w(TAG, "Couldn't get kernel wake lock stats");
10294 return;
10295 }
10296
10297 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
10298 String name = ent.getKey();
10299 KernelWakelockStats.Entry kws = ent.getValue();
10300
10301 SamplingTimer kwlt = mKernelWakelockStats.get(name);
10302 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070010303 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010304 mKernelWakelockStats.put(name, kwlt);
10305 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070010306
Adam Lesinski757c6ea2016-04-21 09:55:41 -070010307 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010308 kwlt.setUpdateVersion(kws.mVersion);
10309 }
10310
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070010311 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070010312 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
10313 // this time.
10314 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
10315 SamplingTimer st = ent.getValue();
10316 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
10317 st.endSample();
10318 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010319 }
10320 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070010321
Adam Lesinskid84ad302016-05-17 18:31:02 -070010322 // Record whether we've seen a non-zero time (for debugging b/22716723).
10323 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070010324 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
10325 }
10326
10327 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
10328 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
10329 wakelockStats.kernelWakelockVersion);
10330 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010331 }
10332
Adam Lesinski72478f02015-06-17 15:39:43 -070010333 // We use an anonymous class to access these variables,
10334 // so they can't live on the stack or they'd have to be
10335 // final MutableLong objects (more allocations).
10336 // Used in updateCpuTimeLocked().
10337 long mTempTotalCpuUserTimeUs;
10338 long mTempTotalCpuSystemTimeUs;
10339
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010340 /**
James Carr3a226052016-07-01 14:49:52 -070010341 * Reads the newest memory stats from the kernel.
10342 */
10343 public void updateKernelMemoryBandwidthLocked() {
10344 mKernelMemoryBandwidthStats.updateStats();
10345 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
10346 final int bandwidthEntryCount = bandwidthEntries.size();
10347 int index;
10348 for (int i = 0; i < bandwidthEntryCount; i++) {
10349 SamplingTimer timer;
10350 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
10351 timer = mKernelMemoryStats.valueAt(index);
10352 } else {
10353 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
10354 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
10355 }
10356 timer.update(bandwidthEntries.valueAt(i), 1);
10357 if (DEBUG_MEMORY) {
10358 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
10359 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
10360 mKernelMemoryStats.get(
10361 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
10362 mKernelMemoryStats.size()));
10363 }
10364 }
10365 }
10366
10367 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070010368 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
10369 * and we are on battery with screen off, we give more of the cpu time to those apps holding
10370 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010371 */
Sudheer Shanka671985f2017-05-19 11:33:42 -070010372 public void updateCpuTimeLocked(boolean updateCpuFreqData) {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070010373 if (mPowerProfile == null) {
10374 return;
10375 }
10376
Adam Lesinski72478f02015-06-17 15:39:43 -070010377 if (DEBUG_ENERGY_CPU) {
10378 Slog.d(TAG, "!Cpu updating!");
10379 }
10380
10381 // Holding a wakelock costs more than just using the cpu.
10382 // Currently, we assign only half the cpu time to an app that is running but
10383 // not holding a wakelock. The apps holding wakelocks get the rest of the blame.
10384 // If no app is holding a wakelock, then the distribution is normal.
10385 final int wakelockWeight = 50;
10386
Adam Lesinski72478f02015-06-17 15:39:43 -070010387 int numWakelocks = 0;
10388
10389 // Calculate how many wakelocks we have to distribute amongst. The system is excluded.
10390 // Only distribute cpu power to wakelocks if the screen is off and we're on battery.
10391 final int numPartialTimers = mPartialTimers.size();
10392 if (mOnBatteryScreenOffTimeBase.isRunning()) {
10393 for (int i = 0; i < numPartialTimers; i++) {
10394 final StopwatchTimer timer = mPartialTimers.get(i);
10395 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
10396 // Since the collection and blaming of wakelocks can be scheduled to run after
10397 // some delay, the mPartialTimers list may have new entries. We can't blame
10398 // the newly added timer for past cpu time, so we only consider timers that
10399 // were present for one round of collection. Once a timer has gone through
10400 // a round of collection, its mInList field is set to true.
10401 numWakelocks++;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010402 }
Adam Lesinski72478f02015-06-17 15:39:43 -070010403 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010404 }
Adam Lesinski72478f02015-06-17 15:39:43 -070010405
10406 final int numWakelocksF = numWakelocks;
10407 mTempTotalCpuUserTimeUs = 0;
10408 mTempTotalCpuSystemTimeUs = 0;
10409
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010410 final SparseLongArray updatedUids = new SparseLongArray();
10411
Adam Lesinski72478f02015-06-17 15:39:43 -070010412 // Read the CPU data for each UID. This will internally generate a snapshot so next time
10413 // we read, we get a delta. If we are to distribute the cpu time, then do so. Otherwise
10414 // we just ignore the data.
Amith Yamasanid0ddeba2017-05-26 09:46:58 -070010415 final long startTimeMs = mClocks.uptimeMillis();
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010416 mUserInfoProvider.refreshUserIds();
Adam Lesinski72478f02015-06-17 15:39:43 -070010417 mKernelUidCpuTimeReader.readDelta(!mOnBatteryInternal ? null :
10418 new KernelUidCpuTimeReader.Callback() {
10419 @Override
Adam Lesinskid4abd1e2017-04-12 11:29:13 -070010420 public void onUidCpuTime(int uid, long userTimeUs, long systemTimeUs) {
Sudheer Shankaea87a4b2017-06-02 16:48:13 -070010421 uid = mapUid(uid);
10422 if (Process.isIsolated(uid)) {
10423 // This could happen if the isolated uid mapping was removed before
10424 // that process was actually killed.
10425 mKernelUidCpuTimeReader.removeUid(uid);
10426 Slog.d(TAG, "Got readings for an isolated uid with"
10427 + " no mapping to owning uid: " + uid);
10428 return;
10429 }
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010430 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
10431 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
10432 mKernelUidCpuTimeReader.removeUid(uid);
10433 return;
10434 }
Sudheer Shankaea87a4b2017-06-02 16:48:13 -070010435 final Uid u = getUidStatsLocked(uid);
Adam Lesinski72478f02015-06-17 15:39:43 -070010436
10437 // Accumulate the total system and user time.
10438 mTempTotalCpuUserTimeUs += userTimeUs;
10439 mTempTotalCpuSystemTimeUs += systemTimeUs;
10440
10441 StringBuilder sb = null;
10442 if (DEBUG_ENERGY_CPU) {
10443 sb = new StringBuilder();
10444 sb.append(" got time for uid=").append(u.mUid).append(": u=");
10445 TimeUtils.formatDuration(userTimeUs / 1000, sb);
10446 sb.append(" s=");
10447 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
Adam Lesinskid4abd1e2017-04-12 11:29:13 -070010448 sb.append("\n");
Adam Lesinski72478f02015-06-17 15:39:43 -070010449 }
10450
10451 if (numWakelocksF > 0) {
10452 // We have wakelocks being held, so only give a portion of the
10453 // time to the process. The rest will be distributed among wakelock
10454 // holders.
10455 userTimeUs = (userTimeUs * wakelockWeight) / 100;
10456 systemTimeUs = (systemTimeUs * wakelockWeight) / 100;
10457 }
10458
10459 if (sb != null) {
10460 sb.append(" adding to uid=").append(u.mUid).append(": u=");
10461 TimeUtils.formatDuration(userTimeUs / 1000, sb);
10462 sb.append(" s=");
10463 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
10464 Slog.d(TAG, sb.toString());
10465 }
10466
10467 u.mUserCpuTime.addCountLocked(userTimeUs);
10468 u.mSystemCpuTime.addCountLocked(systemTimeUs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010469 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
Adam Lesinski72478f02015-06-17 15:39:43 -070010470 }
10471 });
10472
Sudheer Shanka671985f2017-05-19 11:33:42 -070010473 if (updateCpuFreqData) {
10474 readKernelUidCpuFreqTimesLocked();
10475 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010476
Amith Yamasanid0ddeba2017-05-26 09:46:58 -070010477 final long elapse = (mClocks.uptimeMillis() - startTimeMs);
Makoto Onuki3f8e2972017-05-11 10:52:37 -070010478 if (DEBUG_ENERGY_CPU || (elapse >= 100)) {
10479 Slog.d(TAG, "Reading cpu stats took " + elapse + " ms");
Adam Lesinski72478f02015-06-17 15:39:43 -070010480 }
10481
10482 if (mOnBatteryInternal && numWakelocks > 0) {
10483 // Distribute a portion of the total cpu time to wakelock holders.
10484 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - wakelockWeight)) / 100;
10485 mTempTotalCpuSystemTimeUs =
10486 (mTempTotalCpuSystemTimeUs * (100 - wakelockWeight)) / 100;
10487
10488 for (int i = 0; i < numPartialTimers; i++) {
10489 final StopwatchTimer timer = mPartialTimers.get(i);
10490
10491 // The system does not share any blame, as it is usually holding the wakelock
10492 // on behalf of an app.
10493 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
10494 int userTimeUs = (int) (mTempTotalCpuUserTimeUs / numWakelocks);
10495 int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / numWakelocks);
10496
10497 if (DEBUG_ENERGY_CPU) {
10498 StringBuilder sb = new StringBuilder();
10499 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
10500 .append(": u=");
10501 TimeUtils.formatDuration(userTimeUs / 1000, sb);
10502 sb.append(" s=");
10503 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
10504 Slog.d(TAG, sb.toString());
10505 }
10506
10507 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs);
10508 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010509 final int uid = timer.mUid.getUid();
10510 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
Adam Lesinski72478f02015-06-17 15:39:43 -070010511
10512 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
Adam Lesinski062e66c2015-07-14 12:02:44 -070010513 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000);
Adam Lesinski72478f02015-06-17 15:39:43 -070010514
10515 mTempTotalCpuUserTimeUs -= userTimeUs;
10516 mTempTotalCpuSystemTimeUs -= systemTimeUs;
10517 numWakelocks--;
10518 }
10519 }
10520
10521 if (mTempTotalCpuUserTimeUs > 0 || mTempTotalCpuSystemTimeUs > 0) {
10522 // Anything left over is given to the system.
10523 if (DEBUG_ENERGY_CPU) {
10524 StringBuilder sb = new StringBuilder();
10525 sb.append(" Distributing lost time to system: u=");
10526 TimeUtils.formatDuration(mTempTotalCpuUserTimeUs / 1000, sb);
10527 sb.append(" s=");
10528 TimeUtils.formatDuration(mTempTotalCpuSystemTimeUs / 1000, sb);
10529 Slog.d(TAG, sb.toString());
10530 }
10531
10532 final Uid u = getUidStatsLocked(Process.SYSTEM_UID);
10533 u.mUserCpuTime.addCountLocked(mTempTotalCpuUserTimeUs);
10534 u.mSystemCpuTime.addCountLocked(mTempTotalCpuSystemTimeUs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010535 updatedUids.put(Process.SYSTEM_UID, updatedUids.get(Process.SYSTEM_UID, 0)
10536 + mTempTotalCpuUserTimeUs + mTempTotalCpuSystemTimeUs);
Adam Lesinski72478f02015-06-17 15:39:43 -070010537
10538 final Uid.Proc proc = u.getProcessStatsLocked("*lost*");
Adam Lesinski062e66c2015-07-14 12:02:44 -070010539 proc.addCpuTimeLocked((int) mTempTotalCpuUserTimeUs / 1000,
10540 (int) mTempTotalCpuSystemTimeUs / 1000);
Adam Lesinski72478f02015-06-17 15:39:43 -070010541 }
10542 }
10543
Sudheer Shanka71f34b32017-07-21 00:14:24 -070010544 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010545 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shanka71f34b32017-07-21 00:14:24 -070010546 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010547 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shanka71f34b32017-07-21 00:14:24 -070010548 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
10549 if (clusterSpeedTimesMs[cluster] != null) {
10550 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
10551 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010552 }
10553 }
10554 }
Sudheer Shanka71f34b32017-07-21 00:14:24 -070010555 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010556 // We have cpu times per freq aggregated over all uids but we need the times per uid.
10557 // So, we distribute total time spent by an uid to different cpu freqs based on the
10558 // amount of time cpu was running at that freq.
10559 final int updatedUidsCount = updatedUids.size();
10560 for (int i = 0; i < updatedUidsCount; ++i) {
10561 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shanka71f34b32017-07-21 00:14:24 -070010562 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010563 // Add the cpu speeds to this UID.
10564 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka71f34b32017-07-21 00:14:24 -070010565 if (u.mCpuClusterSpeedTimesUs == null || u.mCpuClusterSpeedTimesUs.length !=
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010566 numClusters) {
Sudheer Shanka71f34b32017-07-21 00:14:24 -070010567 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010568 }
10569
Sudheer Shanka71f34b32017-07-21 00:14:24 -070010570 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
10571 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
10572 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
10573 u.mCpuClusterSpeedTimesUs[cluster].length) {
10574 u.mCpuClusterSpeedTimesUs[cluster]
10575 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010576 }
10577
Sudheer Shanka71f34b32017-07-21 00:14:24 -070010578 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010579 for (int speed = 0; speed < speedsInCluster; speed++) {
10580 if (cpuSpeeds[speed] == null) {
10581 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
10582 }
Sudheer Shanka71f34b32017-07-21 00:14:24 -070010583 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
10584 * clusterSpeedTimesMs[cluster][speed]
10585 / totalCpuClustersTimeMs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010586 }
10587 }
10588 }
10589 }
10590
Adam Lesinski72478f02015-06-17 15:39:43 -070010591 // See if there is a difference in wakelocks between this collection and the last
10592 // collection.
10593 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
10594 // No difference, so each timer is now considered for the next collection.
10595 for (int i = 0; i < numPartialTimers; i++) {
10596 mPartialTimers.get(i).mInList = true;
10597 }
10598 } else {
10599 // The lists are different, meaning we added (or removed a timer) since the last
10600 // collection.
10601 final int numLastPartialTimers = mLastPartialTimers.size();
10602 for (int i = 0; i < numLastPartialTimers; i++) {
10603 mLastPartialTimers.get(i).mInList = false;
10604 }
10605 mLastPartialTimers.clear();
10606
10607 // Mark the current timers as gone through a collection.
10608 for (int i = 0; i < numPartialTimers; i++) {
10609 final StopwatchTimer timer = mPartialTimers.get(i);
10610 timer.mInList = true;
10611 mLastPartialTimers.add(timer);
10612 }
10613 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010614 }
10615
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010616 void readKernelUidCpuFreqTimesLocked() {
10617 mKernelUidCpuFreqTimeReader.readDelta(!mOnBatteryInternal ? null :
10618 new KernelUidCpuFreqTimeReader.Callback() {
10619 @Override
10620 public void onCpuFreqs(long[] cpuFreqs) {
10621 mCpuFreqs = cpuFreqs;
10622 }
10623
10624 @Override
10625 public void onUidCpuFreqTime(int uid, long[] cpuFreqTimeMs) {
Sudheer Shankaea87a4b2017-06-02 16:48:13 -070010626 uid = mapUid(uid);
10627 if (Process.isIsolated(uid)) {
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -070010628 mKernelUidCpuFreqTimeReader.removeUid(uid);
10629 Slog.d(TAG, "Got freq readings for an isolated uid with"
10630 + " no mapping to owning uid: " + uid);
Sudheer Shankaea87a4b2017-06-02 16:48:13 -070010631 return;
10632 }
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010633 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
10634 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
10635 mKernelUidCpuFreqTimeReader.removeUid(uid);
10636 return;
10637 }
Sudheer Shankaea87a4b2017-06-02 16:48:13 -070010638 final Uid u = getUidStatsLocked(uid);
Sudheer Shankaa87245d2017-08-10 12:02:31 -070010639 if (u.mCpuFreqTimeMs == null
10640 || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010641 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
10642 }
10643 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
Sudheer Shankaa87245d2017-08-10 12:02:31 -070010644 if (u.mScreenOffCpuFreqTimeMs == null
10645 || u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010646 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
10647 mOnBatteryScreenOffTimeBase);
10648 }
10649 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
10650 }
10651 });
10652 }
10653
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010654 boolean setChargingLocked(boolean charging) {
10655 if (mCharging != charging) {
10656 mCharging = charging;
10657 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070010658 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010659 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070010660 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010661 }
10662 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
10663 return true;
10664 }
10665 return false;
10666 }
10667
Dianne Hackborn40c87252014-03-19 16:55:40 -070010668 void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime, final boolean onBattery,
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010669 final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010670 boolean doWrite = false;
10671 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
10672 m.arg1 = onBattery ? 1 : 0;
10673 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010674
Dianne Hackborn40c87252014-03-19 16:55:40 -070010675 final long uptime = mSecUptime * 1000;
10676 final long realtime = mSecRealtime * 1000;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010677 final boolean screenOn = mScreenState == Display.STATE_ON;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010678 if (onBattery) {
10679 // We will reset our status if we are unplugging after the
10680 // battery was last full, or the level is at 100, or
10681 // we have gone through a significant charge (from a very low
10682 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010683 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070010684 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010685 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070010686 || (mDischargeCurrentLevel < 20 && level >= 80)
10687 || (getHighDischargeAmountSinceCharge() >= 200
10688 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070010689 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070010690 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070010691 + " lowAmount=" + getLowDischargeAmountSinceCharge()
10692 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010693 // Before we write, collect a snapshot of the final aggregated
10694 // stats to be reported in the next checkin. Only do this if we have
10695 // a sufficient amount of data to make it interesting.
10696 if (getLowDischargeAmountSinceCharge() >= 20) {
10697 final Parcel parcel = Parcel.obtain();
10698 writeSummaryToParcel(parcel, true);
10699 BackgroundThread.getHandler().post(new Runnable() {
10700 @Override public void run() {
10701 synchronized (mCheckinFile) {
10702 FileOutputStream stream = null;
10703 try {
10704 stream = mCheckinFile.startWrite();
10705 stream.write(parcel.marshall());
10706 stream.flush();
10707 FileUtils.sync(stream);
10708 stream.close();
10709 mCheckinFile.finishWrite(stream);
10710 } catch (IOException e) {
10711 Slog.w("BatteryStats",
10712 "Error writing checkin battery statistics", e);
10713 mCheckinFile.failWrite(stream);
10714 } finally {
10715 parcel.recycle();
10716 }
10717 }
10718 }
10719 });
10720 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010721 doWrite = true;
10722 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080010723 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010724 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080010725 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010726 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010727 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010728 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010729 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010730 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010731 if (mCharging) {
10732 setChargingLocked(false);
10733 }
10734 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010735 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070010736 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070010737 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010738 mDischargeStepTracker.clearTime();
10739 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010740 mInitStepMode = mCurStepMode;
10741 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010742 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010743 mHistoryCur.batteryLevel = (byte)level;
10744 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
10745 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
10746 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010747 if (reset) {
10748 mRecordingHistory = true;
10749 startRecordingHistory(mSecRealtime, mSecUptime, reset);
10750 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010751 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010752 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010753 if (screenOn) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010754 mDischargeScreenOnUnplugLevel = level;
10755 mDischargeScreenOffUnplugLevel = 0;
10756 } else {
10757 mDischargeScreenOnUnplugLevel = 0;
10758 mDischargeScreenOffUnplugLevel = level;
10759 }
10760 mDischargeAmountScreenOn = 0;
10761 mDischargeAmountScreenOff = 0;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010762 updateTimeBasesLocked(true, !screenOn, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010763 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010764 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010765 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010766 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010767 mHistoryCur.batteryLevel = (byte)level;
10768 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
10769 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
10770 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070010771 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010772 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010773 if (level < mDischargeUnplugLevel) {
10774 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
10775 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
10776 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070010777 updateDischargeScreenLevelsLocked(screenOn, screenOn);
10778 updateTimeBasesLocked(false, !screenOn, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010779 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070010780 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070010781 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010782 mInitStepMode = mCurStepMode;
10783 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010784 }
10785 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
10786 if (mFile != null) {
10787 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010788 }
10789 }
10790 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010791
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010792 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
10793 boolean reset) {
10794 mRecordingHistory = true;
10795 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn37de0982014-05-09 09:32:18 -070010796 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs,
10797 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010798 mHistoryCur);
10799 mHistoryCur.currentTime = 0;
10800 if (reset) {
10801 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
10802 }
10803 }
10804
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070010805 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
10806 final long uptimeMs) {
10807 if (mRecordingHistory) {
10808 mHistoryCur.currentTime = currentTime;
10809 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_CURRENT_TIME,
10810 mHistoryCur);
10811 mHistoryCur.currentTime = 0;
10812 }
10813 }
10814
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080010815 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
10816 if (mRecordingHistory) {
10817 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080010818 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_SHUTDOWN,
10819 mHistoryCur);
10820 mHistoryCur.currentTime = 0;
10821 }
10822 }
10823
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010824 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010825 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010826 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010827 }
10828 }
10829
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010830 // This should probably be exposed in the API, though it's not critical
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010831 public static final int BATTERY_PLUGGED_NONE = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010832
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010833 public void setBatteryStateLocked(int status, int health, int plugType, int level,
Adam Lesinski041d9172016-12-12 12:03:56 -080010834 int temp, int volt, int chargeUAh, int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070010835 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
10836 temp = Math.max(0, temp);
10837
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010838 final boolean onBattery = plugType == BATTERY_PLUGGED_NONE;
Joe Onoratoabded112016-02-08 16:49:39 -080010839 final long uptime = mClocks.uptimeMillis();
10840 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010841 if (!mHaveBatteryLevel) {
10842 mHaveBatteryLevel = true;
10843 // We start out assuming that the device is plugged in (not
10844 // on battery). If our first report is now that we are indeed
10845 // plugged in, then twiddle our state to correctly reflect that
10846 // since we won't be going through the full setOnBattery().
10847 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070010848 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010849 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070010850 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010851 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070010852 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010853 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010854 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070010855 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010856 mHistoryCur.batteryStatus = (byte)status;
10857 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010858 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010859 mMaxChargeStepLevel = mMinDischargeStepLevel =
10860 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010861 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010862 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
10863 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
10864 }
10865 int oldStatus = mHistoryCur.batteryStatus;
10866 if (onBattery) {
10867 mDischargeCurrentLevel = level;
10868 if (!mRecordingHistory) {
10869 mRecordingHistory = true;
10870 startRecordingHistory(elapsedRealtime, uptime, true);
10871 }
10872 } else if (level < 96) {
10873 if (!mRecordingHistory) {
10874 mRecordingHistory = true;
10875 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010876 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010877 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010878 mCurrentBatteryLevel = level;
10879 if (mDischargePlugLevel < 0) {
10880 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070010881 }
Adam Lesinski926969b2016-04-28 17:31:12 -070010882
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010883 if (onBattery != mOnBattery) {
10884 mHistoryCur.batteryLevel = (byte)level;
10885 mHistoryCur.batteryStatus = (byte)status;
10886 mHistoryCur.batteryHealth = (byte)health;
10887 mHistoryCur.batteryPlugType = (byte)plugType;
10888 mHistoryCur.batteryTemperature = (short)temp;
10889 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010890 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
10891 // Only record discharges
10892 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
10893 mDischargeCounter.addCountLocked(chargeDiff);
10894 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
10895 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070010896 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010897 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010898 } else {
10899 boolean changed = false;
10900 if (mHistoryCur.batteryLevel != level) {
10901 mHistoryCur.batteryLevel = (byte)level;
10902 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070010903
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010904 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
10905 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010906 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070010907 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010908 if (mHistoryCur.batteryStatus != status) {
10909 mHistoryCur.batteryStatus = (byte)status;
10910 changed = true;
10911 }
10912 if (mHistoryCur.batteryHealth != health) {
10913 mHistoryCur.batteryHealth = (byte)health;
10914 changed = true;
10915 }
10916 if (mHistoryCur.batteryPlugType != plugType) {
10917 mHistoryCur.batteryPlugType = (byte)plugType;
10918 changed = true;
10919 }
10920 if (temp >= (mHistoryCur.batteryTemperature+10)
10921 || temp <= (mHistoryCur.batteryTemperature-10)) {
10922 mHistoryCur.batteryTemperature = (short)temp;
10923 changed = true;
10924 }
10925 if (volt > (mHistoryCur.batteryVoltage+20)
10926 || volt < (mHistoryCur.batteryVoltage-20)) {
10927 mHistoryCur.batteryVoltage = (char)volt;
10928 changed = true;
10929 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070010930 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
10931 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010932 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
10933 // Only record discharges
10934 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
10935 mDischargeCounter.addCountLocked(chargeDiff);
10936 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
10937 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070010938 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070010939 changed = true;
10940 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010941 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
10942 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
10943 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
10944 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010945 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010946 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
10947 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
10948 modeBits, elapsedRealtime);
10949 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
10950 modeBits, elapsedRealtime);
10951 mLastDischargeStepLevel = level;
10952 mMinDischargeStepLevel = level;
10953 mInitStepMode = mCurStepMode;
10954 mModStepMode = 0;
10955 }
10956 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010957 if (level >= 90) {
10958 // If the battery level is at least 90%, always consider the device to be
10959 // charging even if it happens to go down a level.
10960 changed |= setChargingLocked(true);
10961 mLastChargeStepLevel = level;
10962 } if (!mCharging) {
10963 if (mLastChargeStepLevel < level) {
10964 // We have not reporting that we are charging, but the level has now
10965 // gone up, so consider the state to be charging.
10966 changed |= setChargingLocked(true);
10967 mLastChargeStepLevel = level;
10968 }
10969 } else {
10970 if (mLastChargeStepLevel > level) {
10971 // We had reported that the device was charging, but here we are with
10972 // power connected and the level going down. Looks like the current
10973 // power supplied isn't enough, so consider the device to now be
10974 // discharging.
10975 changed |= setChargingLocked(false);
10976 mLastChargeStepLevel = level;
10977 }
10978 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010979 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
10980 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
10981 modeBits, elapsedRealtime);
10982 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
10983 modeBits, elapsedRealtime);
10984 mLastChargeStepLevel = level;
10985 mMaxChargeStepLevel = level;
10986 mInitStepMode = mCurStepMode;
10987 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070010988 }
10989 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010990 if (changed) {
10991 addHistoryRecordLocked(elapsedRealtime, uptime);
10992 }
Evan Millarc64edde2009-04-18 12:26:32 -070010993 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010994 if (!onBattery && status == BatteryManager.BATTERY_STATUS_FULL) {
10995 // We don't record history while we are plugged in and fully charged.
10996 // The next time we are unplugged, history will be cleared.
10997 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080010998 }
Adam Lesinski041d9172016-12-12 12:03:56 -080010999
Jocelyn Dangc627d102017-04-14 13:15:14 -070011000 if (mMinLearnedBatteryCapacity == -1) {
11001 mMinLearnedBatteryCapacity = chargeFullUAh;
11002 } else {
11003 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080011004 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070011005 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070011006 }
11007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011008 public long getAwakeTimeBattery() {
11009 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
11010 }
11011
11012 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080011013 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011014 }
11015
11016 @Override
11017 public long computeUptime(long curTime, int which) {
11018 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011019 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011020 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070011021 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011022 }
11023 return 0;
11024 }
11025
11026 @Override
11027 public long computeRealtime(long curTime, int which) {
11028 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011029 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011030 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070011031 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011032 }
11033 return 0;
11034 }
11035
11036 @Override
11037 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011038 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039 }
11040
11041 @Override
11042 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011043 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011044 }
11045
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011046 @Override
11047 public long computeBatteryScreenOffUptime(long curTime, int which) {
11048 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
11049 }
11050
11051 @Override
11052 public long computeBatteryScreenOffRealtime(long curTime, int which) {
11053 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011054 }
11055
Dianne Hackborn260c5022014-04-29 11:23:16 -070011056 private long computeTimePerLevel(long[] steps, int numSteps) {
11057 // For now we'll do a simple average across all steps.
11058 if (numSteps <= 0) {
11059 return -1;
11060 }
11061 long total = 0;
11062 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011063 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011064 }
11065 return total / numSteps;
11066 /*
11067 long[] buckets = new long[numSteps];
11068 int numBuckets = 0;
11069 int numToAverage = 4;
11070 int i = 0;
11071 while (i < numSteps) {
11072 long totalTime = 0;
11073 int num = 0;
11074 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011075 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011076 num++;
11077 }
11078 buckets[numBuckets] = totalTime / num;
11079 numBuckets++;
11080 numToAverage *= 2;
11081 i += num;
11082 }
11083 if (numBuckets < 1) {
11084 return -1;
11085 }
11086 long averageTime = buckets[numBuckets-1];
11087 for (i=numBuckets-2; i>=0; i--) {
11088 averageTime = (averageTime + buckets[i]) / 2;
11089 }
11090 return averageTime;
11091 */
11092 }
11093
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011094 @Override
11095 public long computeBatteryTimeRemaining(long curTime) {
11096 if (!mOnBattery) {
11097 return -1;
11098 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070011099 /* Simple implementation just looks at the average discharge per level across the
11100 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011101 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
11102 if (discharge < 2) {
11103 return -1;
11104 }
11105 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
11106 if (duration < 1000*1000) {
11107 return -1;
11108 }
11109 long usPerLevel = duration/discharge;
11110 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011111 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011112 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070011113 return -1;
11114 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011115 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070011116 if (msPerLevel <= 0) {
11117 return -1;
11118 }
11119 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011120 }
11121
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011122 @Override
11123 public LevelStepTracker getDischargeLevelStepTracker() {
11124 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070011125 }
11126
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011127 @Override
11128 public LevelStepTracker getDailyDischargeLevelStepTracker() {
11129 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070011130 }
11131
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011132 @Override
11133 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070011134 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011135 // Not yet working.
11136 return -1;
11137 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070011138 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011139 int curLevel = mCurrentBatteryLevel;
11140 int plugLevel = mDischargePlugLevel;
11141 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
11142 return -1;
11143 }
11144 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
11145 if (duration < 1000*1000) {
11146 return -1;
11147 }
11148 long usPerLevel = duration/(curLevel-plugLevel);
11149 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070011150 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011151 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070011152 return -1;
11153 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011154 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070011155 if (msPerLevel <= 0) {
11156 return -1;
11157 }
11158 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011159 }
11160
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011161 @Override
11162 public LevelStepTracker getChargeLevelStepTracker() {
11163 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070011164 }
11165
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011166 @Override
11167 public LevelStepTracker getDailyChargeLevelStepTracker() {
11168 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070011169 }
11170
Dianne Hackborn88e98df2015-03-23 13:29:14 -070011171 @Override
11172 public ArrayList<PackageChange> getDailyPackageChanges() {
11173 return mDailyPackageChanges;
11174 }
11175
Joe Onoratoe1acd632016-02-23 13:25:10 -080011176 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080011177 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011178 }
11179
11180 @Override
11181 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011182 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011183 }
11184
11185 @Override
11186 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011187 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011188 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070011189
The Android Open Source Project10592532009-03-18 17:39:46 -070011190 @Override
Evan Millar633a1742009-04-02 16:36:33 -070011191 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011192 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070011193 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070011194 }
11195 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011196
Evan Millar633a1742009-04-02 16:36:33 -070011197 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011198 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070011199 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011200
The Android Open Source Project10592532009-03-18 17:39:46 -070011201 @Override
Evan Millar633a1742009-04-02 16:36:33 -070011202 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011203 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070011204 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070011205 }
11206 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011207
Evan Millar633a1742009-04-02 16:36:33 -070011208 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080011209 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070011210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211
Amith Yamasanie43530a2009-08-21 13:11:37 -070011212 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011213 public int getLowDischargeAmountSinceCharge() {
11214 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080011215 int val = mLowDischargeAmountSinceCharge;
11216 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
11217 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
11218 }
11219 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011220 }
11221 }
11222
11223 @Override
11224 public int getHighDischargeAmountSinceCharge() {
11225 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080011226 int val = mHighDischargeAmountSinceCharge;
11227 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
11228 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
11229 }
11230 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011231 }
11232 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070011233
11234 @Override
11235 public int getDischargeAmount(int which) {
11236 int dischargeAmount = which == STATS_SINCE_CHARGED
11237 ? getHighDischargeAmountSinceCharge()
11238 : (getDischargeStartLevel() - getDischargeCurrentLevel());
11239 if (dischargeAmount < 0) {
11240 dischargeAmount = 0;
11241 }
11242 return dischargeAmount;
11243 }
11244
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011245 public int getDischargeAmountScreenOn() {
11246 synchronized(this) {
11247 int val = mDischargeAmountScreenOn;
Jeff Browne95c3cd2014-05-02 16:59:26 -070011248 if (mOnBattery && mScreenState == Display.STATE_ON
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011249 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
11250 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
11251 }
11252 return val;
11253 }
11254 }
11255
11256 public int getDischargeAmountScreenOnSinceCharge() {
11257 synchronized(this) {
11258 int val = mDischargeAmountScreenOnSinceCharge;
Jeff Browne95c3cd2014-05-02 16:59:26 -070011259 if (mOnBattery && mScreenState == Display.STATE_ON
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011260 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
11261 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
11262 }
11263 return val;
11264 }
11265 }
11266
11267 public int getDischargeAmountScreenOff() {
11268 synchronized(this) {
11269 int val = mDischargeAmountScreenOff;
Jeff Browne95c3cd2014-05-02 16:59:26 -070011270 if (mOnBattery && mScreenState != Display.STATE_ON
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011271 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
11272 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
11273 }
11274 return val;
11275 }
11276 }
11277
11278 public int getDischargeAmountScreenOffSinceCharge() {
11279 synchronized(this) {
11280 int val = mDischargeAmountScreenOffSinceCharge;
Jeff Browne95c3cd2014-05-02 16:59:26 -070011281 if (mOnBattery && mScreenState != Display.STATE_ON
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011282 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
11283 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
11284 }
11285 return val;
11286 }
11287 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011289 /**
11290 * Retrieve the statistics object for a particular uid, creating if needed.
11291 */
11292 public Uid getUidStatsLocked(int uid) {
11293 Uid u = mUidStats.get(uid);
11294 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080011295 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011296 mUidStats.put(uid, u);
11297 }
11298 return u;
11299 }
11300
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011301 public void onCleanupUserLocked(int userId) {
11302 final int firstUidForUser = UserHandle.getUid(userId, 0);
11303 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
11304 mKernelUidCpuFreqTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
11305 mKernelUidCpuTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
11306 }
11307
11308 public void onUserRemovedLocked(int userId) {
11309 final int firstUidForUser = UserHandle.getUid(userId, 0);
11310 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
11311 mUidStats.put(firstUidForUser, null);
11312 mUidStats.put(lastUidForUser, null);
11313 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
11314 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
11315 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
11316 }
11317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011318 /**
11319 * Remove the statistics object for a particular uid.
11320 */
11321 public void removeUidStatsLocked(int uid) {
Adam Lesinskib83ffee2015-05-12 14:43:47 -070011322 mKernelUidCpuTimeReader.removeUid(uid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -070011323 mKernelUidCpuFreqTimeReader.removeUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011324 mUidStats.remove(uid);
11325 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070011326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011327 /**
11328 * Retrieve the statistics object for a particular process, creating
11329 * if needed.
11330 */
11331 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070011332 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 Uid u = getUidStatsLocked(uid);
11334 return u.getProcessStatsLocked(name);
11335 }
11336
11337 /**
11338 * Retrieve the statistics object for a particular process, creating
11339 * if needed.
11340 */
11341 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070011342 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011343 Uid u = getUidStatsLocked(uid);
11344 return u.getPackageStatsLocked(pkg);
11345 }
11346
11347 /**
11348 * Retrieve the statistics object for a particular service, creating
11349 * if needed.
11350 */
11351 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070011352 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011353 Uid u = getUidStatsLocked(uid);
11354 return u.getServiceStatsLocked(pkg, name);
11355 }
11356
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011357 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080011358 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011359 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011360 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011361 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011362
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011363 Parcel mPendingWrite = null;
11364 final ReentrantLock mWriteLock = new ReentrantLock();
11365
11366 public void writeAsyncLocked() {
11367 writeLocked(false);
11368 }
11369
11370 public void writeSyncLocked() {
11371 writeLocked(true);
11372 }
11373
11374 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011375 if (mFile == null) {
11376 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011377 return;
11378 }
11379
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011380 if (mShuttingDown) {
11381 return;
11382 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011383
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011384 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011385 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080011386 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011387
11388 if (mPendingWrite != null) {
11389 mPendingWrite.recycle();
11390 }
11391 mPendingWrite = out;
11392
11393 if (sync) {
11394 commitPendingDataToDisk();
11395 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011396 BackgroundThread.getHandler().post(new Runnable() {
11397 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011398 commitPendingDataToDisk();
11399 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011400 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011401 }
11402 }
11403
11404 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070011405 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011406 synchronized (this) {
11407 next = mPendingWrite;
11408 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070011409 if (next == null) {
11410 return;
11411 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011412 }
11413
Amith Yamasanid2450862017-02-07 15:58:24 -080011414 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011415 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011416 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011417 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070011419 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011420 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011421 mFile.commit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011422 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011423 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011424 mFile.rollback();
11425 } finally {
11426 next.recycle();
11427 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070011428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011429 }
11430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011431 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011432 if (mDailyFile != null) {
11433 readDailyStatsLocked();
11434 }
11435
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011436 if (mFile == null) {
11437 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011438 return;
11439 }
11440
11441 mUidStats.clear();
11442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011443 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011444 File file = mFile.chooseForRead();
11445 if (!file.exists()) {
11446 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011447 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011448 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011450 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011451 Parcel in = Parcel.obtain();
11452 in.unmarshall(raw, 0, raw.length);
11453 in.setDataPosition(0);
11454 stream.close();
11455
11456 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080011457 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011458 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011459 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011460 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011461
Dianne Hackborncd0e3352014-08-07 17:08:09 -070011462 mEndPlatformVersion = Build.ID;
11463
Dianne Hackborne5167ca2014-03-08 14:39:10 -080011464 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011465 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080011466 final long elapsedRealtime = mClocks.elapsedRealtime();
11467 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080011468 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011469 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080011470 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011471 addHistoryBufferLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
11472 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070011473 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011474
11475 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011476 }
11477
11478 public int describeContents() {
11479 return 0;
11480 }
11481
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011482 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070011483 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011484
11485 mHistoryBuffer.setDataSize(0);
11486 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011487 mHistoryTagPool.clear();
11488 mNextHistoryTagIdx = 0;
11489 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080011490
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011491 int numTags = in.readInt();
11492 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080011493 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011494 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011495 if (str == null) {
11496 throw new ParcelFormatException("null history tag string");
11497 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011498 int uid = in.readInt();
11499 HistoryTag tag = new HistoryTag();
11500 tag.string = str;
11501 tag.uid = uid;
11502 tag.poolIdx = idx;
11503 mHistoryTagPool.put(tag, idx);
11504 if (idx >= mNextHistoryTagIdx) {
11505 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080011506 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011507 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080011508 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011509
11510 int bufSize = in.readInt();
11511 int curPos = in.dataPosition();
11512 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011513 throw new ParcelFormatException("File corrupt: history data buffer too large " +
11514 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011515 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011516 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
11517 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011518 } else {
11519 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
11520 + " bytes at " + curPos);
11521 mHistoryBuffer.appendFrom(in, curPos, bufSize);
11522 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011523 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011524
Dianne Hackbornae384452011-06-28 12:33:48 -070011525 if (andOldHistory) {
11526 readOldHistory(in);
11527 }
11528
11529 if (DEBUG_HISTORY) {
11530 StringBuilder sb = new StringBuilder(128);
11531 sb.append("****************** OLD mHistoryBaseTime: ");
11532 TimeUtils.formatDuration(mHistoryBaseTime, sb);
11533 Slog.i(TAG, sb.toString());
11534 }
11535 mHistoryBaseTime = historyBaseTime;
11536 if (DEBUG_HISTORY) {
11537 StringBuilder sb = new StringBuilder(128);
11538 sb.append("****************** NEW mHistoryBaseTime: ");
11539 TimeUtils.formatDuration(mHistoryBaseTime, sb);
11540 Slog.i(TAG, sb.toString());
11541 }
11542
11543 // We are just arbitrarily going to insert 1 minute from the sample of
11544 // the last run until samples in this run.
11545 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080011546 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011547 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070011548 if (DEBUG_HISTORY) {
11549 StringBuilder sb = new StringBuilder(128);
11550 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
11551 TimeUtils.formatDuration(mHistoryBaseTime, sb);
11552 Slog.i(TAG, sb.toString());
11553 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070011554 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011555 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011556
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011557 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070011558 if (!USE_OLD_HISTORY) {
11559 return;
11560 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011561 mHistory = mHistoryEnd = mHistoryCache = null;
11562 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070011563 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011564 HistoryItem rec = new HistoryItem(time, in);
11565 addHistoryRecordLocked(rec);
11566 }
11567 }
11568
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011569 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070011570 if (DEBUG_HISTORY) {
11571 StringBuilder sb = new StringBuilder(128);
11572 sb.append("****************** WRITING mHistoryBaseTime: ");
11573 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070011574 sb.append(" mLastHistoryElapsedRealtime: ");
11575 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070011576 Slog.i(TAG, sb.toString());
11577 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070011578 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011579 if (!inclData) {
11580 out.writeInt(0);
11581 out.writeInt(0);
11582 return;
11583 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011584 out.writeInt(mHistoryTagPool.size());
11585 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
11586 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080011587 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011588 out.writeString(tag.string);
11589 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080011590 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011591 out.writeInt(mHistoryBuffer.dataSize());
11592 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
11593 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
11594 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070011595
11596 if (andOldHistory) {
11597 writeOldHistory(out);
11598 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011599 }
11600
11601 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070011602 if (!USE_OLD_HISTORY) {
11603 return;
11604 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011605 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011606 while (rec != null) {
11607 if (rec.time >= 0) rec.writeToParcel(out, 0);
11608 rec = rec.next;
11609 }
11610 out.writeLong(-1);
11611 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011612
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011613 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011614 final int version = in.readInt();
11615 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011616 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011617 + ", expected " + VERSION + "; erasing old stats");
11618 return;
11619 }
11620
Dianne Hackbornae384452011-06-28 12:33:48 -070011621 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011623 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011624 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011625 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080011626 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070011627 mStartPlatformVersion = in.readString();
11628 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011629 mOnBatteryTimeBase.readSummaryFromParcel(in);
11630 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011631 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011632 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070011633 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011634 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070011635 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070011636 mMinLearnedBatteryCapacity = in.readInt();
11637 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011638 mLowDischargeAmountSinceCharge = in.readInt();
11639 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011640 mDischargeAmountScreenOnSinceCharge = in.readInt();
11641 mDischargeAmountScreenOffSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011642 mDischargeStepTracker.readFromParcel(in);
11643 mChargeStepTracker.readFromParcel(in);
11644 mDailyDischargeStepTracker.readFromParcel(in);
11645 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070011646 mDischargeCounter.readSummaryFromParcelLocked(in);
11647 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070011648 int NPKG = in.readInt();
11649 if (NPKG > 0) {
11650 mDailyPackageChanges = new ArrayList<>(NPKG);
11651 while (NPKG > 0) {
11652 NPKG--;
11653 PackageChange pc = new PackageChange();
11654 pc.mPackageName = in.readString();
11655 pc.mUpdate = in.readInt() != 0;
11656 pc.mVersionCode = in.readInt();
11657 mDailyPackageChanges.add(pc);
11658 }
11659 } else {
11660 mDailyPackageChanges = null;
11661 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011662 mDailyStartTime = in.readLong();
11663 mNextMinDailyDeadline = in.readLong();
11664 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011666 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011667
Jeff Browne95c3cd2014-05-02 16:59:26 -070011668 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011669 mScreenOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070011670 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
11671 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
11672 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070011673 mInteractive = false;
11674 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011675 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070011676 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070011677 mLongestLightIdleTime = in.readLong();
11678 mLongestFullIdleTime = in.readLong();
11679 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
11680 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
11681 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070011682 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011683 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080011684 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070011685 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
11686 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070011687 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070011688 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
11689 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
11690 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011691 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080011692 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
11693 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011694 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011695 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080011696 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011697 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011698 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080011699 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
11700 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070011701 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070011702 mWifiOn = false;
11703 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070011704 mGlobalWifiRunning = false;
11705 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080011706 for (int i=0; i<NUM_WIFI_STATES; i++) {
11707 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
11708 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070011709 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
11710 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
11711 }
11712 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
11713 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
11714 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011715 mWifiActivity.readSummaryFromParcel(in);
11716 mBluetoothActivity.readSummaryFromParcel(in);
11717 mModemActivity.readSummaryFromParcel(in);
11718 mHasWifiReporting = in.readInt() != 0;
11719 mHasBluetoothReporting = in.readInt() != 0;
11720 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070011721
Dianne Hackborn1e01d162014-12-04 17:46:42 -080011722 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011723 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070011724 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011725 mCameraOnNesting = 0;
11726 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011727 mBluetoothScanNesting = 0;
11728 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011729
Bookatz50df7112017-08-04 14:53:26 -070011730 int NRPMS = in.readInt();
11731 if (NRPMS > 10000) {
11732 throw new ParcelFormatException("File corrupt: too many rpm stats " + NRPMS);
11733 }
11734 for (int irpm = 0; irpm < NRPMS; irpm++) {
11735 if (in.readInt() != 0) {
11736 String rpmName = in.readString();
11737 getRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
11738 }
11739 }
11740 int NSORPMS = in.readInt();
11741 if (NSORPMS > 10000) {
11742 throw new ParcelFormatException("File corrupt: too many screen-off rpm stats " + NSORPMS);
11743 }
11744 for (int irpm = 0; irpm < NSORPMS; irpm++) {
11745 if (in.readInt() != 0) {
11746 String rpmName = in.readString();
11747 getScreenOffRpmTimerLocked(rpmName).readSummaryFromParcelLocked(in);
11748 }
11749 }
11750
Evan Millarc64edde2009-04-18 12:26:32 -070011751 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011752 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011753 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011754 }
Evan Millarc64edde2009-04-18 12:26:32 -070011755 for (int ikw = 0; ikw < NKW; ikw++) {
11756 if (in.readInt() != 0) {
11757 String kwltName = in.readString();
11758 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
11759 }
11760 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070011761
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011762 int NWR = in.readInt();
11763 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011764 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011765 }
11766 for (int iwr = 0; iwr < NWR; iwr++) {
11767 if (in.readInt() != 0) {
11768 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070011769 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011770 }
11771 }
11772
James Carr3a226052016-07-01 14:49:52 -070011773 int NMS = in.readInt();
11774 for (int ims = 0; ims < NMS; ims++) {
11775 if (in.readInt() != 0) {
11776 long kmstName = in.readLong();
11777 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
11778 }
11779 }
11780
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011781 mCpuFreqs = in.createLongArray();
11782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011783 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011784 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011785 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011787 for (int iu = 0; iu < NU; iu++) {
11788 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080011789 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011790 mUidStats.put(uid, u);
11791
Bookatz867c0d72017-03-07 18:23:42 -080011792 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070011793 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080011794
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070011795 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011796 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070011797 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011798 }
The Android Open Source Project10592532009-03-18 17:39:46 -070011799 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011800 if (in.readInt() != 0) {
11801 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
11802 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070011803 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011804 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070011805 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011806 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070011807 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
11808 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
11809 if (in.readInt() != 0) {
11810 u.makeWifiBatchedScanBin(i, null);
11811 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
11812 }
11813 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070011814 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011815 if (in.readInt() != 0) {
11816 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
11817 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011818 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080011819 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011820 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011821 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080011822 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
11823 }
11824 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011825 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
11826 }
11827 if (in.readInt() != 0) {
11828 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
11829 }
11830 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070011831 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
11832 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011833 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070011834 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
11835 }
11836 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070011837 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
11838 }
11839 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011840 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
11841 }
Bookatz956f36bf2017-04-28 09:48:17 -070011842 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070011843 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
11844 }
11845 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070011846 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
11847 }
Bookatzb1f04f32017-05-19 13:57:32 -070011848 if (in.readInt() != 0) {
11849 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
11850 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080011851 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070011852 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
11853 if (in.readInt() != 0) {
11854 u.makeProcessState(i, null);
11855 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
11856 }
11857 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070011858 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080011859 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011860 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070011861
Dianne Hackborn617f8772009-03-31 15:04:46 -070011862 if (in.readInt() != 0) {
11863 if (u.mUserActivityCounters == null) {
11864 u.initUserActivityLocked();
11865 }
11866 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
11867 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
11868 }
11869 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011870
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011871 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080011872 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011873 u.initNetworkActivityLocked();
11874 }
11875 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080011876 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
11877 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011878 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080011879 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
11880 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011881 }
11882
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011883 u.mUserCpuTime.readSummaryFromParcelLocked(in);
11884 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
11885
Adam Lesinski6832f392015-09-05 18:05:40 -070011886 if (in.readInt() != 0) {
11887 final int numClusters = in.readInt();
11888 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
11889 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011890 }
Adam Lesinski6832f392015-09-05 18:05:40 -070011891
Sudheer Shanka71f34b32017-07-21 00:14:24 -070011892 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070011893 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070011894 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070011895 final int NSB = in.readInt();
11896 if (mPowerProfile != null &&
11897 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
11898 throw new ParcelFormatException("File corrupt: too many speed bins " +
11899 NSB);
11900 }
11901
Sudheer Shanka71f34b32017-07-21 00:14:24 -070011902 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070011903 for (int speed = 0; speed < NSB; speed++) {
11904 if (in.readInt() != 0) {
Sudheer Shanka71f34b32017-07-21 00:14:24 -070011905 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070011906 mOnBatteryTimeBase);
Sudheer Shanka71f34b32017-07-21 00:14:24 -070011907 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070011908 }
11909 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070011910 } else {
Sudheer Shanka71f34b32017-07-21 00:14:24 -070011911 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070011912 }
11913 }
11914 } else {
Sudheer Shanka71f34b32017-07-21 00:14:24 -070011915 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011916 }
11917
Sudheer Shanka59f5c002017-05-15 10:57:15 -070011918 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
11919 in, mOnBatteryTimeBase);
11920 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
11921 in, mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011922
11923 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070011924 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
11925 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
11926 } else {
11927 u.mMobileRadioApWakeupCount = null;
11928 }
11929
11930 if (in.readInt() != 0) {
11931 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
11932 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
11933 } else {
11934 u.mWifiRadioApWakeupCount = null;
11935 }
11936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011937 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070011938 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011939 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011941 for (int iw = 0; iw < NW; iw++) {
11942 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070011943 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011944 }
11945
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011946 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070011947 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011948 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011949 }
11950 for (int is = 0; is < NS; is++) {
11951 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070011952 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011953 }
11954
11955 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070011956 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011957 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011958 }
11959 for (int ij = 0; ij < NJ; ij++) {
11960 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070011961 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011962 }
11963
Dianne Hackborn94326cb2017-06-28 16:17:20 -070011964 u.readJobCompletionsFromParcelLocked(in);
11965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011966 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080011967 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011968 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011970 for (int is = 0; is < NP; is++) {
11971 int seNumber = in.readInt();
11972 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080011973 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011974 }
11975 }
11976
11977 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080011978 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011979 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011981 for (int ip = 0; ip < NP; ip++) {
11982 String procName = in.readString();
11983 Uid.Proc p = u.getProcessStatsLocked(procName);
11984 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011985 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070011986 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011987 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080011988 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
11989 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011990 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011991 }
11992
11993 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011994 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011995 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011997 for (int ip = 0; ip < NP; ip++) {
11998 String pkgName = in.readString();
11999 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070012000 final int NWA = in.readInt();
12001 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012002 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070012003 }
12004 p.mWakeupAlarms.clear();
12005 for (int iwa=0; iwa<NWA; iwa++) {
12006 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070012007 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070012008 c.readSummaryFromParcelLocked(in);
12009 p.mWakeupAlarms.put(tag, c);
12010 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012011 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080012012 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070012013 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080012014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012015 for (int is = 0; is < NS; is++) {
12016 String servName = in.readString();
12017 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
12018 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012019 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012020 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012021 }
12022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012023 }
12024 }
12025
12026 /**
12027 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
12028 * disk. This format does not allow a lossless round-trip.
12029 *
12030 * @param out the Parcel to be written to.
12031 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012032 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080012033 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012034
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012035 // Pull the clock time. This may update the time and make a new history entry
12036 // if we had originally pulled a time before the RTC was set.
12037 long startClockTime = getStartClockTime();
12038
Joe Onoratoabded112016-02-08 16:49:39 -080012039 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
12040 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012041
12042 out.writeInt(VERSION);
12043
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012044 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012046 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012047 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012048 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012049 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070012050 out.writeString(mStartPlatformVersion);
12051 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012052 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
12053 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012054 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012055 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070012056 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012057 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012058 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070012059 out.writeInt(mMinLearnedBatteryCapacity);
12060 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080012061 out.writeInt(getLowDischargeAmountSinceCharge());
12062 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012063 out.writeInt(getDischargeAmountScreenOnSinceCharge());
12064 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012065 mDischargeStepTracker.writeToParcel(out);
12066 mChargeStepTracker.writeToParcel(out);
12067 mDailyDischargeStepTracker.writeToParcel(out);
12068 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070012069 mDischargeCounter.writeSummaryFromParcelLocked(out);
12070 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012071 if (mDailyPackageChanges != null) {
12072 final int NPKG = mDailyPackageChanges.size();
12073 out.writeInt(NPKG);
12074 for (int i=0; i<NPKG; i++) {
12075 PackageChange pc = mDailyPackageChanges.get(i);
12076 out.writeString(pc.mPackageName);
12077 out.writeInt(pc.mUpdate ? 1 : 0);
12078 out.writeInt(pc.mVersionCode);
12079 }
12080 } else {
12081 out.writeInt(0);
12082 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012083 out.writeLong(mDailyStartTime);
12084 out.writeLong(mNextMinDailyDeadline);
12085 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012086
12087 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070012088 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012089 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070012090 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070012091 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070012092 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070012093 out.writeLong(mLongestLightIdleTime);
12094 out.writeLong(mLongestFullIdleTime);
12095 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12096 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12097 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012098 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012099 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080012100 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012101 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070012102 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012103 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070012104 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012105 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070012106 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012107 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080012108 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
12109 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012110 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012111 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12112 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012113 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080012114 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
12115 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012116 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12117 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080012118 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012119 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080012120 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070012121 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12122 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12123 }
12124 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12125 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12126 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080012127 mWifiActivity.writeSummaryToParcel(out);
12128 mBluetoothActivity.writeSummaryToParcel(out);
12129 mModemActivity.writeSummaryToParcel(out);
12130 out.writeInt(mHasWifiReporting ? 1 : 0);
12131 out.writeInt(mHasBluetoothReporting ? 1 : 0);
12132 out.writeInt(mHasModemReporting ? 1 : 0);
12133
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012134 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070012135 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012136 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012137 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012138
Bookatz50df7112017-08-04 14:53:26 -070012139 out.writeInt(mRpmStats.size());
12140 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
12141 Timer rpmt = ent.getValue();
12142 if (rpmt != null) {
12143 out.writeInt(1);
12144 out.writeString(ent.getKey());
12145 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12146 } else {
12147 out.writeInt(0);
12148 }
12149 }
12150 out.writeInt(mScreenOffRpmStats.size());
12151 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
12152 Timer rpmt = ent.getValue();
12153 if (rpmt != null) {
12154 out.writeInt(1);
12155 out.writeString(ent.getKey());
12156 rpmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12157 } else {
12158 out.writeInt(0);
12159 }
12160 }
12161
Evan Millarc64edde2009-04-18 12:26:32 -070012162 out.writeInt(mKernelWakelockStats.size());
12163 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
12164 Timer kwlt = ent.getValue();
12165 if (kwlt != null) {
12166 out.writeInt(1);
12167 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012168 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12169 } else {
12170 out.writeInt(0);
12171 }
12172 }
12173
12174 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012175 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
12176 SamplingTimer timer = ent.getValue();
12177 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012178 out.writeInt(1);
12179 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012180 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070012181 } else {
12182 out.writeInt(0);
12183 }
12184 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012185
James Carr3a226052016-07-01 14:49:52 -070012186 out.writeInt(mKernelMemoryStats.size());
12187 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
12188 Timer kmt = mKernelMemoryStats.valueAt(i);
12189 if (kmt != null) {
12190 out.writeInt(1);
12191 out.writeLong(mKernelMemoryStats.keyAt(i));
12192 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12193 } else {
12194 out.writeInt(0);
12195 }
12196 }
12197
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012198 out.writeLongArray(mCpuFreqs);
12199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012200 final int NU = mUidStats.size();
12201 out.writeInt(NU);
12202 for (int iu = 0; iu < NU; iu++) {
12203 out.writeInt(mUidStats.keyAt(iu));
12204 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012205
Bookatz867c0d72017-03-07 18:23:42 -080012206 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070012207 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080012208
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012209 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012210 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012211 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012212 } else {
12213 out.writeInt(0);
12214 }
12215 if (u.mFullWifiLockTimer != null) {
12216 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012217 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012218 } else {
12219 out.writeInt(0);
12220 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070012221 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012222 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012223 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012224 } else {
12225 out.writeInt(0);
12226 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070012227 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
12228 if (u.mWifiBatchedScanTimer[i] != null) {
12229 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012230 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070012231 } else {
12232 out.writeInt(0);
12233 }
12234 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012235 if (u.mWifiMulticastTimer != null) {
12236 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012237 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012238 } else {
12239 out.writeInt(0);
12240 }
12241 if (u.mAudioTurnedOnTimer != null) {
12242 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012243 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012244 } else {
12245 out.writeInt(0);
12246 }
12247 if (u.mVideoTurnedOnTimer != null) {
12248 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012249 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012250 } else {
12251 out.writeInt(0);
12252 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012253 if (u.mFlashlightTurnedOnTimer != null) {
12254 out.writeInt(1);
12255 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12256 } else {
12257 out.writeInt(0);
12258 }
12259 if (u.mCameraTurnedOnTimer != null) {
12260 out.writeInt(1);
12261 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12262 } else {
12263 out.writeInt(0);
12264 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070012265 if (u.mForegroundActivityTimer != null) {
12266 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012267 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070012268 } else {
12269 out.writeInt(0);
12270 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070012271 if (u.mForegroundServiceTimer != null) {
12272 out.writeInt(1);
12273 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12274 } else {
12275 out.writeInt(0);
12276 }
Bookatzc8c44962017-05-11 12:12:54 -070012277 if (u.mAggregatedPartialWakelockTimer != null) {
12278 out.writeInt(1);
12279 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12280 } else {
12281 out.writeInt(0);
12282 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012283 if (u.mBluetoothScanTimer != null) {
12284 out.writeInt(1);
12285 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12286 } else {
12287 out.writeInt(0);
12288 }
Bookatzb1f04f32017-05-19 13:57:32 -070012289 if (u.mBluetoothUnoptimizedScanTimer != null) {
12290 out.writeInt(1);
12291 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12292 } else {
12293 out.writeInt(0);
12294 }
Bookatz956f36bf2017-04-28 09:48:17 -070012295 if (u.mBluetoothScanResultCounter != null) {
12296 out.writeInt(1);
12297 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
12298 } else {
12299 out.writeInt(0);
12300 }
Bookatzb1f04f32017-05-19 13:57:32 -070012301 if (u.mBluetoothScanResultBgCounter != null) {
12302 out.writeInt(1);
12303 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
12304 } else {
12305 out.writeInt(0);
12306 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070012307 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
12308 if (u.mProcessStateTimer[i] != null) {
12309 out.writeInt(1);
12310 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12311 } else {
12312 out.writeInt(0);
12313 }
12314 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080012315 if (u.mVibratorOnTimer != null) {
12316 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012317 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080012318 } else {
12319 out.writeInt(0);
12320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012321
Dianne Hackborn617f8772009-03-31 15:04:46 -070012322 if (u.mUserActivityCounters == null) {
12323 out.writeInt(0);
12324 } else {
12325 out.writeInt(1);
12326 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
12327 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
12328 }
12329 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012330
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080012331 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012332 out.writeInt(0);
12333 } else {
12334 out.writeInt(1);
12335 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080012336 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
12337 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012338 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080012339 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
12340 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012341 }
12342
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012343 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
12344 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
12345
Sudheer Shanka71f34b32017-07-21 00:14:24 -070012346 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070012347 out.writeInt(1);
Sudheer Shanka71f34b32017-07-21 00:14:24 -070012348 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
12349 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070012350 if (cpuSpeeds != null) {
12351 out.writeInt(1);
12352 out.writeInt(cpuSpeeds.length);
12353 for (LongSamplingCounter c : cpuSpeeds) {
12354 if (c != null) {
12355 out.writeInt(1);
12356 c.writeSummaryFromParcelLocked(out);
12357 } else {
12358 out.writeInt(0);
12359 }
12360 }
12361 } else {
12362 out.writeInt(0);
12363 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012364 }
Adam Lesinski6832f392015-09-05 18:05:40 -070012365 } else {
12366 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012367 }
12368
Sudheer Shanka59f5c002017-05-15 10:57:15 -070012369 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
12370 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012371
Adam Lesinski5f056f62016-07-14 16:56:08 -070012372 if (u.mMobileRadioApWakeupCount != null) {
12373 out.writeInt(1);
12374 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
12375 } else {
12376 out.writeInt(0);
12377 }
12378
12379 if (u.mWifiRadioApWakeupCount != null) {
12380 out.writeInt(1);
12381 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
12382 } else {
12383 out.writeInt(0);
12384 }
12385
Dianne Hackbornd953c532014-08-16 18:17:38 -070012386 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
12387 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012388 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012389 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070012390 out.writeString(wakeStats.keyAt(iw));
12391 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012392 if (wl.mTimerFull != null) {
12393 out.writeInt(1);
12394 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12395 } else {
12396 out.writeInt(0);
12397 }
12398 if (wl.mTimerPartial != null) {
12399 out.writeInt(1);
12400 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12401 } else {
12402 out.writeInt(0);
12403 }
12404 if (wl.mTimerWindow != null) {
12405 out.writeInt(1);
12406 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12407 } else {
12408 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012409 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070012410 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070012411 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070012412 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070012413 } else {
12414 out.writeInt(0);
12415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012416 }
12417
Bookatz2bffb5b2017-04-13 11:59:33 -070012418 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070012419 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012420 out.writeInt(NS);
12421 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070012422 out.writeString(syncStats.keyAt(is));
12423 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012424 }
12425
Bookatzaa4594a2017-03-24 12:39:56 -070012426 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070012427 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012428 out.writeInt(NJ);
12429 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070012430 out.writeString(jobStats.keyAt(ij));
12431 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012432 }
12433
Dianne Hackborn94326cb2017-06-28 16:17:20 -070012434 u.writeJobCompletionsToParcelLocked(out);
12435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012436 int NSE = u.mSensorStats.size();
12437 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012438 for (int ise=0; ise<NSE; ise++) {
12439 out.writeInt(u.mSensorStats.keyAt(ise));
12440 Uid.Sensor se = u.mSensorStats.valueAt(ise);
12441 if (se.mTimer != null) {
12442 out.writeInt(1);
12443 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12444 } else {
12445 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012446 }
12447 }
12448
12449 int NP = u.mProcessStats.size();
12450 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012451 for (int ip=0; ip<NP; ip++) {
12452 out.writeString(u.mProcessStats.keyAt(ip));
12453 Uid.Proc ps = u.mProcessStats.valueAt(ip);
12454 out.writeLong(ps.mUserTime);
12455 out.writeLong(ps.mSystemTime);
12456 out.writeLong(ps.mForegroundTime);
12457 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012458 out.writeInt(ps.mNumCrashes);
12459 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012460 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012461 }
12462
12463 NP = u.mPackageStats.size();
12464 out.writeInt(NP);
12465 if (NP > 0) {
12466 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
12467 : u.mPackageStats.entrySet()) {
12468 out.writeString(ent.getKey());
12469 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070012470 final int NWA = ps.mWakeupAlarms.size();
12471 out.writeInt(NWA);
12472 for (int iwa=0; iwa<NWA; iwa++) {
12473 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
12474 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
12475 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012476 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012477 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070012478 for (int is=0; is<NS; is++) {
12479 out.writeString(ps.mServiceStats.keyAt(is));
12480 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
12481 long time = ss.getStartTimeToNowLocked(
12482 mOnBatteryTimeBase.getUptime(NOW_SYS));
12483 out.writeLong(time);
12484 out.writeInt(ss.mStarts);
12485 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012486 }
12487 }
12488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012489 }
12490 }
12491
12492 public void readFromParcel(Parcel in) {
12493 readFromParcelLocked(in);
12494 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012496 void readFromParcelLocked(Parcel in) {
12497 int magic = in.readInt();
12498 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012499 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012500 }
12501
Dianne Hackbornae384452011-06-28 12:33:48 -070012502 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012504 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080012505 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070012506 mStartPlatformVersion = in.readString();
12507 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012508 mUptime = in.readLong();
12509 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012510 mRealtime = in.readLong();
12511 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012512 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012513 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070012514 mMinLearnedBatteryCapacity = in.readInt();
12515 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012516 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012517 mOnBatteryTimeBase.readFromParcel(in);
12518 mOnBatteryScreenOffTimeBase.readFromParcel(in);
12519
Jeff Browne95c3cd2014-05-02 16:59:26 -070012520 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080012521 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012522 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012523 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
12524 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012525 }
Dianne Hackborn29325132014-05-21 15:01:03 -070012526 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080012527 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012528 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080012529 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
12530 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070012531 mLongestLightIdleTime = in.readLong();
12532 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080012533 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
12534 mOnBatteryTimeBase, in);
12535 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
12536 mOnBatteryTimeBase, in);
12537 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
12538 mOnBatteryTimeBase, in);
12539 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
12540 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012541 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012542 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012543 null, mOnBatteryTimeBase, in);
12544 }
Joe Onoratoabded112016-02-08 16:49:39 -080012545 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
12546 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012547 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012548 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012549 null, mOnBatteryTimeBase, in);
12550 }
12551 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
12552 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
12553 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
12554 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012555 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080012556 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
12557 mOnBatteryTimeBase, in);
12558 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
12559 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012560 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012561 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
12562 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012563 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012564 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080012565 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012566 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080012567 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
12568 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012569 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012570 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012571 null, mOnBatteryTimeBase, in);
12572 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070012573 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012574 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070012575 null, mOnBatteryTimeBase, in);
12576 }
12577 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012578 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070012579 null, mOnBatteryTimeBase, in);
12580 }
Adam Lesinski33dac552015-03-09 15:24:48 -070012581
Adam Lesinski21f76aa2016-01-25 12:27:06 -080012582 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
12583 NUM_WIFI_TX_LEVELS, in);
12584 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
12585 NUM_BT_TX_LEVELS, in);
12586 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
12587 ModemActivityInfo.TX_POWER_LEVELS, in);
12588 mHasWifiReporting = in.readInt() != 0;
12589 mHasBluetoothReporting = in.readInt() != 0;
12590 mHasModemReporting = in.readInt() != 0;
12591
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012592 mNumConnectivityChange = in.readInt();
12593 mLoadedNumConnectivityChange = in.readInt();
12594 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070012595 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012596 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070012597 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012598 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012599 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012600 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012601 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012602 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012603 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012604 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012605 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012606 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070012607 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012608 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012609 mLowDischargeAmountSinceCharge = in.readInt();
12610 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012611 mDischargeAmountScreenOn = in.readInt();
12612 mDischargeAmountScreenOnSinceCharge = in.readInt();
12613 mDischargeAmountScreenOff = in.readInt();
12614 mDischargeAmountScreenOffSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012615 mDischargeStepTracker.readFromParcel(in);
12616 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012617 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
12618 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012619 mLastWriteTime = in.readLong();
12620
Bookatz50df7112017-08-04 14:53:26 -070012621 mRpmStats.clear();
12622 int NRPMS = in.readInt();
12623 for (int irpm = 0; irpm < NRPMS; irpm++) {
12624 if (in.readInt() != 0) {
12625 String rpmName = in.readString();
12626 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
12627 mRpmStats.put(rpmName, rpmt);
12628 }
12629 }
12630 mScreenOffRpmStats.clear();
12631 int NSORPMS = in.readInt();
12632 for (int irpm = 0; irpm < NSORPMS; irpm++) {
12633 if (in.readInt() != 0) {
12634 String rpmName = in.readString();
12635 SamplingTimer rpmt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
12636 mScreenOffRpmStats.put(rpmName, rpmt);
12637 }
12638 }
12639
Evan Millarc64edde2009-04-18 12:26:32 -070012640 mKernelWakelockStats.clear();
12641 int NKW = in.readInt();
12642 for (int ikw = 0; ikw < NKW; ikw++) {
12643 if (in.readInt() != 0) {
12644 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080012645 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070012646 mKernelWakelockStats.put(wakelockName, kwlt);
12647 }
12648 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012649
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012650 mWakeupReasonStats.clear();
12651 int NWR = in.readInt();
12652 for (int iwr = 0; iwr < NWR; iwr++) {
12653 if (in.readInt() != 0) {
12654 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080012655 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012656 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012657 }
12658 }
12659
James Carr3a226052016-07-01 14:49:52 -070012660 mKernelMemoryStats.clear();
12661 int nmt = in.readInt();
12662 for (int imt = 0; imt < nmt; imt++) {
12663 if (in.readInt() != 0) {
12664 Long bucket = in.readLong();
12665 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
12666 mKernelMemoryStats.put(bucket, kmt);
12667 }
12668 }
12669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012670 mPartialTimers.clear();
12671 mFullTimers.clear();
12672 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012673 mWifiRunningTimers.clear();
12674 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070012675 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070012676 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012677 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070012678 mAudioTurnedOnTimers.clear();
12679 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012680 mFlashlightTurnedOnTimers.clear();
12681 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012682
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012683 mCpuFreqs = in.createLongArray();
12684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012685 int numUids = in.readInt();
12686 mUidStats.clear();
12687 for (int i = 0; i < numUids; i++) {
12688 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080012689 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012690 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012691 mUidStats.append(uid, u);
12692 }
12693 }
12694
12695 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012696 writeToParcelLocked(out, true, flags);
12697 }
12698
12699 public void writeToParcelWithoutUids(Parcel out, int flags) {
12700 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012701 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012702
12703 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012704 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012705 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012706 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012707
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012708 // Pull the clock time. This may update the time and make a new history entry
12709 // if we had originally pulled a time before the RTC was set.
12710 long startClockTime = getStartClockTime();
12711
Joe Onoratoabded112016-02-08 16:49:39 -080012712 final long uSecUptime = mClocks.uptimeMillis() * 1000;
12713 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012714 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
12715 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012717 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012718
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012719 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012721 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012722 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070012723 out.writeString(mStartPlatformVersion);
12724 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012725 out.writeLong(mUptime);
12726 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012727 out.writeLong(mRealtime);
12728 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012729 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012730 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070012731 out.writeInt(mMinLearnedBatteryCapacity);
12732 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012733 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
12734 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
12735
12736 mScreenOnTimer.writeToParcel(out, uSecRealtime);
12737 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
12738 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
12739 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070012740 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070012741 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070012742 out.writeLong(mLongestLightIdleTime);
12743 out.writeLong(mLongestFullIdleTime);
12744 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
12745 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
12746 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012747 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012748 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
12749 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
12750 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
12751 }
12752 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
12753 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
12754 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
12755 }
12756 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
12757 mNetworkByteActivityCounters[i].writeToParcel(out);
12758 mNetworkPacketActivityCounters[i].writeToParcel(out);
12759 }
12760 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
12761 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012762 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012763 mMobileRadioActiveUnknownTime.writeToParcel(out);
12764 mMobileRadioActiveUnknownCount.writeToParcel(out);
12765 mWifiOnTimer.writeToParcel(out, uSecRealtime);
12766 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
12767 for (int i=0; i<NUM_WIFI_STATES; i++) {
12768 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
12769 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070012770 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12771 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
12772 }
12773 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12774 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
12775 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080012776 mWifiActivity.writeToParcel(out, 0);
12777 mBluetoothActivity.writeToParcel(out, 0);
12778 mModemActivity.writeToParcel(out, 0);
12779 out.writeInt(mHasWifiReporting ? 1 : 0);
12780 out.writeInt(mHasBluetoothReporting ? 1 : 0);
12781 out.writeInt(mHasModemReporting ? 1 : 0);
12782
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012783 out.writeInt(mNumConnectivityChange);
12784 out.writeInt(mLoadedNumConnectivityChange);
12785 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070012786 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012787 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012788 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012789 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012790 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070012791 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012792 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012793 out.writeInt(mLowDischargeAmountSinceCharge);
12794 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012795 out.writeInt(mDischargeAmountScreenOn);
12796 out.writeInt(mDischargeAmountScreenOnSinceCharge);
12797 out.writeInt(mDischargeAmountScreenOff);
12798 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012799 mDischargeStepTracker.writeToParcel(out);
12800 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012801 mDischargeCounter.writeToParcel(out);
12802 mDischargeScreenOffCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012803 out.writeLong(mLastWriteTime);
12804
Bookatz50df7112017-08-04 14:53:26 -070012805 out.writeInt(mRpmStats.size());
12806 for (Map.Entry<String, SamplingTimer> ent : mRpmStats.entrySet()) {
12807 SamplingTimer rpmt = ent.getValue();
12808 if (rpmt != null) {
12809 out.writeInt(1);
12810 out.writeString(ent.getKey());
12811 rpmt.writeToParcel(out, uSecRealtime);
12812 } else {
12813 out.writeInt(0);
12814 }
12815 }
12816 out.writeInt(mScreenOffRpmStats.size());
12817 for (Map.Entry<String, SamplingTimer> ent : mScreenOffRpmStats.entrySet()) {
12818 SamplingTimer rpmt = ent.getValue();
12819 if (rpmt != null) {
12820 out.writeInt(1);
12821 out.writeString(ent.getKey());
12822 rpmt.writeToParcel(out, uSecRealtime);
12823 } else {
12824 out.writeInt(0);
12825 }
12826 }
12827
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012828 if (inclUids) {
12829 out.writeInt(mKernelWakelockStats.size());
12830 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
12831 SamplingTimer kwlt = ent.getValue();
12832 if (kwlt != null) {
12833 out.writeInt(1);
12834 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012835 kwlt.writeToParcel(out, uSecRealtime);
12836 } else {
12837 out.writeInt(0);
12838 }
12839 }
12840 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012841 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
12842 SamplingTimer timer = ent.getValue();
12843 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012844 out.writeInt(1);
12845 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012846 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012847 } else {
12848 out.writeInt(0);
12849 }
Evan Millarc64edde2009-04-18 12:26:32 -070012850 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012851 } else {
Bookatz50df7112017-08-04 14:53:26 -070012852 // TODO: There should be two 0's printed here, not just one.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012853 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070012854 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070012855
James Carr3a226052016-07-01 14:49:52 -070012856 out.writeInt(mKernelMemoryStats.size());
12857 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
12858 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
12859 if (kmt != null) {
12860 out.writeInt(1);
12861 out.writeLong(mKernelMemoryStats.keyAt(i));
12862 kmt.writeToParcel(out, uSecRealtime);
12863 } else {
12864 out.writeInt(0);
12865 }
12866 }
12867
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012868 out.writeLongArray(mCpuFreqs);
12869
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012870 if (inclUids) {
12871 int size = mUidStats.size();
12872 out.writeInt(size);
12873 for (int i = 0; i < size; i++) {
12874 out.writeInt(mUidStats.keyAt(i));
12875 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012876
Bookatz867c0d72017-03-07 18:23:42 -080012877 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012878 }
12879 } else {
12880 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012881 }
12882 }
12883
12884 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
12885 new Parcelable.Creator<BatteryStatsImpl>() {
12886 public BatteryStatsImpl createFromParcel(Parcel in) {
12887 return new BatteryStatsImpl(in);
12888 }
12889
12890 public BatteryStatsImpl[] newArray(int size) {
12891 return new BatteryStatsImpl[size];
12892 }
12893 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012894
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012895 public void prepareForDumpLocked() {
12896 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012897 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012898
12899 // Pull the clock time. This may update the time and make a new history entry
12900 // if we had originally pulled a time before the RTC was set.
12901 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012902 }
12903
Dianne Hackbornc51cf032014-03-02 19:08:15 -080012904 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012905 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012906 pw.println("mOnBatteryTimeBase:");
12907 mOnBatteryTimeBase.dump(pw, " ");
12908 pw.println("mOnBatteryScreenOffTimeBase:");
12909 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070012910 Printer pr = new PrintWriterPrinter(pw);
12911 pr.println("*** Screen timer:");
12912 mScreenOnTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070012913 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070012914 pr.println("*** Screen brightness #" + i + ":");
12915 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070012916 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070012917 pr.println("*** Interactive timer:");
12918 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070012919 pr.println("*** Power save mode timer:");
12920 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070012921 pr.println("*** Device idle mode light timer:");
12922 mDeviceIdleModeLightTimer.logState(pr, " ");
12923 pr.println("*** Device idle mode full timer:");
12924 mDeviceIdleModeFullTimer.logState(pr, " ");
12925 pr.println("*** Device light idling timer:");
12926 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012927 pr.println("*** Device idling timer:");
12928 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070012929 pr.println("*** Phone timer:");
12930 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080012931 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070012932 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070012933 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070012934 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070012935 pr.println("*** Signal scanning :");
12936 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070012937 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070012938 pr.println("*** Data connection type #" + i + ":");
12939 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070012940 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012941 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080012942 pr.println("*** Mobile network active timer:");
12943 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012944 pr.println("*** Mobile network active adjusted timer:");
12945 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012946 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070012947 pr.println("*** Wifi timer:");
12948 mWifiOnTimer.logState(pr, " ");
12949 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012950 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080012951 for (int i=0; i<NUM_WIFI_STATES; i++) {
12952 pr.println("*** Wifi state #" + i + ":");
12953 mWifiStateTimer[i].logState(pr, " ");
12954 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070012955 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12956 pr.println("*** Wifi suppl state #" + i + ":");
12957 mWifiSupplStateTimer[i].logState(pr, " ");
12958 }
12959 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12960 pr.println("*** Wifi signal strength #" + i + ":");
12961 mWifiSignalStrengthsTimer[i].logState(pr, " ");
12962 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070012963 pr.println("*** Flashlight timer:");
12964 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012965 pr.println("*** Camera timer:");
12966 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012967 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080012968 super.dumpLocked(context, pw, flags, reqUid, histStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012970}