blob: c58ff0590dfa1054b53312667f473ec3474bcf55 [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
Sudheer Shankab8ad5942017-08-08 12:16:09 -0700122 private static final int VERSION = 165 + (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
Sudheer Shanka38383232017-07-25 09:55:03 -0700160 /**
161 * Holding a wakelock costs more than just using the cpu.
162 * Currently, we assign only half the cpu time to an app that is running but
163 * not holding a wakelock. The apps holding wakelocks get the rest of the blame.
164 * If no app is holding a wakelock, then the distribution is normal.
165 */
166 @VisibleForTesting
167 public static final int WAKE_LOCK_WEIGHT = 50;
168
Joe Onoratoabded112016-02-08 16:49:39 -0800169 protected Clocks mClocks;
170
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700171 private final JournaledFile mFile;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700172 public final AtomicFile mCheckinFile;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800173 public final AtomicFile mDailyFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700175 static final int MSG_UPDATE_WAKELOCKS = 1;
176 static final int MSG_REPORT_POWER_CHANGE = 2;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700177 static final int MSG_REPORT_CHARGING = 3;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700178 static final long DELAY_UPDATE_WAKELOCKS = 5*1000;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700179
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700180 private final KernelWakelockReader mKernelWakelockReader = new KernelWakelockReader();
181 private final KernelWakelockStats mTmpWakelockStats = new KernelWakelockStats();
182
Sudheer Shanka38383232017-07-25 09:55:03 -0700183 @VisibleForTesting
184 protected KernelUidCpuTimeReader mKernelUidCpuTimeReader = new KernelUidCpuTimeReader();
185 @VisibleForTesting
186 protected KernelCpuSpeedReader[] mKernelCpuSpeedReaders;
187 @VisibleForTesting
188 protected KernelUidCpuFreqTimeReader mKernelUidCpuFreqTimeReader =
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700189 new KernelUidCpuFreqTimeReader();
Adam Lesinski06af1fa2015-05-05 17:35:35 -0700190
James Carr3a226052016-07-01 14:49:52 -0700191 private final KernelMemoryBandwidthStats mKernelMemoryBandwidthStats
192 = new KernelMemoryBandwidthStats();
193 private final LongSparseArray<SamplingTimer> mKernelMemoryStats = new LongSparseArray<>();
194 public LongSparseArray<SamplingTimer> getKernelMemoryStats() {
195 return mKernelMemoryStats;
196 }
197
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700198 public interface BatteryCallback {
199 public void batteryNeedsCpuUpdate();
200 public void batteryPowerChanged(boolean onBattery);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700201 public void batterySendBroadcast(Intent intent);
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700202 }
203
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700204 public interface PlatformIdleStateCallback {
205 public String getPlatformLowPowerStats();
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +0000206 public String getSubsystemLowPowerStats();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700207 }
208
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700209 public static abstract class UserInfoProvider {
210 private int[] userIds;
211 protected abstract @Nullable int[] getUserIds();
Sudheer Shanka38383232017-07-25 09:55:03 -0700212 @VisibleForTesting
213 public final void refreshUserIds() {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700214 userIds = getUserIds();
215 }
Sudheer Shanka38383232017-07-25 09:55:03 -0700216 @VisibleForTesting
217 public boolean exists(int userId) {
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700218 return userIds != null ? ArrayUtils.contains(userIds, userId) : true;
219 }
220 }
221
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700222 private final PlatformIdleStateCallback mPlatformIdleStateCallback;
223
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700224 final class MyHandler extends Handler {
Jeff Brown6f357d32014-01-15 20:40:55 -0800225 public MyHandler(Looper looper) {
226 super(looper, null, true);
227 }
228
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700229 @Override
230 public void handleMessage(Message msg) {
231 BatteryCallback cb = mCallback;
232 switch (msg.what) {
233 case MSG_UPDATE_WAKELOCKS:
Adam Lesinski72478f02015-06-17 15:39:43 -0700234 synchronized (BatteryStatsImpl.this) {
Sudheer Shankab8ad5942017-08-08 12:16:09 -0700235 updateCpuTimeLocked();
Adam Lesinski72478f02015-06-17 15:39:43 -0700236 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700237 if (cb != null) {
238 cb.batteryNeedsCpuUpdate();
239 }
240 break;
241 case MSG_REPORT_POWER_CHANGE:
242 if (cb != null) {
243 cb.batteryPowerChanged(msg.arg1 != 0);
244 }
245 break;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700246 case MSG_REPORT_CHARGING:
247 if (cb != null) {
248 final String action;
249 synchronized (BatteryStatsImpl.this) {
250 action = mCharging ? BatteryManager.ACTION_CHARGING
251 : BatteryManager.ACTION_DISCHARGING;
252 }
253 Intent intent = new Intent(action);
254 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
255 cb.batterySendBroadcast(intent);
256 }
257 break;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700258 }
259 }
260 }
261
Joe Onoratoabded112016-02-08 16:49:39 -0800262 public interface Clocks {
263 public long elapsedRealtime();
264 public long uptimeMillis();
265 }
266
267 public static class SystemClocks implements Clocks {
268 public long elapsedRealtime() {
269 return SystemClock.elapsedRealtime();
270 }
271
272 public long uptimeMillis() {
273 return SystemClock.uptimeMillis();
274 }
275 }
276
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700277 public interface ExternalStatsSync {
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700278 int UPDATE_CPU = 0x01;
279 int UPDATE_WIFI = 0x02;
280 int UPDATE_RADIO = 0x04;
281 int UPDATE_BT = 0x08;
282 int UPDATE_ALL = UPDATE_CPU | UPDATE_WIFI | UPDATE_RADIO | UPDATE_BT;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800283
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700284 Future<?> scheduleSync(String reason, int flags);
285 Future<?> scheduleCpuSyncDueToRemovedUid(int uid);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700286 }
287
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700288 public final MyHandler mHandler;
Adam Lesinskib3a1bad2017-05-26 11:50:40 -0700289 private ExternalStatsSync mExternalSync = null;
Sudheer Shanka38383232017-07-25 09:55:03 -0700290 @VisibleForTesting
291 protected UserInfoProvider mUserInfoProvider = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700292
293 private BatteryCallback mCallback;
294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -0800296 * Mapping isolated uids to the actual owning app uid.
297 */
298 final SparseIntArray mIsolatedUids = new SparseIntArray();
299
300 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 * The statistics we have collected organized by uids.
302 */
Adam Lesinski50e47602015-12-04 17:04:54 -0800303 final SparseArray<BatteryStatsImpl.Uid> mUidStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304
305 // A set of pools of currently active timers. When a timer is queried, we will divide the
306 // elapsed time by the number of active timers to arrive at that timer's share of the time.
307 // In order to do this, we must refresh each timer whenever the number of active timers
308 // changes.
Sudheer Shanka38383232017-07-25 09:55:03 -0700309 @VisibleForTesting
310 protected ArrayList<StopwatchTimer> mPartialTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700311 final ArrayList<StopwatchTimer> mFullTimers = new ArrayList<>();
312 final ArrayList<StopwatchTimer> mWindowTimers = new ArrayList<>();
Jeff Brown6a8bd7b2015-06-19 15:07:51 -0700313 final ArrayList<StopwatchTimer> mDrawTimers = new ArrayList<>();
Adam Lesinskie08af192015-03-25 16:42:59 -0700314 final SparseArray<ArrayList<StopwatchTimer>> mSensorTimers = new SparseArray<>();
315 final ArrayList<StopwatchTimer> mWifiRunningTimers = new ArrayList<>();
316 final ArrayList<StopwatchTimer> mFullWifiLockTimers = new ArrayList<>();
317 final ArrayList<StopwatchTimer> mWifiMulticastTimers = new ArrayList<>();
318 final ArrayList<StopwatchTimer> mWifiScanTimers = new ArrayList<>();
319 final SparseArray<ArrayList<StopwatchTimer>> mWifiBatchedScanTimers = new SparseArray<>();
320 final ArrayList<StopwatchTimer> mAudioTurnedOnTimers = new ArrayList<>();
321 final ArrayList<StopwatchTimer> mVideoTurnedOnTimers = new ArrayList<>();
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700322 final ArrayList<StopwatchTimer> mFlashlightTurnedOnTimers = new ArrayList<>();
323 final ArrayList<StopwatchTimer> mCameraTurnedOnTimers = new ArrayList<>();
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800324 final ArrayList<StopwatchTimer> mBluetoothScanOnTimers = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700326 // Last partial timers we use for distributing CPU usage.
Sudheer Shanka38383232017-07-25 09:55:03 -0700327 @VisibleForTesting
328 protected ArrayList<StopwatchTimer> mLastPartialTimers = new ArrayList<>();
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 // These are the objects that will want to do something when the device
331 // is unplugged from power.
Joe Onoratoabded112016-02-08 16:49:39 -0800332 protected final TimeBase mOnBatteryTimeBase = new TimeBase();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800333
334 // These are the objects that will want to do something when the device
335 // is unplugged from power *and* the screen is off.
336 final TimeBase mOnBatteryScreenOffTimeBase = new TimeBase();
337
338 // Set to true when we want to distribute CPU across wakelocks for the next
339 // CPU update, even if we aren't currently running wake locks.
340 boolean mDistributeWakelockCpu;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700341
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700342 boolean mShuttingDown;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700343
Dianne Hackborn37de0982014-05-09 09:32:18 -0700344 final HistoryEventTracker mActiveEvents = new HistoryEventTracker();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -0800345
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700346 long mHistoryBaseTime;
347 boolean mHaveBatteryLevel = false;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700348 boolean mRecordingHistory = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700349 int mNumHistoryItems;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700350
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700351 final Parcel mHistoryBuffer = Parcel.obtain();
352 final HistoryItem mHistoryLastWritten = new HistoryItem();
353 final HistoryItem mHistoryLastLastWritten = new HistoryItem();
Dianne Hackborn1fadab52011-04-14 17:57:33 -0700354 final HistoryItem mHistoryReadTmp = new HistoryItem();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700355 final HistoryItem mHistoryAddTmp = new HistoryItem();
Adam Lesinskie08af192015-03-25 16:42:59 -0700356 final HashMap<HistoryTag, Integer> mHistoryTagPool = new HashMap<>();
Dianne Hackborn099bc622014-01-22 13:39:16 -0800357 String[] mReadHistoryStrings;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -0800358 int[] mReadHistoryUids;
359 int mReadHistoryChars;
360 int mNextHistoryTagIdx = 0;
361 int mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700362 int mHistoryBufferLastPos = -1;
363 boolean mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700364 int mActiveHistoryStates = 0xffffffff;
365 int mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn40c87252014-03-19 16:55:40 -0700366 long mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700367 long mTrackRunningHistoryElapsedRealtime = 0;
368 long mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700369
370 final HistoryItem mHistoryCur = new HistoryItem();
371
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700372 HistoryItem mHistory;
373 HistoryItem mHistoryEnd;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700374 HistoryItem mHistoryLastEnd;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700375 HistoryItem mHistoryCache;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700376
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800377 // Used by computeHistoryStepDetails
378 HistoryStepDetails mLastHistoryStepDetails = null;
379 byte mLastHistoryStepLevel = 0;
380 final HistoryStepDetails mCurHistoryStepDetails = new HistoryStepDetails();
381 final HistoryStepDetails mReadHistoryStepDetails = new HistoryStepDetails();
382 final HistoryStepDetails mTmpHistoryStepDetails = new HistoryStepDetails();
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700383
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800384 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700385 * Total time (in milliseconds) spent executing in user code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800386 */
387 long mLastStepCpuUserTime;
388 long mCurStepCpuUserTime;
389 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700390 * Total time (in milliseconds) spent executing in kernel code.
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800391 */
392 long mLastStepCpuSystemTime;
393 long mCurStepCpuSystemTime;
394 /**
Adam Lesinski7b83b0c2015-06-05 12:59:36 -0700395 * Times from /proc/stat (but measured in milliseconds).
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -0800396 */
397 long mLastStepStatUserTime;
398 long mLastStepStatSystemTime;
399 long mLastStepStatIOWaitTime;
400 long mLastStepStatIrqTime;
401 long mLastStepStatSoftIrqTime;
402 long mLastStepStatIdleTime;
403 long mCurStepStatUserTime;
404 long mCurStepStatSystemTime;
405 long mCurStepStatIOWaitTime;
406 long mCurStepStatIrqTime;
407 long mCurStepStatSoftIrqTime;
408 long mCurStepStatIdleTime;
409
Dianne Hackborn0ffc9882011-04-13 18:15:56 -0700410 private HistoryItem mHistoryIterator;
411 private boolean mReadOverflow;
412 private boolean mIteratingHistory;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 int mStartCount;
415
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800416 long mStartClockTime;
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700417 String mStartPlatformVersion;
418 String mEndPlatformVersion;
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -0800419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 long mUptime;
421 long mUptimeStart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 long mRealtime;
423 long mRealtimeStart;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700424
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800425 int mWakeLockNesting;
426 boolean mWakeLockImportant;
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700427 public boolean mRecordAllHistory;
Dianne Hackborn9a755432014-05-15 17:05:22 -0700428 boolean mNoAutoReset;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800429
Jeff Browne95c3cd2014-05-02 16:59:26 -0700430 int mScreenState = Display.STATE_UNKNOWN;
Evan Millarc64edde2009-04-18 12:26:32 -0700431 StopwatchTimer mScreenOnTimer;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700432
Dianne Hackborn617f8772009-03-31 15:04:46 -0700433 int mScreenBrightnessBin = -1;
Evan Millarc64edde2009-04-18 12:26:32 -0700434 final StopwatchTimer[] mScreenBrightnessTimer = new StopwatchTimer[NUM_SCREEN_BRIGHTNESS_BINS];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700435
Amith Yamasani674c9bb2017-02-01 09:45:17 -0800436 boolean mPretendScreenOff;
437
Jeff Browne95c3cd2014-05-02 16:59:26 -0700438 boolean mInteractive;
439 StopwatchTimer mInteractiveTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700440
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700441 boolean mPowerSaveModeEnabled;
442 StopwatchTimer mPowerSaveModeEnabledTimer;
443
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700444 boolean mDeviceIdling;
445 StopwatchTimer mDeviceIdlingTimer;
446
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700447 boolean mDeviceLightIdling;
448 StopwatchTimer mDeviceLightIdlingTimer;
449
450 int mDeviceIdleMode;
451 long mLastIdleTimeStart;
452 long mLongestLightIdleTime;
453 long mLongestFullIdleTime;
454 StopwatchTimer mDeviceIdleModeLightTimer;
455 StopwatchTimer mDeviceIdleModeFullTimer;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -0700456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 boolean mPhoneOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700458 StopwatchTimer mPhoneOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700459
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700460 int mAudioOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700461 StopwatchTimer mAudioOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700462
Dianne Hackborn10eaa852014-07-22 22:54:55 -0700463 int mVideoOnNesting;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700464 StopwatchTimer mVideoOnTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700465
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700466 int mFlashlightOnNesting;
Dianne Hackbornabc7c492014-06-30 16:57:46 -0700467 StopwatchTimer mFlashlightOnTimer;
468
Ruben Brunk6d2c3632015-05-26 17:32:16 -0700469 int mCameraOnNesting;
470 StopwatchTimer mCameraOnTimer;
471
Dianne Hackborn627bba72009-03-24 22:32:56 -0700472 int mPhoneSignalStrengthBin = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800473 int mPhoneSignalStrengthBinRaw = -1;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700474 final StopwatchTimer[] mPhoneSignalStrengthsTimer =
Wink Saville52840902011-02-18 12:40:47 -0800475 new StopwatchTimer[SignalStrength.NUM_SIGNAL_STRENGTH_BINS];
Amith Yamasanif37447b2009-10-08 18:28:01 -0700476
477 StopwatchTimer mPhoneSignalScanningTimer;
478
Dianne Hackborn627bba72009-03-24 22:32:56 -0700479 int mPhoneDataConnectionType = -1;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700480 final StopwatchTimer[] mPhoneDataConnectionsTimer =
Evan Millarc64edde2009-04-18 12:26:32 -0700481 new StopwatchTimer[NUM_DATA_CONNECTION_TYPES];
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700482
Dianne Hackborn57ed6a62013-12-09 18:15:56 -0800483 final LongSamplingCounter[] mNetworkByteActivityCounters =
484 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
485 final LongSamplingCounter[] mNetworkPacketActivityCounters =
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700486 new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
487
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800488 /**
489 * The WiFi controller activity (time in tx, rx, idle, and power consumed) for the device.
490 */
491 ControllerActivityCounterImpl mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -0700492
Adam Lesinski21f76aa2016-01-25 12:27:06 -0800493 /**
494 * The Bluetooth controller activity (time in tx, rx, idle, and power consumed) for the device.
495 */
496 ControllerActivityCounterImpl mBluetoothActivity;
497
498 /**
499 * The Modem controller activity (time in tx, rx, idle, and power consumed) for the device.
500 */
501 ControllerActivityCounterImpl mModemActivity;
502
503 /**
504 * Whether the device supports WiFi controller energy reporting. This is set to true on
505 * the first WiFi energy report. See {@link #mWifiActivity}.
506 */
507 boolean mHasWifiReporting = false;
508
509 /**
510 * Whether the device supports Bluetooth controller energy reporting. This is set to true on
511 * the first Bluetooth energy report. See {@link #mBluetoothActivity}.
512 */
513 boolean mHasBluetoothReporting = false;
514
515 /**
516 * Whether the device supports Modem controller energy reporting. This is set to true on
517 * the first Modem energy report. See {@link #mModemActivity}.
518 */
519 boolean mHasModemReporting = false;
Adam Lesinski33dac552015-03-09 15:24:48 -0700520
The Android Open Source Project10592532009-03-18 17:39:46 -0700521 boolean mWifiOn;
Evan Millarc64edde2009-04-18 12:26:32 -0700522 StopwatchTimer mWifiOnTimer;
Eric Shienbroodd4c5f892009-03-24 18:13:20 -0700523
Dianne Hackborn58e0eef2010-09-16 01:22:10 -0700524 boolean mGlobalWifiRunning;
525 StopwatchTimer mGlobalWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700526
Dianne Hackbornca1bf212014-02-14 14:18:36 -0800527 int mWifiState = -1;
528 final StopwatchTimer[] mWifiStateTimer = new StopwatchTimer[NUM_WIFI_STATES];
529
Dianne Hackborn3251b902014-06-20 14:40:53 -0700530 int mWifiSupplState = -1;
531 final StopwatchTimer[] mWifiSupplStateTimer = new StopwatchTimer[NUM_WIFI_SUPPL_STATES];
532
533 int mWifiSignalStrengthBin = -1;
534 final StopwatchTimer[] mWifiSignalStrengthsTimer =
535 new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
536
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800537 int mBluetoothScanNesting;
Bookatz867c0d72017-03-07 18:23:42 -0800538 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
539 protected StopwatchTimer mBluetoothScanTimer;
Adam Lesinski9f55cc72016-01-27 20:42:14 -0800540
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700541 int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackbornf7097a52014-05-13 09:56:14 -0700542 long mMobileRadioActiveStartTime;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800543 StopwatchTimer mMobileRadioActiveTimer;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800544 StopwatchTimer mMobileRadioActivePerAppTimer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700545 LongSamplingCounter mMobileRadioActiveAdjustedTime;
Dianne Hackbornd45665b2014-02-26 12:35:32 -0800546 LongSamplingCounter mMobileRadioActiveUnknownTime;
547 LongSamplingCounter mMobileRadioActiveUnknownCount;
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800548
Dianne Hackborn0c820db2015-04-14 17:47:34 -0700549 int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 /**
552 * These provide time bases that discount the time the device is plugged
553 * in to power.
554 */
555 boolean mOnBattery;
Sudheer Shanka38383232017-07-25 09:55:03 -0700556 @VisibleForTesting
557 protected boolean mOnBatteryInternal;
Amith Yamasani3718aaa2009-06-09 06:32:35 -0700558
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700559 /**
560 * External reporting of whether the device is actually charging.
561 */
562 boolean mCharging = true;
563 int mLastChargingStateLevel;
564
The Android Open Source Project10592532009-03-18 17:39:46 -0700565 /*
566 * These keep track of battery levels (1-100) at the last plug event and the last unplug event.
567 */
Evan Millar633a1742009-04-02 16:36:33 -0700568 int mDischargeStartLevel;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700569 int mDischargeUnplugLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700570 int mDischargePlugLevel;
Evan Millar633a1742009-04-02 16:36:33 -0700571 int mDischargeCurrentLevel;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700572 int mCurrentBatteryLevel;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -0700573 int mLowDischargeAmountSinceCharge;
574 int mHighDischargeAmountSinceCharge;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -0800575 int mDischargeScreenOnUnplugLevel;
576 int mDischargeScreenOffUnplugLevel;
577 int mDischargeAmountScreenOn;
578 int mDischargeAmountScreenOnSinceCharge;
579 int mDischargeAmountScreenOff;
580 int mDischargeAmountScreenOffSinceCharge;
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700581
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700582 private LongSamplingCounter mDischargeScreenOffCounter;
583 private LongSamplingCounter mDischargeCounter;
584
Dianne Hackborncd0e3352014-08-07 17:08:09 -0700585 static final int MAX_LEVEL_STEPS = 200;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700586
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700587 int mInitStepMode = 0;
588 int mCurStepMode = 0;
589 int mModStepMode = 0;
590
Dianne Hackborn260c5022014-04-29 11:23:16 -0700591 int mLastDischargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700592 int mMinDischargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800593 final LevelStepTracker mDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
594 final LevelStepTracker mDailyDischargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700595 ArrayList<PackageChange> mDailyPackageChanges;
Dianne Hackborn260c5022014-04-29 11:23:16 -0700596
597 int mLastChargeStepLevel;
Dianne Hackborn29325132014-05-21 15:01:03 -0700598 int mMaxChargeStepLevel;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800599 final LevelStepTracker mChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS);
600 final LevelStepTracker mDailyChargeStepTracker = new LevelStepTracker(MAX_LEVEL_STEPS*2);
601
602 static final int MAX_DAILY_ITEMS = 10;
603
604 long mDailyStartTime = 0;
605 long mNextMinDailyDeadline = 0;
606 long mNextMaxDailyDeadline = 0;
607
608 final ArrayList<DailyItem> mDailyItems = new ArrayList<>();
Dianne Hackborn260c5022014-04-29 11:23:16 -0700609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 long mLastWriteTime = 0; // Milliseconds
Amith Yamasani244fa5c2009-05-22 14:36:07 -0700611
Amith Yamasanif37447b2009-10-08 18:28:01 -0700612 private int mPhoneServiceState = -1;
Dianne Hackborne4a59512010-12-07 11:08:07 -0800613 private int mPhoneServiceStateRaw = -1;
614 private int mPhoneSimStateRaw = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -0700615
Dianne Hackborn1e01d162014-12-04 17:46:42 -0800616 private int mNumConnectivityChange;
617 private int mLoadedNumConnectivityChange;
618 private int mUnpluggedNumConnectivityChange;
619
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700620 private int mEstimatedBatteryCapacity = -1;
621
Jocelyn Dangc627d102017-04-14 13:15:14 -0700622 private int mMinLearnedBatteryCapacity = -1;
623 private int mMaxLearnedBatteryCapacity = -1;
Adam Lesinski041d9172016-12-12 12:03:56 -0800624
Sudheer Shanka9b735c52017-05-09 18:26:18 -0700625 private long[] mCpuFreqs;
626
Sudheer Shanka38383232017-07-25 09:55:03 -0700627 @VisibleForTesting
628 protected PowerProfile mPowerProfile;
Adam Lesinskie08af192015-03-25 16:42:59 -0700629
Evan Millarc64edde2009-04-18 12:26:32 -0700630 /*
631 * Holds a SamplingTimer associated with each kernel wakelock name being tracked.
632 */
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -0700633 private final HashMap<String, SamplingTimer> mKernelWakelockStats = new HashMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700634
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700635 public Map<String, ? extends Timer> getKernelWakelockStats() {
Evan Millarc64edde2009-04-18 12:26:32 -0700636 return mKernelWakelockStats;
637 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700638
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700639 String mLastWakeupReason = null;
640 long mLastWakeupUptimeMs = 0;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700641 private final HashMap<String, SamplingTimer> mWakeupReasonStats = new HashMap<>();
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700642
Dianne Hackbornc3940bc2014-09-05 15:50:25 -0700643 public Map<String, ? extends Timer> getWakeupReasonStats() {
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700644 return mWakeupReasonStats;
645 }
646
Adam Lesinski3ee3f632016-06-08 13:55:55 -0700647 @Override
648 public LongCounter getDischargeScreenOffCoulombCounter() {
649 return mDischargeScreenOffCounter;
650 }
651
652 @Override
653 public LongCounter getDischargeCoulombCounter() {
654 return mDischargeCounter;
655 }
656
Adam Lesinskif9b20a92016-06-17 17:30:01 -0700657 @Override
658 public int getEstimatedBatteryCapacity() {
659 return mEstimatedBatteryCapacity;
660 }
661
Jocelyn Dangc627d102017-04-14 13:15:14 -0700662 @Override
663 public int getMinLearnedBatteryCapacity() {
664 return mMinLearnedBatteryCapacity;
665 }
666
667 @Override
668 public int getMaxLearnedBatteryCapacity() {
669 return mMaxLearnedBatteryCapacity;
670 }
671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 public BatteryStatsImpl() {
Joe Onoratoabded112016-02-08 16:49:39 -0800673 this(new SystemClocks());
674 }
675
676 public BatteryStatsImpl(Clocks clocks) {
677 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -0700678 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700679 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -0800680 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700681 mHandler = null;
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -0700682 mPlatformIdleStateCallback = null;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -0700683 mUserInfoProvider = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -0700684 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 }
686
Joe Onoratoabded112016-02-08 16:49:39 -0800687 private void init(Clocks clocks) {
688 mClocks = clocks;
Joe Onoratoabded112016-02-08 16:49:39 -0800689 }
690
Adam Lesinski14ae39a2017-05-26 11:50:40 -0700691 public interface TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800692 void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime);
693 void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime);
694 }
695
Joe Onoratoabded112016-02-08 16:49:39 -0800696 // methods are protected not private to be VisibleForTesting
697 public static class TimeBase {
698 protected final ArrayList<TimeBaseObs> mObservers = new ArrayList<>();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800699
Joe Onoratoabded112016-02-08 16:49:39 -0800700 protected long mUptime;
701 protected long mRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800702
Joe Onoratoabded112016-02-08 16:49:39 -0800703 protected boolean mRunning;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800704
Joe Onoratoabded112016-02-08 16:49:39 -0800705 protected long mPastUptime;
706 protected long mUptimeStart;
707 protected long mPastRealtime;
708 protected long mRealtimeStart;
709 protected long mUnpluggedUptime;
710 protected long mUnpluggedRealtime;
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800711
712 public void dump(PrintWriter pw, String prefix) {
713 StringBuilder sb = new StringBuilder(128);
714 pw.print(prefix); pw.print("mRunning="); pw.println(mRunning);
715 sb.setLength(0);
716 sb.append(prefix);
717 sb.append("mUptime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700718 formatTimeMs(sb, mUptime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800719 pw.println(sb.toString());
720 sb.setLength(0);
721 sb.append(prefix);
722 sb.append("mRealtime=");
Dianne Hackborn4590e522014-03-24 13:36:46 -0700723 formatTimeMs(sb, mRealtime / 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800724 pw.println(sb.toString());
725 sb.setLength(0);
726 sb.append(prefix);
727 sb.append("mPastUptime=");
728 formatTimeMs(sb, mPastUptime / 1000); sb.append("mUptimeStart=");
729 formatTimeMs(sb, mUptimeStart / 1000);
730 sb.append("mUnpluggedUptime="); formatTimeMs(sb, mUnpluggedUptime / 1000);
731 pw.println(sb.toString());
732 sb.setLength(0);
733 sb.append(prefix);
734 sb.append("mPastRealtime=");
735 formatTimeMs(sb, mPastRealtime / 1000); sb.append("mRealtimeStart=");
736 formatTimeMs(sb, mRealtimeStart / 1000);
737 sb.append("mUnpluggedRealtime="); formatTimeMs(sb, mUnpluggedRealtime / 1000);
738 pw.println(sb.toString());
739 }
740
741 public void add(TimeBaseObs observer) {
742 mObservers.add(observer);
743 }
744
745 public void remove(TimeBaseObs observer) {
746 if (!mObservers.remove(observer)) {
747 Slog.wtf(TAG, "Removed unknown observer: " + observer);
748 }
749 }
750
Joe Onoratoabded112016-02-08 16:49:39 -0800751 public boolean hasObserver(TimeBaseObs observer) {
752 return mObservers.contains(observer);
753 }
754
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800755 public void init(long uptime, long realtime) {
756 mRealtime = 0;
757 mUptime = 0;
758 mPastUptime = 0;
759 mPastRealtime = 0;
760 mUptimeStart = uptime;
761 mRealtimeStart = realtime;
762 mUnpluggedUptime = getUptime(mUptimeStart);
763 mUnpluggedRealtime = getRealtime(mRealtimeStart);
764 }
765
766 public void reset(long uptime, long realtime) {
767 if (!mRunning) {
768 mPastUptime = 0;
769 mPastRealtime = 0;
770 } else {
771 mUptimeStart = uptime;
772 mRealtimeStart = realtime;
Joe Onoratoabded112016-02-08 16:49:39 -0800773 // TODO: Since mUptimeStart was just reset and we are running, getUptime will
774 // just return mPastUptime. Also, are we sure we don't want to reset that?
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800775 mUnpluggedUptime = getUptime(uptime);
Joe Onoratoabded112016-02-08 16:49:39 -0800776 // TODO: likewise.
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800777 mUnpluggedRealtime = getRealtime(realtime);
778 }
779 }
780
781 public long computeUptime(long curTime, int which) {
782 switch (which) {
783 case STATS_SINCE_CHARGED:
784 return mUptime + getUptime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800785 case STATS_CURRENT:
786 return getUptime(curTime);
787 case STATS_SINCE_UNPLUGGED:
788 return getUptime(curTime) - mUnpluggedUptime;
789 }
790 return 0;
791 }
792
793 public long computeRealtime(long curTime, int which) {
794 switch (which) {
795 case STATS_SINCE_CHARGED:
796 return mRealtime + getRealtime(curTime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800797 case STATS_CURRENT:
798 return getRealtime(curTime);
799 case STATS_SINCE_UNPLUGGED:
800 return getRealtime(curTime) - mUnpluggedRealtime;
801 }
802 return 0;
803 }
804
805 public long getUptime(long curTime) {
806 long time = mPastUptime;
807 if (mRunning) {
808 time += curTime - mUptimeStart;
809 }
810 return time;
811 }
812
813 public long getRealtime(long curTime) {
814 long time = mPastRealtime;
815 if (mRunning) {
816 time += curTime - mRealtimeStart;
817 }
818 return time;
819 }
820
821 public long getUptimeStart() {
822 return mUptimeStart;
823 }
824
825 public long getRealtimeStart() {
826 return mRealtimeStart;
827 }
828
829 public boolean isRunning() {
830 return mRunning;
831 }
832
833 public boolean setRunning(boolean running, long uptime, long realtime) {
834 if (mRunning != running) {
835 mRunning = running;
836 if (running) {
837 mUptimeStart = uptime;
838 mRealtimeStart = realtime;
839 long batteryUptime = mUnpluggedUptime = getUptime(uptime);
840 long batteryRealtime = mUnpluggedRealtime = getRealtime(realtime);
841
842 for (int i = mObservers.size() - 1; i >= 0; i--) {
843 mObservers.get(i).onTimeStarted(realtime, batteryUptime, batteryRealtime);
844 }
845 } else {
846 mPastUptime += uptime - mUptimeStart;
847 mPastRealtime += realtime - mRealtimeStart;
848
849 long batteryUptime = getUptime(uptime);
850 long batteryRealtime = getRealtime(realtime);
851
852 for (int i = mObservers.size() - 1; i >= 0; i--) {
853 mObservers.get(i).onTimeStopped(realtime, batteryUptime, batteryRealtime);
854 }
855 }
856 return true;
857 }
858 return false;
859 }
860
861 public void readSummaryFromParcel(Parcel in) {
862 mUptime = in.readLong();
863 mRealtime = in.readLong();
864 }
865
866 public void writeSummaryToParcel(Parcel out, long uptime, long realtime) {
867 out.writeLong(computeUptime(uptime, STATS_SINCE_CHARGED));
868 out.writeLong(computeRealtime(realtime, STATS_SINCE_CHARGED));
869 }
870
871 public void readFromParcel(Parcel in) {
872 mRunning = false;
873 mUptime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800874 mPastUptime = in.readLong();
875 mUptimeStart = in.readLong();
Dianne Hackbornef640cd2014-03-25 14:41:05 -0700876 mRealtime = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800877 mPastRealtime = in.readLong();
878 mRealtimeStart = in.readLong();
879 mUnpluggedUptime = in.readLong();
880 mUnpluggedRealtime = in.readLong();
881 }
882
883 public void writeToParcel(Parcel out, long uptime, long realtime) {
884 final long runningUptime = getUptime(uptime);
885 final long runningRealtime = getRealtime(realtime);
886 out.writeLong(mUptime);
887 out.writeLong(runningUptime);
888 out.writeLong(mUptimeStart);
Dianne Hackbornef640cd2014-03-25 14:41:05 -0700889 out.writeLong(mRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800890 out.writeLong(runningRealtime);
891 out.writeLong(mRealtimeStart);
892 out.writeLong(mUnpluggedUptime);
893 out.writeLong(mUnpluggedRealtime);
894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 /**
Dianne Hackborn617f8772009-03-31 15:04:46 -0700898 * State for keeping track of counting information.
899 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800900 public static class Counter extends BatteryStats.Counter implements TimeBaseObs {
Christopher Tate4cee7252010-03-19 14:50:40 -0700901 final AtomicInteger mCount = new AtomicInteger();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800902 final TimeBase mTimeBase;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700903 int mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700904 int mUnpluggedCount;
905 int mPluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700906
Bookatz8c6f3c52017-05-24 12:00:17 -0700907 public Counter(TimeBase timeBase, Parcel in) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800908 mTimeBase = timeBase;
Christopher Tate4cee7252010-03-19 14:50:40 -0700909 mPluggedCount = in.readInt();
910 mCount.set(mPluggedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700911 mLoadedCount = in.readInt();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700912 mUnpluggedCount = in.readInt();
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800913 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700914 }
915
Bookatz8c6f3c52017-05-24 12:00:17 -0700916 public Counter(TimeBase timeBase) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800917 mTimeBase = timeBase;
918 timeBase.add(this);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700919 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700920
Dianne Hackborn617f8772009-03-31 15:04:46 -0700921 public void writeToParcel(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700922 out.writeInt(mCount.get());
Dianne Hackborn617f8772009-03-31 15:04:46 -0700923 out.writeInt(mLoadedCount);
Dianne Hackborn617f8772009-03-31 15:04:46 -0700924 out.writeInt(mUnpluggedCount);
925 }
926
Bookatz8c6f3c52017-05-24 12:00:17 -0700927 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800928 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700929 mUnpluggedCount = mPluggedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700930 }
931
Bookatz8c6f3c52017-05-24 12:00:17 -0700932 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800933 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700934 mPluggedCount = mCount.get();
Dianne Hackborn617f8772009-03-31 15:04:46 -0700935 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700936
Dianne Hackborn617f8772009-03-31 15:04:46 -0700937 /**
938 * Writes a possibly null Counter to a Parcel.
939 *
940 * @param out the Parcel to be written to.
941 * @param counter a Counter, or null.
942 */
943 public static void writeCounterToParcel(Parcel out, Counter counter) {
944 if (counter == null) {
945 out.writeInt(0); // indicates null
946 return;
947 }
948 out.writeInt(1); // indicates non-null
949
950 counter.writeToParcel(out);
951 }
952
953 @Override
Evan Millarc64edde2009-04-18 12:26:32 -0700954 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -0700955 int val = mCount.get();
956 if (which == STATS_SINCE_UNPLUGGED) {
957 val -= mUnpluggedCount;
958 } else if (which != STATS_SINCE_CHARGED) {
959 val -= mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -0700960 }
961
962 return val;
963 }
964
965 public void logState(Printer pw, String prefix) {
Christopher Tate4cee7252010-03-19 14:50:40 -0700966 pw.println(prefix + "mCount=" + mCount.get()
Bookatz8c6f3c52017-05-24 12:00:17 -0700967 + " mLoadedCount=" + mLoadedCount
Dianne Hackborn617f8772009-03-31 15:04:46 -0700968 + " mUnpluggedCount=" + mUnpluggedCount
969 + " mPluggedCount=" + mPluggedCount);
970 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700971
Bookatz8c6f3c52017-05-24 12:00:17 -0700972 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
973 public void stepAtomic() {
974 if (mTimeBase.isRunning()) {
975 mCount.incrementAndGet();
976 }
Dianne Hackborn617f8772009-03-31 15:04:46 -0700977 }
978
Bookatz4ebc0642017-05-11 12:21:19 -0700979 void addAtomic(int delta) {
Bookatz8c6f3c52017-05-24 12:00:17 -0700980 if (mTimeBase.isRunning()) {
981 mCount.addAndGet(delta);
982 }
Bookatz4ebc0642017-05-11 12:21:19 -0700983 }
984
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700985 /**
986 * Clear state of this counter.
987 */
988 void reset(boolean detachIfReset) {
989 mCount.set(0);
Bookatz8c6f3c52017-05-24 12:00:17 -0700990 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700991 if (detachIfReset) {
992 detach();
993 }
994 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700995
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700996 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -0800997 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -0700998 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -0700999
Bookatz8c6f3c52017-05-24 12:00:17 -07001000 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1001 public void writeSummaryFromParcelLocked(Parcel out) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001002 int count = mCount.get();
1003 out.writeInt(count);
Dianne Hackborn617f8772009-03-31 15:04:46 -07001004 }
1005
Bookatz8c6f3c52017-05-24 12:00:17 -07001006 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
1007 public void readSummaryFromParcelLocked(Parcel in) {
Christopher Tate4cee7252010-03-19 14:50:40 -07001008 mLoadedCount = in.readInt();
1009 mCount.set(mLoadedCount);
Christopher Tate4cee7252010-03-19 14:50:40 -07001010 mUnpluggedCount = mPluggedCount = mLoadedCount;
Dianne Hackborn617f8772009-03-31 15:04:46 -07001011 }
1012 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07001013
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001014 @VisibleForTesting
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001015 public static class LongSamplingCounterArray extends LongCounterArray implements TimeBaseObs {
1016 final TimeBase mTimeBase;
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001017 public long[] mCounts;
1018 public long[] mLoadedCounts;
1019 public long[] mUnpluggedCounts;
1020 public long[] mPluggedCounts;
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001021
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001022 private LongSamplingCounterArray(TimeBase timeBase, Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001023 mTimeBase = timeBase;
1024 mPluggedCounts = in.createLongArray();
1025 mCounts = copyArray(mPluggedCounts, mCounts);
1026 mLoadedCounts = in.createLongArray();
1027 mUnpluggedCounts = in.createLongArray();
1028 timeBase.add(this);
1029 }
1030
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001031 public LongSamplingCounterArray(TimeBase timeBase) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001032 mTimeBase = timeBase;
1033 timeBase.add(this);
1034 }
1035
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001036 private void writeToParcel(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001037 out.writeLongArray(mCounts);
1038 out.writeLongArray(mLoadedCounts);
1039 out.writeLongArray(mUnpluggedCounts);
1040 }
1041
1042 @Override
1043 public void onTimeStarted(long elapsedRealTime, long baseUptime, long baseRealtime) {
1044 mUnpluggedCounts = copyArray(mPluggedCounts, mUnpluggedCounts);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001045 }
1046
1047 @Override
1048 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1049 mPluggedCounts = copyArray(mCounts, mPluggedCounts);
1050 }
1051
1052 @Override
1053 public long[] getCountsLocked(int which) {
1054 long[] val = copyArray(mTimeBase.isRunning() ? mCounts : mPluggedCounts, null);
1055 if (which == STATS_SINCE_UNPLUGGED) {
1056 subtract(val, mUnpluggedCounts);
1057 } else if (which != STATS_SINCE_CHARGED) {
1058 subtract(val, mLoadedCounts);
1059 }
1060 return val;
1061 }
1062
1063 @Override
1064 public void logState(Printer pw, String prefix) {
1065 pw.println(prefix + "mCounts=" + Arrays.toString(mCounts)
1066 + " mLoadedCounts=" + Arrays.toString(mLoadedCounts)
1067 + " mUnpluggedCounts=" + Arrays.toString(mUnpluggedCounts)
1068 + " mPluggedCounts=" + Arrays.toString(mPluggedCounts));
1069 }
1070
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001071 public void addCountLocked(long[] counts) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001072 if (counts == null) {
1073 return;
1074 }
Bookatz8c6f3c52017-05-24 12:00:17 -07001075 if (mTimeBase.isRunning()) {
1076 if (mCounts == null) {
1077 mCounts = new long[counts.length];
1078 }
1079 for (int i = 0; i < counts.length; ++i) {
1080 mCounts[i] += counts[i];
1081 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001082 }
1083 }
1084
Sudheer Shankab8ad5942017-08-08 12:16:09 -07001085 public int getSize() {
1086 return mCounts == null ? 0 : mCounts.length;
1087 }
1088
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001089 /**
1090 * Clear state of this counter.
1091 */
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001092 public void reset(boolean detachIfReset) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001093 fillArray(mCounts, 0);
1094 fillArray(mLoadedCounts, 0);
1095 fillArray(mPluggedCounts, 0);
1096 fillArray(mUnpluggedCounts, 0);
1097 if (detachIfReset) {
1098 detach();
1099 }
1100 }
1101
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001102 public void detach() {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001103 mTimeBase.remove(this);
1104 }
1105
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001106 private void writeSummaryToParcelLocked(Parcel out) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001107 out.writeLongArray(mCounts);
1108 }
1109
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001110 private void readSummaryFromParcelLocked(Parcel in) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001111 mCounts = in.createLongArray();
1112 mLoadedCounts = copyArray(mCounts, mLoadedCounts);
1113 mUnpluggedCounts = copyArray(mCounts, mUnpluggedCounts);
1114 mPluggedCounts = copyArray(mCounts, mPluggedCounts);
1115 }
1116
Sudheer Shanka59f5c002017-05-15 10:57:15 -07001117 public static void writeToParcel(Parcel out, LongSamplingCounterArray counterArray) {
1118 if (counterArray != null) {
1119 out.writeInt(1);
1120 counterArray.writeToParcel(out);
1121 } else {
1122 out.writeInt(0);
1123 }
1124 }
1125
1126 public static LongSamplingCounterArray readFromParcel(Parcel in, TimeBase timeBase) {
1127 if (in.readInt() != 0) {
1128 return new LongSamplingCounterArray(timeBase, in);
1129 } else {
1130 return null;
1131 }
1132 }
1133
1134 public static void writeSummaryToParcelLocked(Parcel out,
1135 LongSamplingCounterArray counterArray) {
1136 if (counterArray != null) {
1137 out.writeInt(1);
1138 counterArray.writeSummaryToParcelLocked(out);
1139 } else {
1140 out.writeInt(0);
1141 }
1142 }
1143
1144 public static LongSamplingCounterArray readSummaryFromParcelLocked(Parcel in,
1145 TimeBase timeBase) {
1146 if (in.readInt() != 0) {
1147 final LongSamplingCounterArray counterArray
1148 = new LongSamplingCounterArray(timeBase);
1149 counterArray.readSummaryFromParcelLocked(in);
1150 return counterArray;
1151 } else {
1152 return null;
1153 }
1154 }
1155
Bookatz8c6f3c52017-05-24 12:00:17 -07001156 private static void fillArray(long[] a, long val) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001157 if (a != null) {
1158 Arrays.fill(a, val);
1159 }
1160 }
1161
Bookatz8c6f3c52017-05-24 12:00:17 -07001162 private static void subtract(@NonNull long[] val, long[] toSubtract) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001163 if (toSubtract == null) {
1164 return;
1165 }
1166 for (int i = 0; i < val.length; i++) {
1167 val[i] -= toSubtract[i];
1168 }
1169 }
1170
Bookatz8c6f3c52017-05-24 12:00:17 -07001171 private static long[] copyArray(long[] src, long[] dest) {
Sudheer Shanka9b735c52017-05-09 18:26:18 -07001172 if (src == null) {
1173 return null;
1174 } else {
1175 if (dest == null) {
1176 dest = new long[src.length];
1177 }
1178 System.arraycopy(src, 0, dest, 0, src.length);
1179 return dest;
1180 }
1181 }
1182 }
1183
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001184 public static class LongSamplingCounter extends LongCounter implements TimeBaseObs {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001185 final TimeBase mTimeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001186 long mCount;
1187 long mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001188 long mUnpluggedCount;
1189 long mPluggedCount;
1190
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001191 LongSamplingCounter(TimeBase timeBase, Parcel in) {
1192 mTimeBase = timeBase;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001193 mPluggedCount = in.readLong();
1194 mCount = mPluggedCount;
1195 mLoadedCount = in.readLong();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001196 mUnpluggedCount = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001197 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001198 }
1199
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001200 LongSamplingCounter(TimeBase timeBase) {
1201 mTimeBase = timeBase;
1202 timeBase.add(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001203 }
1204
1205 public void writeToParcel(Parcel out) {
1206 out.writeLong(mCount);
1207 out.writeLong(mLoadedCount);
1208 out.writeLong(mUnpluggedCount);
1209 }
1210
1211 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001212 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001213 mUnpluggedCount = mPluggedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001214 }
1215
1216 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001217 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001218 mPluggedCount = mCount;
1219 }
1220
1221 public long getCountLocked(int which) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001222 long val = mTimeBase.isRunning() ? mCount : mPluggedCount;
Dianne Hackborn4590e522014-03-24 13:36:46 -07001223 if (which == STATS_SINCE_UNPLUGGED) {
1224 val -= mUnpluggedCount;
1225 } else if (which != STATS_SINCE_CHARGED) {
1226 val -= mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001227 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001228 return val;
1229 }
1230
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001231 @Override
1232 public void logState(Printer pw, String prefix) {
1233 pw.println(prefix + "mCount=" + mCount
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001234 + " mLoadedCount=" + mLoadedCount
Dianne Hackborna1bd7922014-03-21 11:07:11 -07001235 + " mUnpluggedCount=" + mUnpluggedCount
1236 + " mPluggedCount=" + mPluggedCount);
1237 }
1238
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001239 void addCountLocked(long count) {
Bookatz8c6f3c52017-05-24 12:00:17 -07001240 if (mTimeBase.isRunning()) {
1241 mCount += count;
1242 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001243 }
1244
1245 /**
1246 * Clear state of this counter.
1247 */
1248 void reset(boolean detachIfReset) {
1249 mCount = 0;
Adam Lesinski3ee3f632016-06-08 13:55:55 -07001250 mLoadedCount = mPluggedCount = mUnpluggedCount = 0;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001251 if (detachIfReset) {
1252 detach();
1253 }
1254 }
1255
1256 void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001257 mTimeBase.remove(this);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001258 }
1259
1260 void writeSummaryFromParcelLocked(Parcel out) {
1261 out.writeLong(mCount);
1262 }
1263
1264 void readSummaryFromParcelLocked(Parcel in) {
1265 mLoadedCount = in.readLong();
1266 mCount = mLoadedCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07001267 mUnpluggedCount = mPluggedCount = mLoadedCount;
1268 }
1269 }
1270
Dianne Hackborn617f8772009-03-31 15:04:46 -07001271 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 * State for keeping track of timing information.
1273 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001274 public static abstract class Timer extends BatteryStats.Timer implements TimeBaseObs {
Joe Onoratoabded112016-02-08 16:49:39 -08001275 protected final Clocks mClocks;
1276 protected final int mType;
1277 protected final TimeBase mTimeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001278
Joe Onoratoabded112016-02-08 16:49:39 -08001279 protected int mCount;
1280 protected int mLoadedCount;
1281 protected int mLastCount;
1282 protected int mUnpluggedCount;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 // Times are in microseconds for better accuracy when dividing by the
1285 // lock count, and are in "battery realtime" units.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 /**
1288 * The total time we have accumulated since the start of the original
1289 * boot, to the last time something interesting happened in the
1290 * current run.
1291 */
Joe Onoratoabded112016-02-08 16:49:39 -08001292 protected long mTotalTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 /**
1295 * The total time we loaded for the previous runs. Subtract this from
1296 * mTotalTime to find the time for the current run of the system.
1297 */
Joe Onoratoabded112016-02-08 16:49:39 -08001298 protected long mLoadedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 /**
1301 * The run time of the last run of the system, as loaded from the
1302 * saved data.
1303 */
Joe Onoratoabded112016-02-08 16:49:39 -08001304 protected long mLastTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 /**
1307 * The value of mTotalTime when unplug() was last called. Subtract
1308 * this from mTotalTime to find the time since the last unplug from
1309 * power.
1310 */
Joe Onoratoabded112016-02-08 16:49:39 -08001311 protected long mUnpluggedTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001312
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001313 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07001314 * The total time this timer has been running until the latest mark has been set.
1315 * Subtract this from mTotalTime to get the time spent running since the mark was set.
1316 */
Joe Onoratoabded112016-02-08 16:49:39 -08001317 protected long mTimeBeforeMark;
Adam Lesinskie08af192015-03-25 16:42:59 -07001318
1319 /**
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001320 * Constructs from a parcel.
1321 * @param type
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001322 * @param timeBase
Amith Yamasani244fa5c2009-05-22 14:36:07 -07001323 * @param in
1324 */
Joe Onoratoabded112016-02-08 16:49:39 -08001325 public Timer(Clocks clocks, int type, TimeBase timeBase, Parcel in) {
1326 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001328 mTimeBase = timeBase;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 mCount = in.readInt();
1331 mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001332 mLastCount = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 mUnpluggedCount = in.readInt();
1334 mTotalTime = in.readLong();
1335 mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001336 mLastTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 mUnpluggedTime = in.readLong();
Adam Lesinskie08af192015-03-25 16:42:59 -07001338 mTimeBeforeMark = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001339 timeBase.add(this);
Dianne Hackborn29325132014-05-21 15:01:03 -07001340 if (DEBUG) Log.i(TAG, "**** READ TIMER #" + mType + ": mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 }
1342
Joe Onoratoabded112016-02-08 16:49:39 -08001343 public Timer(Clocks clocks, int type, TimeBase timeBase) {
1344 mClocks = clocks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 mType = type;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001346 mTimeBase = timeBase;
1347 timeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 }
Evan Millarc64edde2009-04-18 12:26:32 -07001349
1350 protected abstract long computeRunTimeLocked(long curBatteryRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001351
Evan Millarc64edde2009-04-18 12:26:32 -07001352 protected abstract int computeCurrentCountLocked();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001353
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001354 /**
1355 * Clear state of this timer. Returns true if the timer is inactive
1356 * so can be completely dropped.
1357 */
Joe Onoratoabded112016-02-08 16:49:39 -08001358 public boolean reset(boolean detachIfReset) {
Adam Lesinskie08af192015-03-25 16:42:59 -07001359 mTotalTime = mLoadedTime = mLastTime = mTimeBeforeMark = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001360 mCount = mLoadedCount = mLastCount = 0;
1361 if (detachIfReset) {
1362 detach();
1363 }
1364 return true;
1365 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001366
Joe Onoratoabded112016-02-08 16:49:39 -08001367 public void detach() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001368 mTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001369 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001370
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001371 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn29325132014-05-21 15:01:03 -07001372 if (DEBUG) Log.i(TAG, "**** WRITING TIMER #" + mType + ": mTotalTime="
1373 + computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
Adam Lesinski98f0d462016-04-19 16:46:20 -07001374 out.writeInt(computeCurrentCountLocked());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 out.writeInt(mLoadedCount);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 out.writeInt(mUnpluggedCount);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001377 out.writeLong(computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 out.writeLong(mLoadedTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 out.writeLong(mUnpluggedTime);
Adam Lesinskie08af192015-03-25 16:42:59 -07001380 out.writeLong(mTimeBeforeMark);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 }
1382
Adam Lesinskie08af192015-03-25 16:42:59 -07001383 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001384 public void onTimeStarted(long elapsedRealtime, long timeBaseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001386 Log.v(TAG, "unplug #" + mType + ": realtime=" + baseRealtime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 + " old mUnpluggedTime=" + mUnpluggedTime
1388 + " old mUnpluggedCount=" + mUnpluggedCount);
1389 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001390 mUnpluggedTime = computeRunTimeLocked(baseRealtime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001391 mUnpluggedCount = computeCurrentCountLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 if (DEBUG && mType < 0) {
1393 Log.v(TAG, "unplug #" + mType
1394 + ": new mUnpluggedTime=" + mUnpluggedTime
1395 + " new mUnpluggedCount=" + mUnpluggedCount);
1396 }
1397 }
1398
Adam Lesinskie08af192015-03-25 16:42:59 -07001399 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001400 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07001401 if (DEBUG && mType < 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001402 Log.v(TAG, "plug #" + mType + ": realtime=" + baseRealtime
Evan Millarc64edde2009-04-18 12:26:32 -07001403 + " old mTotalTime=" + mTotalTime);
1404 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001405 mTotalTime = computeRunTimeLocked(baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001406 mCount = computeCurrentCountLocked();
1407 if (DEBUG && mType < 0) {
1408 Log.v(TAG, "plug #" + mType
1409 + ": new mTotalTime=" + mTotalTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 }
1411 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 /**
1414 * Writes a possibly null Timer to a Parcel.
1415 *
1416 * @param out the Parcel to be written to.
1417 * @param timer a Timer, or null.
1418 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001419 public static void writeTimerToParcel(Parcel out, Timer timer, long elapsedRealtimeUs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 if (timer == null) {
1421 out.writeInt(0); // indicates null
1422 return;
1423 }
1424 out.writeInt(1); // indicates non-null
1425
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001426 timer.writeToParcel(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428
1429 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001430 public long getTotalTimeLocked(long elapsedRealtimeUs, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001431 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1432 if (which == STATS_SINCE_UNPLUGGED) {
1433 val -= mUnpluggedTime;
1434 } else if (which != STATS_SINCE_CHARGED) {
1435 val -= mLoadedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 }
1437
1438 return val;
1439 }
1440
1441 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001442 public int getCountLocked(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07001443 int val = computeCurrentCountLocked();
1444 if (which == STATS_SINCE_UNPLUGGED) {
1445 val -= mUnpluggedCount;
1446 } else if (which != STATS_SINCE_CHARGED) {
1447 val -= mLoadedCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 }
1449
1450 return val;
1451 }
1452
Adam Lesinskie08af192015-03-25 16:42:59 -07001453 @Override
1454 public long getTimeSinceMarkLocked(long elapsedRealtimeUs) {
1455 long val = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1456 return val - mTimeBeforeMark;
1457 }
1458
1459 @Override
Dianne Hackborn627bba72009-03-24 22:32:56 -07001460 public void logState(Printer pw, String prefix) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07001461 pw.println(prefix + "mCount=" + mCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 + " mLoadedCount=" + mLoadedCount + " mLastCount=" + mLastCount
1463 + " mUnpluggedCount=" + mUnpluggedCount);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001464 pw.println(prefix + "mTotalTime=" + mTotalTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 + " mLoadedTime=" + mLoadedTime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07001466 pw.println(prefix + "mLastTime=" + mLastTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 + " mUnpluggedTime=" + mUnpluggedTime);
Evan Millarc64edde2009-04-18 12:26:32 -07001468 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001469
1470
Joe Onoratoabded112016-02-08 16:49:39 -08001471 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001472 long runTime = computeRunTimeLocked(mTimeBase.getRealtime(elapsedRealtimeUs));
1473 out.writeLong(runTime);
Adam Lesinski98f0d462016-04-19 16:46:20 -07001474 out.writeInt(computeCurrentCountLocked());
Evan Millarc64edde2009-04-18 12:26:32 -07001475 }
1476
Joe Onoratoabded112016-02-08 16:49:39 -08001477 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07001478 // Multiply by 1000 for backwards compatibility
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001479 mTotalTime = mLoadedTime = in.readLong();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001480 mLastTime = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001481 mUnpluggedTime = mTotalTime;
1482 mCount = mLoadedCount = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07001483 mLastCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001484 mUnpluggedCount = mCount;
Adam Lesinskie08af192015-03-25 16:42:59 -07001485
1486 // When reading the summary, we set the mark to be the latest information.
1487 mTimeBeforeMark = mTotalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001488 }
1489 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001490
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001491 /**
1492 * A counter meant to accept monotonically increasing values to its {@link #update(long, int)}
1493 * method. The state of the timer according to its {@link TimeBase} will determine how much
1494 * of the value is recorded.
1495 *
1496 * If the value being recorded resets, {@link #endSample()} can be called in order to
1497 * account for the change. If the value passed in to {@link #update(long, int)} decreased
1498 * between calls, the {@link #endSample()} is automatically called and the new value is
1499 * expected to increase monotonically from that point on.
1500 */
Joe Onoratoabded112016-02-08 16:49:39 -08001501 public static class SamplingTimer extends Timer {
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001502
Evan Millarc64edde2009-04-18 12:26:32 -07001503 /**
1504 * The most recent reported count from /proc/wakelocks.
1505 */
1506 int mCurrentReportedCount;
1507
1508 /**
1509 * The reported count from /proc/wakelocks when unplug() was last
1510 * called.
1511 */
1512 int mUnpluggedReportedCount;
1513
1514 /**
1515 * The most recent reported total_time from /proc/wakelocks.
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001516 */
Evan Millarc64edde2009-04-18 12:26:32 -07001517 long mCurrentReportedTotalTime;
1518
1519
1520 /**
1521 * The reported total_time from /proc/wakelocks when unplug() was last
1522 * called.
1523 */
1524 long mUnpluggedReportedTotalTime;
1525
1526 /**
1527 * Whether we are currently in a discharge cycle.
1528 */
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001529 boolean mTimeBaseRunning;
Evan Millarc64edde2009-04-18 12:26:32 -07001530
1531 /**
1532 * Whether we are currently recording reported values.
1533 */
1534 boolean mTrackingReportedValues;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001535
Evan Millarc64edde2009-04-18 12:26:32 -07001536 /*
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001537 * A sequence counter, incremented once for each update of the stats.
Evan Millarc64edde2009-04-18 12:26:32 -07001538 */
1539 int mUpdateVersion;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001540
Adam Lesinski98f0d462016-04-19 16:46:20 -07001541 @VisibleForTesting
1542 public SamplingTimer(Clocks clocks, TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08001543 super(clocks, 0, timeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -07001544 mCurrentReportedCount = in.readInt();
1545 mUnpluggedReportedCount = in.readInt();
1546 mCurrentReportedTotalTime = in.readLong();
1547 mUnpluggedReportedTotalTime = in.readLong();
1548 mTrackingReportedValues = in.readInt() == 1;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001549 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001550 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001551
Adam Lesinski98f0d462016-04-19 16:46:20 -07001552 @VisibleForTesting
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001553 public SamplingTimer(Clocks clocks, TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08001554 super(clocks, 0, timeBase);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001555 mTrackingReportedValues = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001556 mTimeBaseRunning = timeBase.isRunning();
Evan Millarc64edde2009-04-18 12:26:32 -07001557 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001558
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001559 /**
1560 * Ends the current sample, allowing subsequent values to {@link #update(long, int)} to
1561 * be less than the values used for a previous invocation.
1562 */
1563 public void endSample() {
1564 mTotalTime = computeRunTimeLocked(0 /* unused by us */);
1565 mCount = computeCurrentCountLocked();
1566 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime = 0;
1567 mUnpluggedReportedCount = mCurrentReportedCount = 0;
Evan Millarc64edde2009-04-18 12:26:32 -07001568 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001569
Evan Millarc64edde2009-04-18 12:26:32 -07001570 public void setUpdateVersion(int version) {
1571 mUpdateVersion = version;
1572 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001573
Evan Millarc64edde2009-04-18 12:26:32 -07001574 public int getUpdateVersion() {
1575 return mUpdateVersion;
1576 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001577
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001578 /**
1579 * Updates the current recorded values. These are meant to be monotonically increasing
1580 * and cumulative. If you are dealing with deltas, use {@link #add(long, int)}.
1581 *
1582 * If the values being recorded have been reset, the monotonically increasing requirement
1583 * will be broken. In this case, {@link #endSample()} is automatically called and
1584 * the total value of totalTime and count are recorded, starting a new monotonically
1585 * increasing sample.
1586 *
1587 * @param totalTime total time of sample in microseconds.
1588 * @param count total number of times the event being sampled occurred.
1589 */
1590 public void update(long totalTime, int count) {
1591 if (mTimeBaseRunning && !mTrackingReportedValues) {
Evan Millarc64edde2009-04-18 12:26:32 -07001592 // Updating the reported value for the first time.
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001593 mUnpluggedReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001594 mUnpluggedReportedCount = count;
Evan Millarc64edde2009-04-18 12:26:32 -07001595 }
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001596
1597 mTrackingReportedValues = true;
1598
1599 if (totalTime < mCurrentReportedTotalTime || count < mCurrentReportedCount) {
1600 endSample();
1601 }
1602
1603 mCurrentReportedTotalTime = totalTime;
Evan Millarc64edde2009-04-18 12:26:32 -07001604 mCurrentReportedCount = count;
1605 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001606
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001607 /**
1608 * Adds deltaTime and deltaCount to the current sample.
1609 *
1610 * @param deltaTime additional time recorded since the last sampled event, in microseconds.
1611 * @param deltaCount additional number of times the event being sampled occurred.
1612 */
1613 public void add(long deltaTime, int deltaCount) {
1614 update(mCurrentReportedTotalTime + deltaTime, mCurrentReportedCount + deltaCount);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07001615 }
1616
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001617 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001618 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
1619 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Evan Millarc64edde2009-04-18 12:26:32 -07001620 if (mTrackingReportedValues) {
1621 mUnpluggedReportedTotalTime = mCurrentReportedTotalTime;
1622 mUnpluggedReportedCount = mCurrentReportedCount;
1623 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001624 mTimeBaseRunning = true;
Evan Millarc64edde2009-04-18 12:26:32 -07001625 }
1626
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001627 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001628 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
1629 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
1630 mTimeBaseRunning = false;
Evan Millarc64edde2009-04-18 12:26:32 -07001631 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001632
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001633 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001634 public void logState(Printer pw, String prefix) {
1635 super.logState(pw, prefix);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001636 pw.println(prefix + "mCurrentReportedCount=" + mCurrentReportedCount
Evan Millarc64edde2009-04-18 12:26:32 -07001637 + " mUnpluggedReportedCount=" + mUnpluggedReportedCount
1638 + " mCurrentReportedTotalTime=" + mCurrentReportedTotalTime
1639 + " mUnpluggedReportedTotalTime=" + mUnpluggedReportedTotalTime);
1640 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001641
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001642 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001643 protected long computeRunTimeLocked(long curBatteryRealtime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001644 return mTotalTime + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001645 ? mCurrentReportedTotalTime - mUnpluggedReportedTotalTime : 0);
1646 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001647
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001648 @Override
Evan Millarc64edde2009-04-18 12:26:32 -07001649 protected int computeCurrentCountLocked() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001650 return mCount + (mTimeBaseRunning && mTrackingReportedValues
Evan Millarc64edde2009-04-18 12:26:32 -07001651 ? mCurrentReportedCount - mUnpluggedReportedCount : 0);
1652 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001653
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001654 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001655 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1656 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07001657 out.writeInt(mCurrentReportedCount);
1658 out.writeInt(mUnpluggedReportedCount);
1659 out.writeLong(mCurrentReportedTotalTime);
1660 out.writeLong(mUnpluggedReportedTotalTime);
1661 out.writeInt(mTrackingReportedValues ? 1 : 0);
1662 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001663
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001664 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001665 public boolean reset(boolean detachIfReset) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001666 super.reset(detachIfReset);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07001667 mTrackingReportedValues = false;
1668 mUnpluggedReportedTotalTime = 0;
1669 mUnpluggedReportedCount = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07001670 return true;
1671 }
Evan Millarc64edde2009-04-18 12:26:32 -07001672 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07001673
Evan Millarc64edde2009-04-18 12:26:32 -07001674 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001675 * A timer that increments in batches. It does not run for durations, but just jumps
1676 * for a pre-determined amount.
1677 */
Joe Onoratoabded112016-02-08 16:49:39 -08001678 public static class BatchTimer extends Timer {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001679 final Uid mUid;
1680
1681 /**
1682 * The last time at which we updated the timer. This is in elapsed realtime microseconds.
1683 */
1684 long mLastAddedTime;
1685
1686 /**
1687 * The last duration that we added to the timer. This is in microseconds.
1688 */
1689 long mLastAddedDuration;
1690
1691 /**
1692 * Whether we are currently in a discharge cycle.
1693 */
1694 boolean mInDischarge;
1695
Joe Onoratoabded112016-02-08 16:49:39 -08001696 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase, Parcel in) {
1697 super(clocks, type, timeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001698 mUid = uid;
1699 mLastAddedTime = in.readLong();
1700 mLastAddedDuration = in.readLong();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001701 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001702 }
1703
Joe Onoratoabded112016-02-08 16:49:39 -08001704 BatchTimer(Clocks clocks, Uid uid, int type, TimeBase timeBase) {
1705 super(clocks, type, timeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001706 mUid = uid;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001707 mInDischarge = timeBase.isRunning();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001708 }
1709
1710 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001711 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1712 super.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001713 out.writeLong(mLastAddedTime);
1714 out.writeLong(mLastAddedDuration);
1715 }
1716
1717 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001718 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001719 recomputeLastDuration(mClocks.elapsedRealtime() * 1000, false);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001720 mInDischarge = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001721 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001722 }
1723
1724 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001725 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001726 recomputeLastDuration(elapsedRealtime, false);
1727 mInDischarge = true;
1728 // If we are still within the last added duration, then re-added whatever remains.
1729 if (mLastAddedTime == elapsedRealtime) {
1730 mTotalTime += mLastAddedDuration;
1731 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001732 super.onTimeStarted(elapsedRealtime, baseUptime, baseRealtime);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001733 }
1734
1735 @Override
1736 public void logState(Printer pw, String prefix) {
1737 super.logState(pw, prefix);
1738 pw.println(prefix + "mLastAddedTime=" + mLastAddedTime
1739 + " mLastAddedDuration=" + mLastAddedDuration);
1740 }
1741
1742 private long computeOverage(long curTime) {
1743 if (mLastAddedTime > 0) {
1744 return mLastTime + mLastAddedDuration - curTime;
1745 }
1746 return 0;
1747 }
1748
1749 private void recomputeLastDuration(long curTime, boolean abort) {
1750 final long overage = computeOverage(curTime);
1751 if (overage > 0) {
1752 // Aborting before the duration ran out -- roll back the remaining
1753 // duration. Only do this if currently discharging; otherwise we didn't
1754 // actually add the time.
1755 if (mInDischarge) {
1756 mTotalTime -= overage;
1757 }
1758 if (abort) {
1759 mLastAddedTime = 0;
1760 } else {
1761 mLastAddedTime = curTime;
1762 mLastAddedDuration -= overage;
1763 }
1764 }
1765 }
1766
1767 public void addDuration(BatteryStatsImpl stats, long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08001768 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001769 recomputeLastDuration(now, true);
1770 mLastAddedTime = now;
1771 mLastAddedDuration = durationMillis * 1000;
1772 if (mInDischarge) {
1773 mTotalTime += mLastAddedDuration;
1774 mCount++;
1775 }
1776 }
1777
1778 public void abortLastDuration(BatteryStatsImpl stats) {
Joe Onoratoabded112016-02-08 16:49:39 -08001779 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001780 recomputeLastDuration(now, true);
1781 }
1782
1783 @Override
1784 protected int computeCurrentCountLocked() {
1785 return mCount;
1786 }
1787
1788 @Override
1789 protected long computeRunTimeLocked(long curBatteryRealtime) {
Joe Onoratoabded112016-02-08 16:49:39 -08001790 final long overage = computeOverage(mClocks.elapsedRealtime() * 1000);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001791 if (overage > 0) {
1792 return mTotalTime = overage;
1793 }
1794 return mTotalTime;
1795 }
1796
1797 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08001798 public boolean reset(boolean detachIfReset) {
1799 final long now = mClocks.elapsedRealtime() * 1000;
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001800 recomputeLastDuration(now, true);
1801 boolean stillActive = mLastAddedTime == now;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08001802 super.reset(!stillActive && detachIfReset);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001803 return !stillActive;
1804 }
1805 }
1806
Joe Onorato92fd23f2016-07-25 11:18:42 -07001807
1808 /**
1809 * A StopwatchTimer that also tracks the total and max individual
1810 * time spent active according to the given timebase. Whereas
1811 * StopwatchTimer apportions the time amongst all in the pool,
1812 * the total and max durations are not apportioned.
1813 */
1814 public static class DurationTimer extends StopwatchTimer {
1815 /**
1816 * The time (in ms) that the timer was last acquired or the time base
1817 * last (re-)started. Increasing the nesting depth does not reset this time.
1818 *
1819 * -1 if the timer is currently not running or the time base is not running.
1820 *
1821 * If written to a parcel, the start time is reset, as is mNesting in the base class
1822 * StopwatchTimer.
1823 */
1824 long mStartTimeMs = -1;
1825
1826 /**
Bookatz867c0d72017-03-07 18:23:42 -08001827 * The longest time period (in ms) that the timer has been active. Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001828 */
1829 long mMaxDurationMs;
1830
1831 /**
Bookatz867c0d72017-03-07 18:23:42 -08001832 * The time (in ms) that that the timer has been active since most recent
1833 * stopRunningLocked() or reset(). Not pooled.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001834 */
1835 long mCurrentDurationMs;
1836
Bookatz867c0d72017-03-07 18:23:42 -08001837 /**
1838 * The total time (in ms) that that the timer has been active since most recent reset()
1839 * prior to the current startRunningLocked. This is the sum of all past currentDurations
1840 * (but not including the present currentDuration) since reset. Not pooled.
1841 */
1842 long mTotalDurationMs;
1843
Joe Onorato92fd23f2016-07-25 11:18:42 -07001844 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
1845 TimeBase timeBase, Parcel in) {
1846 super(clocks, uid, type, timerPool, timeBase, in);
1847 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08001848 mTotalDurationMs = in.readLong();
jackqdyulei610a0a02017-08-09 14:02:01 -07001849 mCurrentDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07001850 }
1851
1852 public DurationTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
1853 TimeBase timeBase) {
1854 super(clocks, uid, type, timerPool, timeBase);
1855 }
1856
1857 @Override
1858 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
1859 super.writeToParcel(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08001860 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
jackqdyulei610a0a02017-08-09 14:02:01 -07001861 out.writeLong(mTotalDurationMs);
1862 out.writeLong(getCurrentDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07001863 }
1864
1865 /**
1866 * Write the summary to the parcel.
1867 *
1868 * Since the time base is probably meaningless after we come back, reading
1869 * from this will have the effect of stopping the timer. So here all we write
Bookatz867c0d72017-03-07 18:23:42 -08001870 * is the max and total durations.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001871 */
1872 @Override
1873 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
1874 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Kweku Adams47db5a82016-12-09 19:04:50 -08001875 out.writeLong(getMaxDurationMsLocked(elapsedRealtimeUs / 1000));
Bookatz867c0d72017-03-07 18:23:42 -08001876 out.writeLong(getTotalDurationMsLocked(elapsedRealtimeUs / 1000));
Joe Onorato92fd23f2016-07-25 11:18:42 -07001877 }
1878
1879 /**
1880 * Read the summary parcel.
1881 *
1882 * Has the side effect of stopping the timer.
1883 */
1884 @Override
1885 public void readSummaryFromParcelLocked(Parcel in) {
1886 super.readSummaryFromParcelLocked(in);
1887 mMaxDurationMs = in.readLong();
Bookatz867c0d72017-03-07 18:23:42 -08001888 mTotalDurationMs = in.readLong();
Joe Onorato92fd23f2016-07-25 11:18:42 -07001889 mStartTimeMs = -1;
1890 mCurrentDurationMs = 0;
1891 }
1892
1893 /**
1894 * The TimeBase time started (again).
1895 *
1896 * If the timer is also running, store the start time.
1897 */
1898 public void onTimeStarted(long elapsedRealtimeUs, long baseUptime, long baseRealtime) {
1899 super.onTimeStarted(elapsedRealtimeUs, baseUptime, baseRealtime);
1900 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08001901 mStartTimeMs = baseRealtime / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001902 }
1903 }
1904
1905 /**
1906 * The TimeBase stopped running.
1907 *
1908 * If the timer is running, add the duration into mCurrentDurationMs.
1909 */
1910 @Override
Kweku Adams47db5a82016-12-09 19:04:50 -08001911 public void onTimeStopped(long elapsedRealtimeUs, long baseUptime, long baseRealtimeUs) {
1912 super.onTimeStopped(elapsedRealtimeUs, baseUptime, baseRealtimeUs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07001913 if (mNesting > 0) {
Kweku Adams47db5a82016-12-09 19:04:50 -08001914 // baseRealtimeUs has already been converted to the timebase's realtime.
1915 mCurrentDurationMs += (baseRealtimeUs / 1000) - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001916 }
1917 mStartTimeMs = -1;
1918 }
1919
1920 @Override
1921 public void logState(Printer pw, String prefix) {
1922 super.logState(pw, prefix);
1923 }
1924
1925 @Override
1926 public void startRunningLocked(long elapsedRealtimeMs) {
1927 super.startRunningLocked(elapsedRealtimeMs);
1928 if (mNesting == 1 && mTimeBase.isRunning()) {
1929 // Just started
Kweku Adams47db5a82016-12-09 19:04:50 -08001930 mStartTimeMs = mTimeBase.getRealtime(elapsedRealtimeMs * 1000) / 1000;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001931 }
1932 }
1933
1934 /**
1935 * Decrements the mNesting ref-count on this timer.
1936 *
1937 * If it actually stopped (mNesting went to 0), then possibly update
1938 * mMaxDuration if the current duration was the longest ever.
1939 */
1940 @Override
1941 public void stopRunningLocked(long elapsedRealtimeMs) {
Kweku Adams47db5a82016-12-09 19:04:50 -08001942 if (mNesting == 1) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07001943 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08001944 mTotalDurationMs += durationMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001945 if (durationMs > mMaxDurationMs) {
1946 mMaxDurationMs = durationMs;
1947 }
1948 mStartTimeMs = -1;
1949 mCurrentDurationMs = 0;
1950 }
Kweku Adams47db5a82016-12-09 19:04:50 -08001951 // super method decrements mNesting, which getCurrentDurationMsLocked relies on,
1952 // so call super.stopRunningLocked after calling getCurrentDurationMsLocked.
1953 super.stopRunningLocked(elapsedRealtimeMs);
Joe Onorato92fd23f2016-07-25 11:18:42 -07001954 }
1955
1956 @Override
1957 public boolean reset(boolean detachIfReset) {
1958 boolean result = super.reset(detachIfReset);
1959 mMaxDurationMs = 0;
Bookatz867c0d72017-03-07 18:23:42 -08001960 mTotalDurationMs = 0;
Joe Onorato92fd23f2016-07-25 11:18:42 -07001961 mCurrentDurationMs = 0;
1962 if (mNesting > 0) {
1963 mStartTimeMs = mTimeBase.getRealtime(mClocks.elapsedRealtime()*1000) / 1000;
1964 } else {
1965 mStartTimeMs = -1;
1966 }
1967 return result;
1968 }
1969
1970 /**
1971 * Returns the max duration that this timer has ever seen.
1972 *
1973 * Note that this time is NOT split between the timers in the timer group that
1974 * this timer is attached to. It is the TOTAL time.
1975 */
1976 @Override
1977 public long getMaxDurationMsLocked(long elapsedRealtimeMs) {
1978 if (mNesting > 0) {
1979 final long durationMs = getCurrentDurationMsLocked(elapsedRealtimeMs);
1980 if (durationMs > mMaxDurationMs) {
1981 return durationMs;
1982 }
1983 }
1984 return mMaxDurationMs;
1985 }
1986
1987 /**
1988 * Returns the time since the timer was started.
Bookatz867c0d72017-03-07 18:23:42 -08001989 * Returns 0 if the timer is not currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001990 *
1991 * Note that this time is NOT split between the timers in the timer group that
1992 * this timer is attached to. It is the TOTAL time.
jackqdyulei610a0a02017-08-09 14:02:01 -07001993 *
1994 * Note that if running timer is parceled and unparceled, this method will return
1995 * current duration value at the time of parceling even though timer may not be
1996 * currently running.
Joe Onorato92fd23f2016-07-25 11:18:42 -07001997 */
1998 @Override
1999 public long getCurrentDurationMsLocked(long elapsedRealtimeMs) {
2000 long durationMs = mCurrentDurationMs;
Kweku Adams47db5a82016-12-09 19:04:50 -08002001 if (mNesting > 0 && mTimeBase.isRunning()) {
2002 durationMs += (mTimeBase.getRealtime(elapsedRealtimeMs*1000)/1000)
2003 - mStartTimeMs;
Joe Onorato92fd23f2016-07-25 11:18:42 -07002004 }
2005 return durationMs;
2006 }
Bookatz867c0d72017-03-07 18:23:42 -08002007
2008 /**
2009 * Returns the total cumulative duration that this timer has been on since reset().
2010 * If mTimerPool == null, this should be the same
2011 * as getTotalTimeLocked(elapsedRealtimeMs*1000, STATS_SINCE_CHARGED)/1000.
2012 *
2013 * Note that this time is NOT split between the timers in the timer group that
2014 * this timer is attached to. It is the TOTAL time. For this reason, if mTimerPool != null,
2015 * the result will not be equivalent to getTotalTimeLocked.
2016 */
2017 @Override
2018 public long getTotalDurationMsLocked(long elapsedRealtimeMs) {
2019 return mTotalDurationMs + getCurrentDurationMsLocked(elapsedRealtimeMs);
2020 }
Joe Onorato92fd23f2016-07-25 11:18:42 -07002021 }
2022
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002023 /**
Evan Millarc64edde2009-04-18 12:26:32 -07002024 * State for keeping track of timing information.
2025 */
Joe Onoratoabded112016-02-08 16:49:39 -08002026 public static class StopwatchTimer extends Timer {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002027 final Uid mUid;
Evan Millarc64edde2009-04-18 12:26:32 -07002028 final ArrayList<StopwatchTimer> mTimerPool;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002029
Evan Millarc64edde2009-04-18 12:26:32 -07002030 int mNesting;
2031
Evan Millarc64edde2009-04-18 12:26:32 -07002032 /**
2033 * The last time at which we updated the timer. If mNesting is > 0,
2034 * subtract this from the current battery time to find the amount of
2035 * time we have been running since we last computed an update.
2036 */
2037 long mUpdateTime;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002038
Evan Millarc64edde2009-04-18 12:26:32 -07002039 /**
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002040 * The total time at which the timer was acquired, to determine if it
Bookatzceebafe2017-04-06 11:59:13 -07002041 * was actually held for an interesting duration. If time base was not running when timer
2042 * was acquired, will be -1.
Evan Millarc64edde2009-04-18 12:26:32 -07002043 */
Bookatzceebafe2017-04-06 11:59:13 -07002044 long mAcquireTime = -1;
Evan Millarc64edde2009-04-18 12:26:32 -07002045
Amith Yamasanif37447b2009-10-08 18:28:01 -07002046 long mTimeout;
2047
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002048 /**
2049 * For partial wake locks, keep track of whether we are in the list
2050 * to consume CPU cycles.
2051 */
Sudheer Shanka38383232017-07-25 09:55:03 -07002052 @VisibleForTesting
2053 public boolean mInList;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002054
Joe Onoratoabded112016-02-08 16:49:39 -08002055 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002056 TimeBase timeBase, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08002057 super(clocks, type, timeBase, in);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002058 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002059 mTimerPool = timerPool;
2060 mUpdateTime = in.readLong();
2061 }
2062
Joe Onoratoabded112016-02-08 16:49:39 -08002063 public StopwatchTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002064 TimeBase timeBase) {
Joe Onoratoabded112016-02-08 16:49:39 -08002065 super(clocks, type, timeBase);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07002066 mUid = uid;
Evan Millarc64edde2009-04-18 12:26:32 -07002067 mTimerPool = timerPool;
2068 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002069
Joe Onoratoabded112016-02-08 16:49:39 -08002070 public void setTimeout(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002071 mTimeout = timeout;
2072 }
2073
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002074 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
2075 super.writeToParcel(out, elapsedRealtimeUs);
Evan Millarc64edde2009-04-18 12:26:32 -07002076 out.writeLong(mUpdateTime);
2077 }
2078
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002079 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
Evan Millarc64edde2009-04-18 12:26:32 -07002080 if (mNesting > 0) {
2081 if (DEBUG && mType < 0) {
2082 Log.v(TAG, "old mUpdateTime=" + mUpdateTime);
2083 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002084 super.onTimeStopped(elapsedRealtime, baseUptime, baseRealtime);
2085 mUpdateTime = baseRealtime;
Evan Millarc64edde2009-04-18 12:26:32 -07002086 if (DEBUG && mType < 0) {
2087 Log.v(TAG, "new mUpdateTime=" + mUpdateTime);
2088 }
2089 }
2090 }
2091
2092 public void logState(Printer pw, String prefix) {
2093 super.logState(pw, prefix);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07002094 pw.println(prefix + "mNesting=" + mNesting + " mUpdateTime=" + mUpdateTime
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 + " mAcquireTime=" + mAcquireTime);
2096 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002097
Joe Onoratoabded112016-02-08 16:49:39 -08002098 public void startRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 if (mNesting++ == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002100 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002101 mUpdateTime = batteryRealtime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 if (mTimerPool != null) {
2103 // Accumulate time to all currently active timers before adding
2104 // this new one to the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002105 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 // Add this timer to the active pool
2107 mTimerPool.add(this);
2108 }
Bookatzceebafe2017-04-06 11:59:13 -07002109 if (mTimeBase.isRunning()) {
2110 // Increment the count
2111 mCount++;
2112 mAcquireTime = mTotalTime;
2113 } else {
2114 mAcquireTime = -1;
2115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 if (DEBUG && mType < 0) {
2117 Log.v(TAG, "start #" + mType + ": mUpdateTime=" + mUpdateTime
2118 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2119 + " mAcquireTime=" + mAcquireTime);
2120 }
2121 }
2122 }
2123
Joe Onoratoabded112016-02-08 16:49:39 -08002124 public boolean isRunningLocked() {
Amith Yamasani32dbefd2009-06-19 09:21:17 -07002125 return mNesting > 0;
2126 }
2127
Joe Onoratoabded112016-02-08 16:49:39 -08002128 public void stopRunningLocked(long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 // Ignore attempt to stop a timer that isn't running
2130 if (mNesting == 0) {
2131 return;
2132 }
2133 if (--mNesting == 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002134 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 if (mTimerPool != null) {
2136 // Accumulate time to all active counters, scaled by the total
2137 // active in the pool, before taking this one out of the pool.
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002138 refreshTimersLocked(batteryRealtime, mTimerPool, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 // Remove this timer from the active pool
2140 mTimerPool.remove(this);
2141 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 mNesting = 1;
2143 mTotalTime = computeRunTimeLocked(batteryRealtime);
2144 mNesting = 0;
2145 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 if (DEBUG && mType < 0) {
2148 Log.v(TAG, "stop #" + mType + ": mUpdateTime=" + mUpdateTime
2149 + " mTotalTime=" + mTotalTime + " mCount=" + mCount
2150 + " mAcquireTime=" + mAcquireTime);
2151 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002152
Bookatzceebafe2017-04-06 11:59:13 -07002153 if (mAcquireTime >= 0 && mTotalTime == mAcquireTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 // If there was no change in the time, then discard this
2155 // count. A somewhat cheezy strategy, but hey.
2156 mCount--;
2157 }
2158 }
2159 }
2160
Joe Onoratoabded112016-02-08 16:49:39 -08002161 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07002162 if (mNesting > 0) {
2163 mNesting = 1;
2164 stopRunningLocked(elapsedRealtimeMs);
2165 }
2166 }
2167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 // Update the total time for all other running Timers with the same type as this Timer
2169 // due to a change in timer count
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002170 private static long refreshTimersLocked(long batteryRealtime,
2171 final ArrayList<StopwatchTimer> pool, StopwatchTimer self) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002172 long selfTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 final int N = pool.size();
2174 for (int i=N-1; i>= 0; i--) {
Evan Millarc64edde2009-04-18 12:26:32 -07002175 final StopwatchTimer t = pool.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 long heldTime = batteryRealtime - t.mUpdateTime;
2177 if (heldTime > 0) {
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002178 final long myTime = heldTime / N;
2179 if (t == self) {
2180 selfTime = myTime;
2181 }
2182 t.mTotalTime += myTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 }
2184 t.mUpdateTime = batteryRealtime;
2185 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08002186 return selfTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 }
2188
Evan Millarc64edde2009-04-18 12:26:32 -07002189 @Override
2190 protected long computeRunTimeLocked(long curBatteryRealtime) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07002191 if (mTimeout > 0 && curBatteryRealtime > mUpdateTime + mTimeout) {
2192 curBatteryRealtime = mUpdateTime + mTimeout;
2193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 return mTotalTime + (mNesting > 0
2195 ? (curBatteryRealtime - mUpdateTime)
2196 / (mTimerPool != null ? mTimerPool.size() : 1)
2197 : 0);
2198 }
2199
Evan Millarc64edde2009-04-18 12:26:32 -07002200 @Override
2201 protected int computeCurrentCountLocked() {
2202 return mCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002203 }
2204
Adam Lesinskie08af192015-03-25 16:42:59 -07002205 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002206 public boolean reset(boolean detachIfReset) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002207 boolean canDetach = mNesting <= 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08002208 super.reset(canDetach && detachIfReset);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002209 if (mNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08002210 mUpdateTime = mTimeBase.getRealtime(mClocks.elapsedRealtime() * 1000);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002211 }
Bookatzceebafe2017-04-06 11:59:13 -07002212 mAcquireTime = -1; // to ensure mCount isn't decreased to -1 if timer is stopped later.
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002213 return canDetach;
2214 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002215
Adam Lesinskie08af192015-03-25 16:42:59 -07002216 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002217 public void detach() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07002218 super.detach();
2219 if (mTimerPool != null) {
2220 mTimerPool.remove(this);
2221 }
2222 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002223
Adam Lesinskie08af192015-03-25 16:42:59 -07002224 @Override
Joe Onoratoabded112016-02-08 16:49:39 -08002225 public void readSummaryFromParcelLocked(Parcel in) {
Evan Millarc64edde2009-04-18 12:26:32 -07002226 super.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 mNesting = 0;
2228 }
Adam Lesinskie08af192015-03-25 16:42:59 -07002229
2230 /**
2231 * Set the mark so that we can query later for the total time the timer has
2232 * accumulated since this point. The timer can be running or not.
2233 *
2234 * @param elapsedRealtimeMs the current elapsed realtime in milliseconds.
2235 */
2236 public void setMark(long elapsedRealtimeMs) {
2237 final long batteryRealtime = mTimeBase.getRealtime(elapsedRealtimeMs * 1000);
2238 if (mNesting > 0) {
2239 // We are running.
2240 if (mTimerPool != null) {
2241 refreshTimersLocked(batteryRealtime, mTimerPool, this);
2242 } else {
2243 mTotalTime += batteryRealtime - mUpdateTime;
2244 mUpdateTime = batteryRealtime;
2245 }
2246 }
2247 mTimeBeforeMark = mTotalTime;
2248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002250
Bookatz867c0d72017-03-07 18:23:42 -08002251 /**
2252 * State for keeping track of two DurationTimers with different TimeBases, presumably where one
2253 * TimeBase is effectively a subset of the other.
2254 */
Bookatzaa4594a2017-03-24 12:39:56 -07002255 public static class DualTimer extends DurationTimer {
2256 // This class both is a DurationTimer and also holds a second DurationTimer.
2257 // The main timer (this) typically tracks the total time. It may be pooled (but since it's a
2258 // durationTimer, it also has the unpooled getTotalDurationMsLocked() for
2259 // STATS_SINCE_CHARGED).
Bookatz867c0d72017-03-07 18:23:42 -08002260 // mSubTimer typically tracks only part of the total time, such as background time, as
2261 // determined by a subTimeBase. It is NOT pooled.
2262 private final DurationTimer mSubTimer;
2263
2264 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002265 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2266 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002267 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002268 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002269 */
2270 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2271 TimeBase timeBase, TimeBase subTimeBase, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002272 super(clocks, uid, type, timerPool, timeBase, in);
Bookatz867c0d72017-03-07 18:23:42 -08002273 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase, in);
2274 }
2275
2276 /**
Bookatzaa4594a2017-03-24 12:39:56 -07002277 * Creates a DualTimer to hold a main timer (this) and a mSubTimer.
2278 * The main timer (this) is based on the given timeBase and timerPool.
Bookatz867c0d72017-03-07 18:23:42 -08002279 * The mSubTimer is based on the given subTimeBase. The mSubTimer is not pooled, even if
Bookatzaa4594a2017-03-24 12:39:56 -07002280 * the main timer is.
Bookatz867c0d72017-03-07 18:23:42 -08002281 */
2282 public DualTimer(Clocks clocks, Uid uid, int type, ArrayList<StopwatchTimer> timerPool,
2283 TimeBase timeBase, TimeBase subTimeBase) {
Bookatzaa4594a2017-03-24 12:39:56 -07002284 super(clocks, uid, type, timerPool, timeBase);
Bookatz867c0d72017-03-07 18:23:42 -08002285 mSubTimer = new DurationTimer(clocks, uid, type, null, subTimeBase);
2286 }
2287
Bookatz867c0d72017-03-07 18:23:42 -08002288 /** Get the secondary timer. */
Bookatzaa4594a2017-03-24 12:39:56 -07002289 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002290 public DurationTimer getSubTimer() {
2291 return mSubTimer;
2292 }
2293
Bookatzaa4594a2017-03-24 12:39:56 -07002294 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002295 public void startRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002296 super.startRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002297 mSubTimer.startRunningLocked(elapsedRealtimeMs);
2298 }
2299
Bookatzaa4594a2017-03-24 12:39:56 -07002300 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002301 public void stopRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002302 super.stopRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002303 mSubTimer.stopRunningLocked(elapsedRealtimeMs);
2304 }
2305
Bookatzaa4594a2017-03-24 12:39:56 -07002306 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002307 public void stopAllRunningLocked(long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002308 super.stopAllRunningLocked(elapsedRealtimeMs);
Bookatz867c0d72017-03-07 18:23:42 -08002309 mSubTimer.stopAllRunningLocked(elapsedRealtimeMs);
2310 }
2311
Bookatzaa4594a2017-03-24 12:39:56 -07002312 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002313 public boolean reset(boolean detachIfReset) {
2314 boolean active = false;
Bookatz4a3eda92017-04-10 13:10:46 -07002315 // Do not detach the subTimer explicitly since that'll be done by DualTimer.detach().
2316 active |= !mSubTimer.reset(false);
Bookatzaa4594a2017-03-24 12:39:56 -07002317 active |= !super.reset(detachIfReset);
Bookatz867c0d72017-03-07 18:23:42 -08002318 return !active;
2319 }
2320
Bookatzaa4594a2017-03-24 12:39:56 -07002321 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002322 public void detach() {
Bookatz867c0d72017-03-07 18:23:42 -08002323 mSubTimer.detach();
Bookatz4a3eda92017-04-10 13:10:46 -07002324 super.detach();
Bookatz867c0d72017-03-07 18:23:42 -08002325 }
2326
Bookatzaa4594a2017-03-24 12:39:56 -07002327 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002328 public void writeToParcel(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002329 super.writeToParcel(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002330 mSubTimer.writeToParcel(out, elapsedRealtimeUs);
2331 }
2332
Bookatzaa4594a2017-03-24 12:39:56 -07002333 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002334 public void writeSummaryFromParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07002335 super.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08002336 mSubTimer.writeSummaryFromParcelLocked(out, elapsedRealtimeUs);
2337 }
2338
Bookatzaa4594a2017-03-24 12:39:56 -07002339 @Override
Bookatz867c0d72017-03-07 18:23:42 -08002340 public void readSummaryFromParcelLocked(Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07002341 super.readSummaryFromParcelLocked(in);
Bookatz867c0d72017-03-07 18:23:42 -08002342 mSubTimer.readSummaryFromParcelLocked(in);
2343 }
2344 }
2345
2346
Dianne Hackbornd953c532014-08-16 18:17:38 -07002347 public abstract class OverflowArrayMap<T> {
2348 private static final String OVERFLOW_NAME = "*overflow*";
2349
Dianne Hackborn657153b2016-07-29 14:54:14 -07002350 final int mUid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002351 final ArrayMap<String, T> mMap = new ArrayMap<>();
2352 T mCurOverflow;
2353 ArrayMap<String, MutableInt> mActiveOverflow;
Dianne Hackborn657153b2016-07-29 14:54:14 -07002354 long mLastOverflowTime;
2355 long mLastOverflowFinishTime;
2356 long mLastClearTime;
2357 long mLastCleanupTime;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002358
Dianne Hackborn657153b2016-07-29 14:54:14 -07002359 public OverflowArrayMap(int uid) {
2360 mUid = uid;
Dianne Hackbornd953c532014-08-16 18:17:38 -07002361 }
2362
2363 public ArrayMap<String, T> getMap() {
2364 return mMap;
2365 }
2366
2367 public void clear() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002368 mLastClearTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002369 mMap.clear();
2370 mCurOverflow = null;
2371 mActiveOverflow = null;
2372 }
2373
2374 public void add(String name, T obj) {
Joe Onorato388fc332016-04-12 17:06:47 -07002375 if (name == null) {
2376 name = "";
2377 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002378 mMap.put(name, obj);
2379 if (OVERFLOW_NAME.equals(name)) {
2380 mCurOverflow = obj;
2381 }
2382 }
2383
2384 public void cleanup() {
Dianne Hackborn657153b2016-07-29 14:54:14 -07002385 mLastCleanupTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002386 if (mActiveOverflow != null) {
2387 if (mActiveOverflow.size() == 0) {
2388 mActiveOverflow = null;
2389 }
2390 }
2391 if (mActiveOverflow == null) {
2392 // There is no currently active overflow, so we should no longer have
2393 // an overflow entry.
2394 if (mMap.containsKey(OVERFLOW_NAME)) {
2395 Slog.wtf(TAG, "Cleaning up with no active overflow, but have overflow entry "
2396 + mMap.get(OVERFLOW_NAME));
2397 mMap.remove(OVERFLOW_NAME);
2398 }
2399 mCurOverflow = null;
2400 } else {
2401 // There is currently active overflow, so we should still have an overflow entry.
2402 if (mCurOverflow == null || !mMap.containsKey(OVERFLOW_NAME)) {
2403 Slog.wtf(TAG, "Cleaning up with active overflow, but no overflow entry: cur="
2404 + mCurOverflow + " map=" + mMap.get(OVERFLOW_NAME));
2405 }
2406 }
2407 }
2408
2409 public T startObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002410 if (name == null) {
2411 name = "";
2412 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002413 T obj = mMap.get(name);
2414 if (obj != null) {
2415 return obj;
2416 }
2417
2418 // No object exists for the given name, but do we currently have it
2419 // running as part of the overflow?
2420 if (mActiveOverflow != null) {
2421 MutableInt over = mActiveOverflow.get(name);
2422 if (over != null) {
2423 // We are already actively counting this name in the overflow object.
2424 obj = mCurOverflow;
2425 if (obj == null) {
2426 // Shouldn't be here, but we'll try to recover.
2427 Slog.wtf(TAG, "Have active overflow " + name + " but null overflow");
2428 obj = mCurOverflow = instantiateObject();
2429 mMap.put(OVERFLOW_NAME, obj);
2430 }
2431 over.value++;
2432 return obj;
2433 }
2434 }
2435
2436 // No object exists for given name nor in the overflow; we need to make
2437 // a new one.
2438 final int N = mMap.size();
2439 if (N >= MAX_WAKELOCKS_PER_UID) {
2440 // Went over the limit on number of objects to track; this one goes
2441 // in to the overflow.
2442 obj = mCurOverflow;
2443 if (obj == null) {
2444 // Need to start overflow now...
2445 obj = mCurOverflow = instantiateObject();
2446 mMap.put(OVERFLOW_NAME, obj);
2447 }
2448 if (mActiveOverflow == null) {
2449 mActiveOverflow = new ArrayMap<>();
2450 }
2451 mActiveOverflow.put(name, new MutableInt(1));
Dianne Hackborn657153b2016-07-29 14:54:14 -07002452 mLastOverflowTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002453 return obj;
2454 }
2455
2456 // Normal case where we just need to make a new object.
2457 obj = instantiateObject();
2458 mMap.put(name, obj);
2459 return obj;
2460 }
2461
2462 public T stopObject(String name) {
Joe Onorato388fc332016-04-12 17:06:47 -07002463 if (name == null) {
2464 name = "";
2465 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07002466 T obj = mMap.get(name);
2467 if (obj != null) {
2468 return obj;
2469 }
2470
2471 // No object exists for the given name, but do we currently have it
2472 // running as part of the overflow?
2473 if (mActiveOverflow != null) {
2474 MutableInt over = mActiveOverflow.get(name);
2475 if (over != null) {
2476 // We are already actively counting this name in the overflow object.
2477 obj = mCurOverflow;
2478 if (obj != null) {
2479 over.value--;
2480 if (over.value <= 0) {
2481 mActiveOverflow.remove(name);
Dianne Hackborn657153b2016-07-29 14:54:14 -07002482 mLastOverflowFinishTime = SystemClock.elapsedRealtime();
Dianne Hackbornd953c532014-08-16 18:17:38 -07002483 }
2484 return obj;
2485 }
2486 }
2487 }
2488
2489 // Huh, they are stopping an active operation but we can't find one!
2490 // That's not good.
Dianne Hackborn657153b2016-07-29 14:54:14 -07002491 StringBuilder sb = new StringBuilder();
2492 sb.append("Unable to find object for ");
2493 sb.append(name);
2494 sb.append(" in uid ");
2495 sb.append(mUid);
2496 sb.append(" mapsize=");
2497 sb.append(mMap.size());
2498 sb.append(" activeoverflow=");
2499 sb.append(mActiveOverflow);
2500 sb.append(" curoverflow=");
2501 sb.append(mCurOverflow);
2502 long now = SystemClock.elapsedRealtime();
2503 if (mLastOverflowTime != 0) {
2504 sb.append(" lastOverflowTime=");
2505 TimeUtils.formatDuration(mLastOverflowTime-now, sb);
2506 }
2507 if (mLastOverflowFinishTime != 0) {
2508 sb.append(" lastOverflowFinishTime=");
2509 TimeUtils.formatDuration(mLastOverflowFinishTime-now, sb);
2510 }
2511 if (mLastClearTime != 0) {
2512 sb.append(" lastClearTime=");
2513 TimeUtils.formatDuration(mLastClearTime-now, sb);
2514 }
2515 if (mLastCleanupTime != 0) {
2516 sb.append(" lastCleanupTime=");
2517 TimeUtils.formatDuration(mLastCleanupTime-now, sb);
2518 }
2519 Slog.wtf(TAG, sb.toString());
Dianne Hackbornd953c532014-08-16 18:17:38 -07002520 return null;
2521 }
2522
2523 public abstract T instantiateObject();
2524 }
2525
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002526 public static class ControllerActivityCounterImpl extends ControllerActivityCounter
2527 implements Parcelable {
2528 private final LongSamplingCounter mIdleTimeMillis;
2529 private final LongSamplingCounter mRxTimeMillis;
2530 private final LongSamplingCounter[] mTxTimeMillis;
2531 private final LongSamplingCounter mPowerDrainMaMs;
2532
2533 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates) {
2534 mIdleTimeMillis = new LongSamplingCounter(timeBase);
2535 mRxTimeMillis = new LongSamplingCounter(timeBase);
2536 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2537 for (int i = 0; i < numTxStates; i++) {
2538 mTxTimeMillis[i] = new LongSamplingCounter(timeBase);
2539 }
2540 mPowerDrainMaMs = new LongSamplingCounter(timeBase);
2541 }
2542
2543 public ControllerActivityCounterImpl(TimeBase timeBase, int numTxStates, Parcel in) {
2544 mIdleTimeMillis = new LongSamplingCounter(timeBase, in);
2545 mRxTimeMillis = new LongSamplingCounter(timeBase, in);
2546 final int recordedTxStates = in.readInt();
2547 if (recordedTxStates != numTxStates) {
2548 throw new ParcelFormatException("inconsistent tx state lengths");
2549 }
2550
2551 mTxTimeMillis = new LongSamplingCounter[numTxStates];
2552 for (int i = 0; i < numTxStates; i++) {
2553 mTxTimeMillis[i] = new LongSamplingCounter(timeBase, in);
2554 }
2555 mPowerDrainMaMs = new LongSamplingCounter(timeBase, in);
2556 }
2557
2558 public void readSummaryFromParcel(Parcel in) {
2559 mIdleTimeMillis.readSummaryFromParcelLocked(in);
2560 mRxTimeMillis.readSummaryFromParcelLocked(in);
2561 final int recordedTxStates = in.readInt();
2562 if (recordedTxStates != mTxTimeMillis.length) {
2563 throw new ParcelFormatException("inconsistent tx state lengths");
2564 }
2565 for (LongSamplingCounter counter : mTxTimeMillis) {
2566 counter.readSummaryFromParcelLocked(in);
2567 }
2568 mPowerDrainMaMs.readSummaryFromParcelLocked(in);
2569 }
2570
2571 @Override
2572 public int describeContents() {
2573 return 0;
2574 }
2575
2576 public void writeSummaryToParcel(Parcel dest) {
2577 mIdleTimeMillis.writeSummaryFromParcelLocked(dest);
2578 mRxTimeMillis.writeSummaryFromParcelLocked(dest);
2579 dest.writeInt(mTxTimeMillis.length);
2580 for (LongSamplingCounter counter : mTxTimeMillis) {
2581 counter.writeSummaryFromParcelLocked(dest);
2582 }
2583 mPowerDrainMaMs.writeSummaryFromParcelLocked(dest);
2584 }
2585
2586 @Override
2587 public void writeToParcel(Parcel dest, int flags) {
2588 mIdleTimeMillis.writeToParcel(dest);
2589 mRxTimeMillis.writeToParcel(dest);
2590 dest.writeInt(mTxTimeMillis.length);
2591 for (LongSamplingCounter counter : mTxTimeMillis) {
2592 counter.writeToParcel(dest);
2593 }
2594 mPowerDrainMaMs.writeToParcel(dest);
2595 }
2596
2597 public void reset(boolean detachIfReset) {
2598 mIdleTimeMillis.reset(detachIfReset);
2599 mRxTimeMillis.reset(detachIfReset);
2600 for (LongSamplingCounter counter : mTxTimeMillis) {
2601 counter.reset(detachIfReset);
2602 }
2603 mPowerDrainMaMs.reset(detachIfReset);
2604 }
2605
2606 public void detach() {
2607 mIdleTimeMillis.detach();
2608 mRxTimeMillis.detach();
2609 for (LongSamplingCounter counter : mTxTimeMillis) {
2610 counter.detach();
2611 }
2612 mPowerDrainMaMs.detach();
2613 }
2614
2615 /**
2616 * @return a LongSamplingCounter, measuring time spent in the idle state in
2617 * milliseconds.
2618 */
2619 @Override
2620 public LongSamplingCounter getIdleTimeCounter() {
Roshan Pius81643302016-03-14 16:45:55 -07002621 return mIdleTimeMillis;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08002622 }
2623
2624 /**
2625 * @return a LongSamplingCounter, measuring time spent in the receive state in
2626 * milliseconds.
2627 */
2628 @Override
2629 public LongSamplingCounter getRxTimeCounter() {
2630 return mRxTimeMillis;
2631 }
2632
2633 /**
2634 * @return a LongSamplingCounter[], measuring time spent in various transmit states in
2635 * milliseconds.
2636 */
2637 @Override
2638 public LongSamplingCounter[] getTxTimeCounters() {
2639 return mTxTimeMillis;
2640 }
2641
2642 /**
2643 * @return a LongSamplingCounter, measuring power use in milli-ampere milliseconds (mAmS).
2644 */
2645 @Override
2646 public LongSamplingCounter getPowerCounter() {
2647 return mPowerDrainMaMs;
2648 }
2649 }
2650
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002651 /*
2652 * Get the wakeup reason counter, and create a new one if one
2653 * doesn't already exist.
2654 */
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002655 public SamplingTimer getWakeupReasonTimerLocked(String name) {
2656 SamplingTimer timer = mWakeupReasonStats.get(name);
2657 if (timer == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002658 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002659 mWakeupReasonStats.put(name, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002660 }
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07002661 return timer;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002662 }
2663
Evan Millarc64edde2009-04-18 12:26:32 -07002664 /*
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07002665 * Get the KernelWakelockTimer associated with name, and create a new one if one
Evan Millarc64edde2009-04-18 12:26:32 -07002666 * doesn't already exist.
2667 */
2668 public SamplingTimer getKernelWakelockTimerLocked(String name) {
2669 SamplingTimer kwlt = mKernelWakelockStats.get(name);
2670 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -07002671 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Evan Millarc64edde2009-04-18 12:26:32 -07002672 mKernelWakelockStats.put(name, kwlt);
2673 }
2674 return kwlt;
2675 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07002676
James Carr3a226052016-07-01 14:49:52 -07002677 public SamplingTimer getKernelMemoryTimerLocked(long bucket) {
2678 SamplingTimer kmt = mKernelMemoryStats.get(bucket);
2679 if (kmt == null) {
2680 kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase);
2681 mKernelMemoryStats.put(bucket, kmt);
2682 }
2683 return kmt;
2684 }
2685
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002686 private int writeHistoryTag(HistoryTag tag) {
2687 Integer idxObj = mHistoryTagPool.get(tag);
2688 int idx;
2689 if (idxObj != null) {
2690 idx = idxObj;
2691 } else {
2692 idx = mNextHistoryTagIdx;
2693 HistoryTag key = new HistoryTag();
2694 key.setTo(tag);
2695 tag.poolIdx = idx;
2696 mHistoryTagPool.put(key, idx);
2697 mNextHistoryTagIdx++;
2698 mNumHistoryTagChars += key.string.length() + 1;
2699 }
2700 return idx;
2701 }
2702
2703 private void readHistoryTag(int index, HistoryTag tag) {
2704 tag.string = mReadHistoryStrings[index];
2705 tag.uid = mReadHistoryUids[index];
2706 tag.poolIdx = index;
2707 }
2708
Adam Lesinski926969b2016-04-28 17:31:12 -07002709 /*
2710 The history delta format uses flags to denote further data in subsequent ints in the parcel.
2711
2712 There is always the first token, which may contain the delta time, or an indicator of
2713 the length of the time (int or long) following this token.
2714
2715 First token: always present,
2716 31 23 15 7 0
2717 â–ˆ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â–ˆ
2718
2719 T: the delta time if it is <= 0x7fffd. Otherwise 0x7fffe indicates an int immediately
2720 follows containing the time, and 0x7ffff indicates a long immediately follows with the
2721 delta time.
2722 A: battery level changed and an int follows with battery data.
2723 B: state changed and an int follows with state change data.
2724 C: state2 has changed and an int follows with state2 change data.
2725 D: wakelock/wakereason has changed and an wakelock/wakereason struct follows.
2726 E: event data has changed and an event struct follows.
2727 F: battery charge in coulombs has changed and an int with the charge follows.
2728 G: state flag denoting that the mobile radio was active.
2729 H: state flag denoting that the wifi radio was active.
2730 I: state flag denoting that a wifi scan occurred.
2731 J: state flag denoting that a wifi full lock was held.
2732 K: state flag denoting that the gps was on.
2733 L: state flag denoting that a wakelock was held.
2734 M: state flag denoting that the cpu was running.
2735
2736 Time int/long: if T in the first token is 0x7ffff or 0x7fffe, then an int or long follows
2737 with the time delta.
2738
2739 Battery level int: if A in the first token is set,
2740 31 23 15 7 0
2741 â–ˆ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â–ˆ
2742
2743 D: indicates that extra history details follow.
2744 V: the battery voltage.
2745 T: the battery temperature.
2746 L: the battery level (out of 100).
2747
2748 State change int: if B in the first token is set,
2749 31 23 15 7 0
2750 â–ˆS|S|S|H|H|H|P|Pâ–ˆF|E|D|C|B| | |Aâ–ˆ | | | | | | | â–ˆ | | | | | | | â–ˆ
2751
2752 A: wifi multicast was on.
2753 B: battery was plugged in.
2754 C: screen was on.
2755 D: phone was scanning for signal.
2756 E: audio was on.
2757 F: a sensor was active.
2758
2759 State2 change int: if C in the first token is set,
2760 31 23 15 7 0
2761 â–ˆM|L|K|J|I|H|H|Gâ–ˆF|E|D|C| | | | â–ˆ | | | | | | | â–ˆ |B|B|B|A|A|A|Aâ–ˆ
2762
2763 A: 4 bits indicating the wifi supplicant state: {@link BatteryStats#WIFI_SUPPL_STATE_NAMES}.
2764 B: 3 bits indicating the wifi signal strength: 0, 1, 2, 3, 4.
2765 C: a bluetooth scan was active.
2766 D: the camera was active.
2767 E: bluetooth was on.
2768 F: a phone call was active.
2769 G: the device was charging.
2770 H: 2 bits indicating the device-idle (doze) state: off, light, full
2771 I: the flashlight was on.
2772 J: wifi was on.
2773 K: wifi was running.
2774 L: video was playing.
2775 M: power save mode was on.
2776
2777 Wakelock/wakereason struct: if D in the first token is set,
2778 TODO(adamlesinski): describe wakelock/wakereason struct.
2779
2780 Event struct: if E in the first token is set,
2781 TODO(adamlesinski): describe the event struct.
2782
2783 History step details struct: if D in the battery level int is set,
2784 TODO(adamlesinski): describe the history step details struct.
2785
2786 Battery charge int: if F in the first token is set, an int representing the battery charge
2787 in coulombs follows.
2788 */
2789
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002790 // Part of initial delta int that specifies the time delta.
Dianne Hackborne13c4c02014-02-11 17:18:35 -08002791 static final int DELTA_TIME_MASK = 0x7ffff;
2792 static final int DELTA_TIME_LONG = 0x7ffff; // The delta is a following long
2793 static final int DELTA_TIME_INT = 0x7fffe; // The delta is a following int
2794 static final int DELTA_TIME_ABS = 0x7fffd; // Following is an entire abs update.
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002795 // Flag in delta int: a new battery level int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07002796 static final int DELTA_BATTERY_LEVEL_FLAG = 0x00080000;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002797 // Flag in delta int: a new full state and battery status int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07002798 static final int DELTA_STATE_FLAG = 0x00100000;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08002799 // Flag in delta int: a new full state2 int follows.
Adam Lesinski926969b2016-04-28 17:31:12 -07002800 static final int DELTA_STATE2_FLAG = 0x00200000;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002801 // Flag in delta int: contains a wakelock or wakeReason tag.
Adam Lesinski926969b2016-04-28 17:31:12 -07002802 static final int DELTA_WAKELOCK_FLAG = 0x00400000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002803 // Flag in delta int: contains an event description.
Adam Lesinski926969b2016-04-28 17:31:12 -07002804 static final int DELTA_EVENT_FLAG = 0x00800000;
Adam Lesinskia8018ac2016-05-03 10:18:10 -07002805 // Flag in delta int: contains the battery charge count in uAh.
2806 static final int DELTA_BATTERY_CHARGE_FLAG = 0x01000000;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002807 // These upper bits are the frequently changing state bits.
Adam Lesinski926969b2016-04-28 17:31:12 -07002808 static final int DELTA_STATE_MASK = 0xfe000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08002809
2810 // These are the pieces of battery state that are packed in to the upper bits of
2811 // the state int that have been packed in to the first delta int. They must fit
Adam Lesinski926969b2016-04-28 17:31:12 -07002812 // in STATE_BATTERY_MASK.
2813 static final int STATE_BATTERY_MASK = 0xff000000;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08002814 static final int STATE_BATTERY_STATUS_MASK = 0x00000007;
2815 static final int STATE_BATTERY_STATUS_SHIFT = 29;
2816 static final int STATE_BATTERY_HEALTH_MASK = 0x00000007;
2817 static final int STATE_BATTERY_HEALTH_SHIFT = 26;
2818 static final int STATE_BATTERY_PLUG_MASK = 0x00000003;
2819 static final int STATE_BATTERY_PLUG_SHIFT = 24;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002820
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002821 // We use the low bit of the battery state int to indicate that we have full details
2822 // from a battery level change.
2823 static final int BATTERY_DELTA_LEVEL_FLAG = 0x00000001;
2824
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002825 public void writeHistoryDelta(Parcel dest, HistoryItem cur, HistoryItem last) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002826 if (last == null || cur.cmd != HistoryItem.CMD_UPDATE) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002827 dest.writeInt(DELTA_TIME_ABS);
2828 cur.writeToParcel(dest, 0);
2829 return;
2830 }
2831
2832 final long deltaTime = cur.time - last.time;
2833 final int lastBatteryLevelInt = buildBatteryLevelInt(last);
2834 final int lastStateInt = buildStateInt(last);
2835
2836 int deltaTimeToken;
2837 if (deltaTime < 0 || deltaTime > Integer.MAX_VALUE) {
2838 deltaTimeToken = DELTA_TIME_LONG;
2839 } else if (deltaTime >= DELTA_TIME_ABS) {
2840 deltaTimeToken = DELTA_TIME_INT;
2841 } else {
2842 deltaTimeToken = (int)deltaTime;
2843 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002844 int firstToken = deltaTimeToken | (cur.states&DELTA_STATE_MASK);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002845 final int includeStepDetails = mLastHistoryStepLevel > cur.batteryLevel
2846 ? BATTERY_DELTA_LEVEL_FLAG : 0;
2847 final boolean computeStepDetails = includeStepDetails != 0
2848 || mLastHistoryStepDetails == null;
2849 final int batteryLevelInt = buildBatteryLevelInt(cur) | includeStepDetails;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002850 final boolean batteryLevelIntChanged = batteryLevelInt != lastBatteryLevelInt;
2851 if (batteryLevelIntChanged) {
2852 firstToken |= DELTA_BATTERY_LEVEL_FLAG;
2853 }
2854 final int stateInt = buildStateInt(cur);
2855 final boolean stateIntChanged = stateInt != lastStateInt;
2856 if (stateIntChanged) {
2857 firstToken |= DELTA_STATE_FLAG;
2858 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002859 final boolean state2IntChanged = cur.states2 != last.states2;
2860 if (state2IntChanged) {
2861 firstToken |= DELTA_STATE2_FLAG;
2862 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002863 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002864 firstToken |= DELTA_WAKELOCK_FLAG;
2865 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002866 if (cur.eventCode != HistoryItem.EVENT_NONE) {
2867 firstToken |= DELTA_EVENT_FLAG;
2868 }
Adam Lesinski926969b2016-04-28 17:31:12 -07002869
Adam Lesinskia8018ac2016-05-03 10:18:10 -07002870 final boolean batteryChargeChanged = cur.batteryChargeUAh != last.batteryChargeUAh;
2871 if (batteryChargeChanged) {
2872 firstToken |= DELTA_BATTERY_CHARGE_FLAG;
Adam Lesinski926969b2016-04-28 17:31:12 -07002873 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002874 dest.writeInt(firstToken);
2875 if (DEBUG) Slog.i(TAG, "WRITE DELTA: firstToken=0x" + Integer.toHexString(firstToken)
2876 + " deltaTime=" + deltaTime);
2877
2878 if (deltaTimeToken >= DELTA_TIME_INT) {
2879 if (deltaTimeToken == DELTA_TIME_INT) {
2880 if (DEBUG) Slog.i(TAG, "WRITE DELTA: int deltaTime=" + (int)deltaTime);
2881 dest.writeInt((int)deltaTime);
2882 } else {
2883 if (DEBUG) Slog.i(TAG, "WRITE DELTA: long deltaTime=" + deltaTime);
2884 dest.writeLong(deltaTime);
2885 }
2886 }
2887 if (batteryLevelIntChanged) {
2888 dest.writeInt(batteryLevelInt);
2889 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryToken=0x"
2890 + Integer.toHexString(batteryLevelInt)
2891 + " batteryLevel=" + cur.batteryLevel
2892 + " batteryTemp=" + cur.batteryTemperature
2893 + " batteryVolt=" + (int)cur.batteryVoltage);
2894 }
2895 if (stateIntChanged) {
2896 dest.writeInt(stateInt);
2897 if (DEBUG) Slog.i(TAG, "WRITE DELTA: stateToken=0x"
2898 + Integer.toHexString(stateInt)
2899 + " batteryStatus=" + cur.batteryStatus
2900 + " batteryHealth=" + cur.batteryHealth
2901 + " batteryPlugType=" + cur.batteryPlugType
2902 + " states=0x" + Integer.toHexString(cur.states));
2903 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07002904 if (state2IntChanged) {
2905 dest.writeInt(cur.states2);
2906 if (DEBUG) Slog.i(TAG, "WRITE DELTA: states2=0x"
2907 + Integer.toHexString(cur.states2));
2908 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08002909 if (cur.wakelockTag != null || cur.wakeReasonTag != null) {
2910 int wakeLockIndex;
2911 int wakeReasonIndex;
2912 if (cur.wakelockTag != null) {
2913 wakeLockIndex = writeHistoryTag(cur.wakelockTag);
2914 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
2915 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
2916 } else {
2917 wakeLockIndex = 0xffff;
2918 }
2919 if (cur.wakeReasonTag != null) {
2920 wakeReasonIndex = writeHistoryTag(cur.wakeReasonTag);
2921 if (DEBUG) Slog.i(TAG, "WRITE DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
2922 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
2923 } else {
2924 wakeReasonIndex = 0xffff;
2925 }
2926 dest.writeInt((wakeReasonIndex<<16) | wakeLockIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002927 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002928 if (cur.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002929 int index = writeHistoryTag(cur.eventTag);
2930 int codeAndIndex = (cur.eventCode&0xffff) | (index<<16);
Dianne Hackborn099bc622014-01-22 13:39:16 -08002931 dest.writeInt(codeAndIndex);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08002932 if (DEBUG) Slog.i(TAG, "WRITE DELTA: event=" + cur.eventCode + " tag=#"
2933 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
2934 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002935 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002936 if (computeStepDetails) {
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07002937 if (mPlatformIdleStateCallback != null) {
2938 mCurHistoryStepDetails.statPlatformIdleState =
2939 mPlatformIdleStateCallback.getPlatformLowPowerStats();
2940 if (DEBUG) Slog.i(TAG, "WRITE PlatformIdleState:" +
2941 mCurHistoryStepDetails.statPlatformIdleState);
Ahmed ElArabawyd8b44112017-05-23 21:25:02 +00002942
2943 mCurHistoryStepDetails.statSubsystemPowerState =
2944 mPlatformIdleStateCallback.getSubsystemLowPowerStats();
2945 if (DEBUG) Slog.i(TAG, "WRITE SubsystemPowerState:" +
2946 mCurHistoryStepDetails.statSubsystemPowerState);
2947
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07002948 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002949 computeHistoryStepDetails(mCurHistoryStepDetails, mLastHistoryStepDetails);
2950 if (includeStepDetails != 0) {
2951 mCurHistoryStepDetails.writeToParcel(dest);
2952 }
2953 cur.stepDetails = mCurHistoryStepDetails;
2954 mLastHistoryStepDetails = mCurHistoryStepDetails;
2955 } else {
2956 cur.stepDetails = null;
2957 }
2958 if (mLastHistoryStepLevel < cur.batteryLevel) {
2959 mLastHistoryStepDetails = null;
2960 }
2961 mLastHistoryStepLevel = cur.batteryLevel;
Adam Lesinski926969b2016-04-28 17:31:12 -07002962
Adam Lesinskia8018ac2016-05-03 10:18:10 -07002963 if (batteryChargeChanged) {
2964 if (DEBUG) Slog.i(TAG, "WRITE DELTA: batteryChargeUAh=" + cur.batteryChargeUAh);
2965 dest.writeInt(cur.batteryChargeUAh);
Adam Lesinski926969b2016-04-28 17:31:12 -07002966 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002967 }
2968
2969 private int buildBatteryLevelInt(HistoryItem h) {
2970 return ((((int)h.batteryLevel)<<25)&0xfe000000)
Adam Lesinski3944c812015-11-13 15:54:59 -08002971 | ((((int)h.batteryTemperature)<<15)&0x01ff8000)
2972 | ((((int)h.batteryVoltage)<<1)&0x00007ffe);
2973 }
2974
2975 private void readBatteryLevelInt(int batteryLevelInt, HistoryItem out) {
2976 out.batteryLevel = (byte)((batteryLevelInt & 0xfe000000) >>> 25);
2977 out.batteryTemperature = (short)((batteryLevelInt & 0x01ff8000) >>> 15);
2978 out.batteryVoltage = (char)((batteryLevelInt & 0x00007ffe) >>> 1);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002979 }
2980
2981 private int buildStateInt(HistoryItem h) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08002982 int plugType = 0;
2983 if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_AC) != 0) {
2984 plugType = 1;
2985 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_USB) != 0) {
2986 plugType = 2;
2987 } else if ((h.batteryPlugType&BatteryManager.BATTERY_PLUGGED_WIRELESS) != 0) {
2988 plugType = 3;
2989 }
2990 return ((h.batteryStatus&STATE_BATTERY_STATUS_MASK)<<STATE_BATTERY_STATUS_SHIFT)
2991 | ((h.batteryHealth&STATE_BATTERY_HEALTH_MASK)<<STATE_BATTERY_HEALTH_SHIFT)
2992 | ((plugType&STATE_BATTERY_PLUG_MASK)<<STATE_BATTERY_PLUG_SHIFT)
Adam Lesinski926969b2016-04-28 17:31:12 -07002993 | (h.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08002994 }
2995
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08002996 private void computeHistoryStepDetails(final HistoryStepDetails out,
2997 final HistoryStepDetails last) {
2998 final HistoryStepDetails tmp = last != null ? mTmpHistoryStepDetails : out;
2999
3000 // Perform a CPU update right after we do this collection, so we have started
3001 // collecting good data for the next step.
3002 requestImmediateCpuUpdate();
3003
3004 if (last == null) {
3005 // We are not generating a delta, so all we need to do is reset the stats
3006 // we will later be doing a delta from.
3007 final int NU = mUidStats.size();
3008 for (int i=0; i<NU; i++) {
3009 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3010 uid.mLastStepUserTime = uid.mCurStepUserTime;
3011 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3012 }
3013 mLastStepCpuUserTime = mCurStepCpuUserTime;
3014 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3015 mLastStepStatUserTime = mCurStepStatUserTime;
3016 mLastStepStatSystemTime = mCurStepStatSystemTime;
3017 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3018 mLastStepStatIrqTime = mCurStepStatIrqTime;
3019 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3020 mLastStepStatIdleTime = mCurStepStatIdleTime;
3021 tmp.clear();
3022 return;
3023 }
3024 if (DEBUG) {
3025 Slog.d(TAG, "Step stats last: user=" + mLastStepCpuUserTime + " sys="
3026 + mLastStepStatSystemTime + " io=" + mLastStepStatIOWaitTime
3027 + " irq=" + mLastStepStatIrqTime + " sirq="
3028 + mLastStepStatSoftIrqTime + " idle=" + mLastStepStatIdleTime);
3029 Slog.d(TAG, "Step stats cur: user=" + mCurStepCpuUserTime + " sys="
3030 + mCurStepStatSystemTime + " io=" + mCurStepStatIOWaitTime
3031 + " irq=" + mCurStepStatIrqTime + " sirq="
3032 + mCurStepStatSoftIrqTime + " idle=" + mCurStepStatIdleTime);
3033 }
3034 out.userTime = (int)(mCurStepCpuUserTime - mLastStepCpuUserTime);
3035 out.systemTime = (int)(mCurStepCpuSystemTime - mLastStepCpuSystemTime);
3036 out.statUserTime = (int)(mCurStepStatUserTime - mLastStepStatUserTime);
3037 out.statSystemTime = (int)(mCurStepStatSystemTime - mLastStepStatSystemTime);
3038 out.statIOWaitTime = (int)(mCurStepStatIOWaitTime - mLastStepStatIOWaitTime);
3039 out.statIrqTime = (int)(mCurStepStatIrqTime - mLastStepStatIrqTime);
3040 out.statSoftIrqTime = (int)(mCurStepStatSoftIrqTime - mLastStepStatSoftIrqTime);
3041 out.statIdlTime = (int)(mCurStepStatIdleTime - mLastStepStatIdleTime);
3042 out.appCpuUid1 = out.appCpuUid2 = out.appCpuUid3 = -1;
3043 out.appCpuUTime1 = out.appCpuUTime2 = out.appCpuUTime3 = 0;
3044 out.appCpuSTime1 = out.appCpuSTime2 = out.appCpuSTime3 = 0;
3045 final int NU = mUidStats.size();
3046 for (int i=0; i<NU; i++) {
3047 final BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
3048 final int totalUTime = (int)(uid.mCurStepUserTime - uid.mLastStepUserTime);
3049 final int totalSTime = (int)(uid.mCurStepSystemTime - uid.mLastStepSystemTime);
3050 final int totalTime = totalUTime + totalSTime;
3051 uid.mLastStepUserTime = uid.mCurStepUserTime;
3052 uid.mLastStepSystemTime = uid.mCurStepSystemTime;
3053 if (totalTime <= (out.appCpuUTime3+out.appCpuSTime3)) {
3054 continue;
3055 }
3056 if (totalTime <= (out.appCpuUTime2+out.appCpuSTime2)) {
3057 out.appCpuUid3 = uid.mUid;
3058 out.appCpuUTime3 = totalUTime;
3059 out.appCpuSTime3 = totalSTime;
3060 } else {
3061 out.appCpuUid3 = out.appCpuUid2;
3062 out.appCpuUTime3 = out.appCpuUTime2;
3063 out.appCpuSTime3 = out.appCpuSTime2;
3064 if (totalTime <= (out.appCpuUTime1+out.appCpuSTime1)) {
3065 out.appCpuUid2 = uid.mUid;
3066 out.appCpuUTime2 = totalUTime;
3067 out.appCpuSTime2 = totalSTime;
3068 } else {
3069 out.appCpuUid2 = out.appCpuUid1;
3070 out.appCpuUTime2 = out.appCpuUTime1;
3071 out.appCpuSTime2 = out.appCpuSTime1;
3072 out.appCpuUid1 = uid.mUid;
3073 out.appCpuUTime1 = totalUTime;
3074 out.appCpuSTime1 = totalSTime;
3075 }
3076 }
3077 }
3078 mLastStepCpuUserTime = mCurStepCpuUserTime;
3079 mLastStepCpuSystemTime = mCurStepCpuSystemTime;
3080 mLastStepStatUserTime = mCurStepStatUserTime;
3081 mLastStepStatSystemTime = mCurStepStatSystemTime;
3082 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime;
3083 mLastStepStatIrqTime = mCurStepStatIrqTime;
3084 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime;
3085 mLastStepStatIdleTime = mCurStepStatIdleTime;
3086 }
3087
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003088 public void readHistoryDelta(Parcel src, HistoryItem cur) {
3089 int firstToken = src.readInt();
3090 int deltaTimeToken = firstToken&DELTA_TIME_MASK;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003091 cur.cmd = HistoryItem.CMD_UPDATE;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003092 cur.numReadInts = 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003093 if (DEBUG) Slog.i(TAG, "READ DELTA: firstToken=0x" + Integer.toHexString(firstToken)
3094 + " deltaTimeToken=" + deltaTimeToken);
3095
3096 if (deltaTimeToken < DELTA_TIME_ABS) {
3097 cur.time += deltaTimeToken;
3098 } else if (deltaTimeToken == DELTA_TIME_ABS) {
3099 cur.time = src.readLong();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003100 cur.numReadInts += 2;
3101 if (DEBUG) Slog.i(TAG, "READ DELTA: ABS time=" + cur.time);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003102 cur.readFromParcel(src);
3103 return;
3104 } else if (deltaTimeToken == DELTA_TIME_INT) {
3105 int delta = src.readInt();
3106 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003107 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003108 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3109 } else {
3110 long delta = src.readLong();
3111 if (DEBUG) Slog.i(TAG, "READ DELTA: time delta=" + delta + " new time=" + cur.time);
3112 cur.time += delta;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003113 cur.numReadInts += 2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003114 }
3115
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003116 final int batteryLevelInt;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003117 if ((firstToken&DELTA_BATTERY_LEVEL_FLAG) != 0) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003118 batteryLevelInt = src.readInt();
Adam Lesinski3944c812015-11-13 15:54:59 -08003119 readBatteryLevelInt(batteryLevelInt, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003120 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003121 if (DEBUG) Slog.i(TAG, "READ DELTA: batteryToken=0x"
3122 + Integer.toHexString(batteryLevelInt)
3123 + " batteryLevel=" + cur.batteryLevel
3124 + " batteryTemp=" + cur.batteryTemperature
3125 + " batteryVolt=" + (int)cur.batteryVoltage);
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003126 } else {
3127 batteryLevelInt = 0;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003128 }
3129
3130 if ((firstToken&DELTA_STATE_FLAG) != 0) {
3131 int stateInt = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003132 cur.states = (firstToken&DELTA_STATE_MASK) | (stateInt&(~STATE_BATTERY_MASK));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003133 cur.batteryStatus = (byte)((stateInt>>STATE_BATTERY_STATUS_SHIFT)
3134 & STATE_BATTERY_STATUS_MASK);
3135 cur.batteryHealth = (byte)((stateInt>>STATE_BATTERY_HEALTH_SHIFT)
3136 & STATE_BATTERY_HEALTH_MASK);
3137 cur.batteryPlugType = (byte)((stateInt>>STATE_BATTERY_PLUG_SHIFT)
3138 & STATE_BATTERY_PLUG_MASK);
3139 switch (cur.batteryPlugType) {
3140 case 1:
3141 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_AC;
3142 break;
3143 case 2:
3144 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_USB;
3145 break;
3146 case 3:
3147 cur.batteryPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS;
3148 break;
3149 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003150 cur.numReadInts += 1;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003151 if (DEBUG) Slog.i(TAG, "READ DELTA: stateToken=0x"
3152 + Integer.toHexString(stateInt)
3153 + " batteryStatus=" + cur.batteryStatus
3154 + " batteryHealth=" + cur.batteryHealth
3155 + " batteryPlugType=" + cur.batteryPlugType
3156 + " states=0x" + Integer.toHexString(cur.states));
3157 } else {
Adam Lesinski926969b2016-04-28 17:31:12 -07003158 cur.states = (firstToken&DELTA_STATE_MASK) | (cur.states&(~STATE_BATTERY_MASK));
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003159 }
3160
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003161 if ((firstToken&DELTA_STATE2_FLAG) != 0) {
3162 cur.states2 = src.readInt();
3163 if (DEBUG) Slog.i(TAG, "READ DELTA: states2=0x"
3164 + Integer.toHexString(cur.states2));
3165 }
3166
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003167 if ((firstToken&DELTA_WAKELOCK_FLAG) != 0) {
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003168 int indexes = src.readInt();
3169 int wakeLockIndex = indexes&0xffff;
3170 int wakeReasonIndex = (indexes>>16)&0xffff;
3171 if (wakeLockIndex != 0xffff) {
3172 cur.wakelockTag = cur.localWakelockTag;
3173 readHistoryTag(wakeLockIndex, cur.wakelockTag);
3174 if (DEBUG) Slog.i(TAG, "READ DELTA: wakelockTag=#" + cur.wakelockTag.poolIdx
3175 + " " + cur.wakelockTag.uid + ":" + cur.wakelockTag.string);
3176 } else {
3177 cur.wakelockTag = null;
3178 }
3179 if (wakeReasonIndex != 0xffff) {
3180 cur.wakeReasonTag = cur.localWakeReasonTag;
3181 readHistoryTag(wakeReasonIndex, cur.wakeReasonTag);
3182 if (DEBUG) Slog.i(TAG, "READ DELTA: wakeReasonTag=#" + cur.wakeReasonTag.poolIdx
3183 + " " + cur.wakeReasonTag.uid + ":" + cur.wakeReasonTag.string);
3184 } else {
3185 cur.wakeReasonTag = null;
3186 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003187 cur.numReadInts += 1;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003188 } else {
3189 cur.wakelockTag = null;
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003190 cur.wakeReasonTag = null;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003191 }
3192
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003193 if ((firstToken&DELTA_EVENT_FLAG) != 0) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003194 cur.eventTag = cur.localEventTag;
3195 final int codeAndIndex = src.readInt();
Dianne Hackborn099bc622014-01-22 13:39:16 -08003196 cur.eventCode = (codeAndIndex&0xffff);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003197 final int index = ((codeAndIndex>>16)&0xffff);
3198 readHistoryTag(index, cur.eventTag);
3199 cur.numReadInts += 1;
3200 if (DEBUG) Slog.i(TAG, "READ DELTA: event=" + cur.eventCode + " tag=#"
3201 + cur.eventTag.poolIdx + " " + cur.eventTag.uid + ":"
3202 + cur.eventTag.string);
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003203 } else {
3204 cur.eventCode = HistoryItem.EVENT_NONE;
3205 }
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003206
3207 if ((batteryLevelInt&BATTERY_DELTA_LEVEL_FLAG) != 0) {
3208 cur.stepDetails = mReadHistoryStepDetails;
3209 cur.stepDetails.readFromParcel(src);
3210 } else {
3211 cur.stepDetails = null;
3212 }
Adam Lesinski926969b2016-04-28 17:31:12 -07003213
Adam Lesinskia8018ac2016-05-03 10:18:10 -07003214 if ((firstToken&DELTA_BATTERY_CHARGE_FLAG) != 0) {
3215 cur.batteryChargeUAh = src.readInt();
Adam Lesinski926969b2016-04-28 17:31:12 -07003216 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003217 }
3218
Dianne Hackbornfc064132014-06-02 12:42:12 -07003219 @Override
3220 public void commitCurrentHistoryBatchLocked() {
3221 mHistoryLastWritten.cmd = HistoryItem.CMD_NULL;
3222 }
3223
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003224 void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003225 if (!mHaveBatteryLevel || !mRecordingHistory) {
3226 return;
3227 }
3228
Dianne Hackborn40c87252014-03-19 16:55:40 -07003229 final long timeDiff = (mHistoryBaseTime+elapsedRealtimeMs) - mHistoryLastWritten.time;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003230 final int diffStates = mHistoryLastWritten.states^(cur.states&mActiveHistoryStates);
3231 final int diffStates2 = mHistoryLastWritten.states2^(cur.states2&mActiveHistoryStates2);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003232 final int lastDiffStates = mHistoryLastWritten.states^mHistoryLastLastWritten.states;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003233 final int lastDiffStates2 = mHistoryLastWritten.states2^mHistoryLastLastWritten.states2;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003234 if (DEBUG) Slog.i(TAG, "ADD: tdelta=" + timeDiff + " diff="
3235 + Integer.toHexString(diffStates) + " lastDiff="
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003236 + Integer.toHexString(lastDiffStates) + " diff2="
3237 + Integer.toHexString(diffStates2) + " lastDiff2="
3238 + Integer.toHexString(lastDiffStates2));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003239 if (mHistoryBufferLastPos >= 0 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003240 && timeDiff < 1000 && (diffStates&lastDiffStates) == 0
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003241 && (diffStates2&lastDiffStates2) == 0
3242 && (mHistoryLastWritten.wakelockTag == null || cur.wakelockTag == null)
3243 && (mHistoryLastWritten.wakeReasonTag == null || cur.wakeReasonTag == null)
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003244 && mHistoryLastWritten.stepDetails == null
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003245 && (mHistoryLastWritten.eventCode == HistoryItem.EVENT_NONE
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003246 || cur.eventCode == HistoryItem.EVENT_NONE)
3247 && mHistoryLastWritten.batteryLevel == cur.batteryLevel
3248 && mHistoryLastWritten.batteryStatus == cur.batteryStatus
3249 && mHistoryLastWritten.batteryHealth == cur.batteryHealth
3250 && mHistoryLastWritten.batteryPlugType == cur.batteryPlugType
3251 && mHistoryLastWritten.batteryTemperature == cur.batteryTemperature
3252 && mHistoryLastWritten.batteryVoltage == cur.batteryVoltage) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003253 // We can merge this new change in with the last one. Merging is
Dianne Hackborn40c87252014-03-19 16:55:40 -07003254 // allowed as long as only the states have changed, and within those states
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003255 // as long as no bit has changed both between now and the last entry, as
3256 // well as the last entry and the one before it (so we capture any toggles).
3257 if (DEBUG) Slog.i(TAG, "ADD: rewinding back to " + mHistoryBufferLastPos);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003258 mHistoryBuffer.setDataSize(mHistoryBufferLastPos);
3259 mHistoryBuffer.setDataPosition(mHistoryBufferLastPos);
3260 mHistoryBufferLastPos = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003261 elapsedRealtimeMs = mHistoryLastWritten.time - mHistoryBaseTime;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003262 // If the last written history had a wakelock tag, we need to retain it.
3263 // Note that the condition above made sure that we aren't in a case where
3264 // both it and the current history item have a wakelock tag.
3265 if (mHistoryLastWritten.wakelockTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003266 cur.wakelockTag = cur.localWakelockTag;
3267 cur.wakelockTag.setTo(mHistoryLastWritten.wakelockTag);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003268 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003269 // If the last written history had a wake reason tag, we need to retain it.
3270 // Note that the condition above made sure that we aren't in a case where
3271 // both it and the current history item have a wakelock tag.
3272 if (mHistoryLastWritten.wakeReasonTag != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003273 cur.wakeReasonTag = cur.localWakeReasonTag;
3274 cur.wakeReasonTag.setTo(mHistoryLastWritten.wakeReasonTag);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003275 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003276 // If the last written history had an event, we need to retain it.
3277 // Note that the condition above made sure that we aren't in a case where
3278 // both it and the current history item have an event.
3279 if (mHistoryLastWritten.eventCode != HistoryItem.EVENT_NONE) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003280 cur.eventCode = mHistoryLastWritten.eventCode;
3281 cur.eventTag = cur.localEventTag;
3282 cur.eventTag.setTo(mHistoryLastWritten.eventTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003283 }
Dianne Hackborn1fadab52011-04-14 17:57:33 -07003284 mHistoryLastWritten.setTo(mHistoryLastLastWritten);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003285 }
3286
Adam Lesinski45489782016-12-15 23:45:17 -08003287 boolean recordResetDueToOverflow = false;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003288 final int dataSize = mHistoryBuffer.dataSize();
Adam Lesinski45489782016-12-15 23:45:17 -08003289 if (dataSize >= MAX_MAX_HISTORY_BUFFER*3) {
3290 // Clients can't deal with history buffers this large. This only
3291 // really happens when the device is on charger and interacted with
3292 // for long periods of time, like in retail mode. Since the device is
3293 // most likely charged, when unplugged, stats would have reset anyways.
3294 // Reset the stats and mark that we overflowed.
3295 // b/32540341
3296 resetAllStatsLocked();
3297
3298 // Mark that we want to set *OVERFLOW* event and the RESET:START
3299 // events.
3300 recordResetDueToOverflow = true;
3301
3302 } else if (dataSize >= MAX_HISTORY_BUFFER) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003303 if (!mHistoryOverflow) {
3304 mHistoryOverflow = true;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003305 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
3306 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003307 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003308 }
3309
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003310 // After overflow, we allow various bit-wise states to settle to 0.
3311 boolean writeAnyway = false;
3312 final int curStates = cur.states & HistoryItem.SETTLE_TO_ZERO_STATES
3313 & mActiveHistoryStates;
3314 if (mHistoryLastWritten.states != curStates) {
3315 // mActiveHistoryStates keeps track of which bits in .states are now being
3316 // forced to 0.
3317 int old = mActiveHistoryStates;
3318 mActiveHistoryStates &= curStates | ~HistoryItem.SETTLE_TO_ZERO_STATES;
3319 writeAnyway |= old != mActiveHistoryStates;
3320 }
3321 final int curStates2 = cur.states2 & HistoryItem.SETTLE_TO_ZERO_STATES2
3322 & mActiveHistoryStates2;
3323 if (mHistoryLastWritten.states2 != curStates2) {
3324 // mActiveHistoryStates2 keeps track of which bits in .states2 are now being
3325 // forced to 0.
3326 int old = mActiveHistoryStates2;
3327 mActiveHistoryStates2 &= curStates2 | ~HistoryItem.SETTLE_TO_ZERO_STATES2;
3328 writeAnyway |= old != mActiveHistoryStates2;
3329 }
3330
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003331 // Once we've reached the maximum number of items, we only
3332 // record changes to the battery level and the most interesting states.
3333 // Once we've reached the maximum maximum number of items, we only
3334 // record changes to the battery level.
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003335 if (!writeAnyway && mHistoryLastWritten.batteryLevel == cur.batteryLevel &&
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003336 (dataSize >= MAX_MAX_HISTORY_BUFFER
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003337 || ((mHistoryLastWritten.states^cur.states)
Dianne Hackborn3251b902014-06-20 14:40:53 -07003338 & HistoryItem.MOST_INTERESTING_STATES) == 0
3339 || ((mHistoryLastWritten.states2^cur.states2)
3340 & HistoryItem.MOST_INTERESTING_STATES2) == 0)) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003341 return;
3342 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003343
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003344 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003345 return;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003346 }
3347
Adam Lesinski45489782016-12-15 23:45:17 -08003348 if (dataSize == 0 || recordResetDueToOverflow) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003349 // The history is currently empty; we need it to start with a time stamp.
3350 cur.currentTime = System.currentTimeMillis();
Adam Lesinski45489782016-12-15 23:45:17 -08003351 if (recordResetDueToOverflow) {
3352 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_OVERFLOW, cur);
3353 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003354 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_RESET, cur);
3355 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003356 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003357 }
3358
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003359 private void addHistoryBufferLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd,
3360 HistoryItem cur) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003361 if (mIteratingHistory) {
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003362 throw new IllegalStateException("Can't do this while iterating history!");
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003363 }
3364 mHistoryBufferLastPos = mHistoryBuffer.dataPosition();
3365 mHistoryLastLastWritten.setTo(mHistoryLastWritten);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003366 mHistoryLastWritten.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003367 mHistoryLastWritten.states &= mActiveHistoryStates;
3368 mHistoryLastWritten.states2 &= mActiveHistoryStates2;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08003369 writeHistoryDelta(mHistoryBuffer, mHistoryLastWritten, mHistoryLastLastWritten);
Dianne Hackborn40c87252014-03-19 16:55:40 -07003370 mLastHistoryElapsedRealtime = elapsedRealtimeMs;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003371 cur.wakelockTag = null;
3372 cur.wakeReasonTag = null;
3373 cur.eventCode = HistoryItem.EVENT_NONE;
3374 cur.eventTag = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003375 if (DEBUG_HISTORY) Slog.i(TAG, "Writing history buffer: was " + mHistoryBufferLastPos
3376 + " now " + mHistoryBuffer.dataPosition()
3377 + " size is now " + mHistoryBuffer.dataSize());
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003378 }
3379
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003380 int mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003381 int mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003382
Dianne Hackborn40c87252014-03-19 16:55:40 -07003383 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003384 if (mTrackRunningHistoryElapsedRealtime != 0) {
3385 final long diffElapsed = elapsedRealtimeMs - mTrackRunningHistoryElapsedRealtime;
3386 final long diffUptime = uptimeMs - mTrackRunningHistoryUptime;
3387 if (diffUptime < (diffElapsed-20)) {
3388 final long wakeElapsedTime = elapsedRealtimeMs - (diffElapsed - diffUptime);
3389 mHistoryAddTmp.setTo(mHistoryLastWritten);
3390 mHistoryAddTmp.wakelockTag = null;
3391 mHistoryAddTmp.wakeReasonTag = null;
3392 mHistoryAddTmp.eventCode = HistoryItem.EVENT_NONE;
3393 mHistoryAddTmp.states &= ~HistoryItem.STATE_CPU_RUNNING_FLAG;
3394 addHistoryRecordInnerLocked(wakeElapsedTime, uptimeMs, mHistoryAddTmp);
3395 }
3396 }
3397 mHistoryCur.states |= HistoryItem.STATE_CPU_RUNNING_FLAG;
3398 mTrackRunningHistoryElapsedRealtime = elapsedRealtimeMs;
3399 mTrackRunningHistoryUptime = uptimeMs;
3400 addHistoryRecordInnerLocked(elapsedRealtimeMs, uptimeMs, mHistoryCur);
3401 }
3402
3403 void addHistoryRecordInnerLocked(long elapsedRealtimeMs, long uptimeMs, HistoryItem cur) {
3404 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, cur);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003405
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003406 if (!USE_OLD_HISTORY) {
3407 return;
3408 }
3409
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003410 if (!mHaveBatteryLevel || !mRecordingHistory) {
3411 return;
3412 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003413
3414 // If the current time is basically the same as the last time,
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003415 // and no states have since the last recorded entry changed and
3416 // are now resetting back to their original value, then just collapse
3417 // into one record.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003418 if (mHistoryEnd != null && mHistoryEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003419 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+1000)
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003420 && ((mHistoryEnd.states^cur.states)&mChangedStates&mActiveHistoryStates) == 0
3421 && ((mHistoryEnd.states2^cur.states2)&mChangedStates2&mActiveHistoryStates2) == 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003422 // If the current is the same as the one before, then we no
3423 // longer need the entry.
3424 if (mHistoryLastEnd != null && mHistoryLastEnd.cmd == HistoryItem.CMD_UPDATE
Dianne Hackborn40c87252014-03-19 16:55:40 -07003425 && (mHistoryBaseTime+elapsedRealtimeMs) < (mHistoryEnd.time+500)
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003426 && mHistoryLastEnd.sameNonEvent(cur)) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003427 mHistoryLastEnd.next = null;
3428 mHistoryEnd.next = mHistoryCache;
3429 mHistoryCache = mHistoryEnd;
3430 mHistoryEnd = mHistoryLastEnd;
3431 mHistoryLastEnd = null;
3432 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003433 mChangedStates |= mHistoryEnd.states^(cur.states&mActiveHistoryStates);
3434 mChangedStates2 |= mHistoryEnd.states^(cur.states2&mActiveHistoryStates2);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003435 mHistoryEnd.setTo(mHistoryEnd.time, HistoryItem.CMD_UPDATE, cur);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003436 }
3437 return;
3438 }
3439
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003440 mChangedStates = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003441 mChangedStates2 = 0;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003442
3443 if (mNumHistoryItems == MAX_HISTORY_ITEMS
3444 || mNumHistoryItems == MAX_MAX_HISTORY_ITEMS) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07003445 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_OVERFLOW);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003446 }
3447
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003448 if (mNumHistoryItems >= MAX_HISTORY_ITEMS) {
3449 // Once we've reached the maximum number of items, we only
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003450 // record changes to the battery level and the most interesting states.
3451 // Once we've reached the maximum maximum number of items, we only
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003452 // record changes to the battery level.
3453 if (mHistoryEnd != null && mHistoryEnd.batteryLevel
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003454 == cur.batteryLevel &&
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003455 (mNumHistoryItems >= MAX_MAX_HISTORY_ITEMS
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003456 || ((mHistoryEnd.states^(cur.states&mActiveHistoryStates))
Dianne Hackbornf47d8f22010-10-08 10:46:55 -07003457 & HistoryItem.MOST_INTERESTING_STATES) == 0)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003458 return;
3459 }
3460 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003461
Dianne Hackborn40c87252014-03-19 16:55:40 -07003462 addHistoryRecordLocked(elapsedRealtimeMs, HistoryItem.CMD_UPDATE);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003463 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003464
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003465 public void addHistoryEventLocked(long elapsedRealtimeMs, long uptimeMs, int code,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003466 String name, int uid) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003467 mHistoryCur.eventCode = code;
3468 mHistoryCur.eventTag = mHistoryCur.localEventTag;
3469 mHistoryCur.eventTag.string = name;
3470 mHistoryCur.eventTag.uid = uid;
Dianne Hackborn4590e522014-03-24 13:36:46 -07003471 addHistoryRecordLocked(elapsedRealtimeMs, uptimeMs);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003472 }
3473
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003474 void addHistoryRecordLocked(long elapsedRealtimeMs, long uptimeMs, byte cmd, HistoryItem cur) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003475 HistoryItem rec = mHistoryCache;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003476 if (rec != null) {
3477 mHistoryCache = rec.next;
3478 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003479 rec = new HistoryItem();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003480 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003481 rec.setTo(mHistoryBaseTime + elapsedRealtimeMs, cmd, cur);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003482
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003483 addHistoryRecordLocked(rec);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003484 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003485
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003486 void addHistoryRecordLocked(HistoryItem rec) {
3487 mNumHistoryItems++;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003488 rec.next = null;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003489 mHistoryLastEnd = mHistoryEnd;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003490 if (mHistoryEnd != null) {
3491 mHistoryEnd.next = rec;
3492 mHistoryEnd = rec;
3493 } else {
3494 mHistory = mHistoryEnd = rec;
3495 }
3496 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003497
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003498 void clearHistoryLocked() {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003499 if (DEBUG_HISTORY) Slog.i(TAG, "********** CLEARING HISTORY!");
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003500 if (USE_OLD_HISTORY) {
3501 if (mHistory != null) {
3502 mHistoryEnd.next = mHistoryCache;
3503 mHistoryCache = mHistory;
3504 mHistory = mHistoryLastEnd = mHistoryEnd = null;
3505 }
3506 mNumHistoryItems = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003507 }
Dianne Hackborne8c88e62011-08-17 19:09:09 -07003508
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07003509 mHistoryBaseTime = 0;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003510 mLastHistoryElapsedRealtime = 0;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003511 mTrackRunningHistoryElapsedRealtime = 0;
3512 mTrackRunningHistoryUptime = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003513
3514 mHistoryBuffer.setDataSize(0);
3515 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003516 mHistoryBuffer.setDataCapacity(MAX_HISTORY_BUFFER / 2);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003517 mHistoryLastLastWritten.clear();
3518 mHistoryLastWritten.clear();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003519 mHistoryTagPool.clear();
3520 mNextHistoryTagIdx = 0;
3521 mNumHistoryTagChars = 0;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07003522 mHistoryBufferLastPos = -1;
3523 mHistoryOverflow = false;
Dianne Hackborn0c820db2015-04-14 17:47:34 -07003524 mActiveHistoryStates = 0xffffffff;
3525 mActiveHistoryStates2 = 0xffffffff;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003526 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07003527
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003528 public void updateTimeBasesLocked(boolean unplugged, boolean screenOff, long uptime,
3529 long realtime) {
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003530 final boolean updateOnBatteryTimeBase = unplugged != mOnBatteryTimeBase.isRunning();
3531 final boolean updateOnBatteryScreenOffTimeBase =
3532 (unplugged && screenOff) != mOnBatteryScreenOffTimeBase.isRunning();
Bookatz867c0d72017-03-07 18:23:42 -08003533
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003534 if (updateOnBatteryScreenOffTimeBase || updateOnBatteryTimeBase) {
3535 if (updateOnBatteryScreenOffTimeBase) {
3536 updateKernelWakelocksLocked();
3537 updateBatteryPropertiesLocked();
Bookatz867c0d72017-03-07 18:23:42 -08003538 }
Adam Lesinski72478f02015-06-17 15:39:43 -07003539 if (DEBUG_ENERGY_CPU) {
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003540 Slog.d(TAG, "Updating cpu time because screen is now " + (screenOff ? "off" : "on")
3541 + " and battery is " + (unplugged ? "on" : "off"));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003542 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -07003543 updateCpuTimeLocked();
Sudheer Shanka9d4ed7c2017-07-08 22:10:45 -07003544
3545 mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
3546 mOnBatteryScreenOffTimeBase.setRunning(unplugged && screenOff, uptime, realtime);
3547 for (int i = mUidStats.size() - 1; i >= 0; --i) {
3548 final Uid u = mUidStats.valueAt(i);
3549 if (updateOnBatteryTimeBase) {
3550 u.updateOnBatteryBgTimeBase(uptime, realtime);
3551 }
3552 if (updateOnBatteryScreenOffTimeBase) {
3553 u.updateOnBatteryScreenOffBgTimeBase(uptime, realtime);
3554 }
Bookatzc8c44962017-05-11 12:12:54 -07003555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 }
3557 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07003558
Adam Lesinskie1f480d2017-02-15 18:51:23 -08003559 private void updateBatteryPropertiesLocked() {
3560 try {
3561 IBatteryPropertiesRegistrar registrar = IBatteryPropertiesRegistrar.Stub.asInterface(
3562 ServiceManager.getService("batteryproperties"));
3563 registrar.scheduleUpdate();
3564 } catch (RemoteException e) {
3565 // Ignore.
3566 }
3567 }
3568
Dianne Hackborn099bc622014-01-22 13:39:16 -08003569 public void addIsolatedUidLocked(int isolatedUid, int appUid) {
3570 mIsolatedUids.put(isolatedUid, appUid);
3571 }
3572
Adam Lesinski61db88f2015-07-01 15:05:07 -07003573 /**
3574 * Schedules a read of the latest cpu times before removing the isolated UID.
3575 * @see #removeIsolatedUidLocked(int)
3576 */
3577 public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003578 int curUid = mIsolatedUids.get(isolatedUid, -1);
3579 if (curUid == appUid) {
Adam Lesinski61db88f2015-07-01 15:05:07 -07003580 if (mExternalSync != null) {
3581 mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
3582 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08003583 }
3584 }
3585
Adam Lesinski61db88f2015-07-01 15:05:07 -07003586 /**
3587 * This should only be called after the cpu times have been read.
3588 * @see #scheduleRemoveIsolatedUidLocked(int, int)
3589 */
3590 public void removeIsolatedUidLocked(int isolatedUid) {
3591 mIsolatedUids.delete(isolatedUid);
3592 mKernelUidCpuTimeReader.removeUid(isolatedUid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -07003593 mKernelUidCpuFreqTimeReader.removeUid(isolatedUid);
Adam Lesinski61db88f2015-07-01 15:05:07 -07003594 }
3595
Dianne Hackborn099bc622014-01-22 13:39:16 -08003596 public int mapUid(int uid) {
3597 int isolated = mIsolatedUids.get(uid, -1);
3598 return isolated > 0 ? isolated : uid;
3599 }
3600
3601 public void noteEventLocked(int code, String name, int uid) {
3602 uid = mapUid(uid);
Dianne Hackborn37de0982014-05-09 09:32:18 -07003603 if (!mActiveEvents.updateState(code, name, uid, 0)) {
3604 return;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08003605 }
Joe Onoratoabded112016-02-08 16:49:39 -08003606 final long elapsedRealtime = mClocks.elapsedRealtime();
3607 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07003608 addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -08003609 }
3610
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003611 boolean ensureStartClockTime(final long currentTime) {
3612 final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
3613 if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
3614 // If the start clock time has changed by more than a year, then presumably
3615 // the previous time was completely bogus. So we are going to figure out a
3616 // new time based on how much time has elapsed since we started counting.
Joe Onoratoabded112016-02-08 16:49:39 -08003617 mStartClockTime = currentTime - (mClocks.elapsedRealtime()-(mRealtimeStart/1000));
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003618 return true;
3619 }
3620 return false;
3621 }
3622
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003623 public void noteCurrentTimeChangedLocked() {
3624 final long currentTime = System.currentTimeMillis();
Joe Onoratoabded112016-02-08 16:49:39 -08003625 final long elapsedRealtime = mClocks.elapsedRealtime();
3626 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003627 recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
Dianne Hackbornd48954f2015-07-22 17:20:33 -07003628 ensureStartClockTime(currentTime);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07003629 }
3630
Dianne Hackborn61659e52014-07-09 16:13:01 -07003631 public void noteProcessStartLocked(String name, int uid) {
3632 uid = mapUid(uid);
3633 if (isOnBattery()) {
3634 Uid u = getUidStatsLocked(uid);
3635 u.getProcessStatsLocked(name).incStartsLocked();
3636 }
3637 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_START, name, uid, 0)) {
3638 return;
3639 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003640 if (!mRecordAllHistory) {
3641 return;
3642 }
Joe Onoratoabded112016-02-08 16:49:39 -08003643 final long elapsedRealtime = mClocks.elapsedRealtime();
3644 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn61659e52014-07-09 16:13:01 -07003645 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_START, name, uid);
3646 }
3647
Dianne Hackborn1e01d162014-12-04 17:46:42 -08003648 public void noteProcessCrashLocked(String name, int uid) {
3649 uid = mapUid(uid);
3650 if (isOnBattery()) {
3651 Uid u = getUidStatsLocked(uid);
3652 u.getProcessStatsLocked(name).incNumCrashesLocked();
3653 }
3654 }
3655
3656 public void noteProcessAnrLocked(String name, int uid) {
3657 uid = mapUid(uid);
3658 if (isOnBattery()) {
3659 Uid u = getUidStatsLocked(uid);
3660 u.getProcessStatsLocked(name).incNumAnrsLocked();
3661 }
3662 }
3663
Dianne Hackborna8d10942015-11-19 17:55:19 -08003664 public void noteUidProcessStateLocked(int uid, int state) {
Amith Yamasanifd3caf62017-07-26 11:48:35 -07003665 int parentUid = mapUid(uid);
3666 if (uid != parentUid) {
3667 // Isolated UIDs process state is already rolled up into parent, so no need to track
3668 // Otherwise the parent's process state will get downgraded incorrectly
3669 return;
3670 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08003671 getUidStatsLocked(uid).updateUidProcessStateLocked(state);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003672 }
3673
3674 public void noteProcessFinishLocked(String name, int uid) {
3675 uid = mapUid(uid);
3676 if (!mActiveEvents.updateState(HistoryItem.EVENT_PROC_FINISH, name, uid, 0)) {
3677 return;
3678 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003679 if (!mRecordAllHistory) {
3680 return;
3681 }
Joe Onoratoabded112016-02-08 16:49:39 -08003682 final long elapsedRealtime = mClocks.elapsedRealtime();
3683 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003684 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PROC_FINISH, name, uid);
Dianne Hackborn61659e52014-07-09 16:13:01 -07003685 }
3686
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003687 public void noteSyncStartLocked(String name, int uid) {
3688 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003689 final long elapsedRealtime = mClocks.elapsedRealtime();
3690 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003691 getUidStatsLocked(uid).noteStartSyncLocked(name, elapsedRealtime);
3692 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_START, name, uid, 0)) {
3693 return;
3694 }
3695 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_START, name, uid);
3696 }
3697
3698 public void noteSyncFinishLocked(String name, int uid) {
3699 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003700 final long elapsedRealtime = mClocks.elapsedRealtime();
3701 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003702 getUidStatsLocked(uid).noteStopSyncLocked(name, elapsedRealtime);
3703 if (!mActiveEvents.updateState(HistoryItem.EVENT_SYNC_FINISH, name, uid, 0)) {
3704 return;
3705 }
3706 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SYNC_FINISH, name, uid);
3707 }
3708
3709 public void noteJobStartLocked(String name, int uid) {
3710 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003711 final long elapsedRealtime = mClocks.elapsedRealtime();
3712 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003713 getUidStatsLocked(uid).noteStartJobLocked(name, elapsedRealtime);
3714 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_START, name, uid, 0)) {
3715 return;
3716 }
3717 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_START, name, uid);
3718 }
3719
Dianne Hackborn94326cb2017-06-28 16:17:20 -07003720 public void noteJobFinishLocked(String name, int uid, int stopReason) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003721 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003722 final long elapsedRealtime = mClocks.elapsedRealtime();
3723 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07003724 getUidStatsLocked(uid).noteStopJobLocked(name, elapsedRealtime, stopReason);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07003725 if (!mActiveEvents.updateState(HistoryItem.EVENT_JOB_FINISH, name, uid, 0)) {
3726 return;
3727 }
3728 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_JOB_FINISH, name, uid);
3729 }
3730
Dianne Hackborn1e383822015-04-10 14:02:33 -07003731 public void noteAlarmStartLocked(String name, int uid) {
3732 if (!mRecordAllHistory) {
3733 return;
3734 }
3735 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003736 final long elapsedRealtime = mClocks.elapsedRealtime();
3737 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e383822015-04-10 14:02:33 -07003738 if (!mActiveEvents.updateState(HistoryItem.EVENT_ALARM_START, name, uid, 0)) {
3739 return;
3740 }
3741 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ALARM_START, name, uid);
3742 }
3743
3744 public void noteAlarmFinishLocked(String name, int uid) {
3745 if (!mRecordAllHistory) {
3746 return;
3747 }
3748 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08003749 final long elapsedRealtime = mClocks.elapsedRealtime();
3750 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e383822015-04-10 14:02:33 -07003751 if (!mActiveEvents.updateState(HistoryItem.EVENT_ALARM_FINISH, name, uid, 0)) {
3752 return;
3753 }
3754 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ALARM_FINISH, name, uid);
3755 }
3756
Dianne Hackborn97ae5382014-03-05 16:43:25 -08003757 private void requestWakelockCpuUpdate() {
3758 if (!mHandler.hasMessages(MSG_UPDATE_WAKELOCKS)) {
3759 Message m = mHandler.obtainMessage(MSG_UPDATE_WAKELOCKS);
3760 mHandler.sendMessageDelayed(m, DELAY_UPDATE_WAKELOCKS);
3761 }
3762 }
3763
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08003764 private void requestImmediateCpuUpdate() {
3765 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
3766 mHandler.sendEmptyMessage(MSG_UPDATE_WAKELOCKS);
3767 }
3768
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003769 public void setRecordAllHistoryLocked(boolean enabled) {
3770 mRecordAllHistory = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003771 if (!enabled) {
3772 // Clear out any existing state.
3773 mActiveEvents.removeEvents(HistoryItem.EVENT_WAKE_LOCK);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003774 mActiveEvents.removeEvents(HistoryItem.EVENT_ALARM);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003775 // Record the currently running processes as stopping, now that we are no
3776 // longer tracking them.
3777 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
3778 HistoryItem.EVENT_PROC);
3779 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08003780 long mSecRealtime = mClocks.elapsedRealtime();
3781 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003782 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
3783 SparseIntArray uids = ent.getValue();
3784 for (int j=0; j<uids.size(); j++) {
3785 addHistoryEventLocked(mSecRealtime, mSecUptime,
3786 HistoryItem.EVENT_PROC_FINISH, ent.getKey(), uids.keyAt(j));
3787 }
3788 }
3789 }
3790 } else {
3791 // Record the currently running processes as starting, now that we are tracking them.
3792 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(
3793 HistoryItem.EVENT_PROC);
3794 if (active != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08003795 long mSecRealtime = mClocks.elapsedRealtime();
3796 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003797 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
3798 SparseIntArray uids = ent.getValue();
3799 for (int j=0; j<uids.size(); j++) {
3800 addHistoryEventLocked(mSecRealtime, mSecUptime,
3801 HistoryItem.EVENT_PROC_START, ent.getKey(), uids.keyAt(j));
3802 }
3803 }
3804 }
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003805 }
3806 }
3807
Dianne Hackborn9a755432014-05-15 17:05:22 -07003808 public void setNoAutoReset(boolean enabled) {
3809 mNoAutoReset = enabled;
3810 }
3811
Amith Yamasani674c9bb2017-02-01 09:45:17 -08003812 public void setPretendScreenOff(boolean pretendScreenOff) {
3813 mPretendScreenOff = pretendScreenOff;
3814 noteScreenStateLocked(pretendScreenOff ? Display.STATE_OFF : Display.STATE_ON);
3815 }
3816
Dianne Hackborn9a755432014-05-15 17:05:22 -07003817 private String mInitialAcquireWakeName;
3818 private int mInitialAcquireWakeUid = -1;
3819
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003820 public void noteStartWakeLocked(int uid, int pid, String name, String historyName, int type,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003821 boolean unimportantForLogging, long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003822 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003823 if (type == WAKE_TYPE_PARTIAL) {
3824 // Only care about partial wake locks, since full wake locks
3825 // will be canceled when the user puts the screen to sleep.
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003826 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07003827 if (historyName == null) {
3828 historyName = name;
3829 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003830 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07003831 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_START, historyName,
3832 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07003833 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07003834 HistoryItem.EVENT_WAKE_LOCK_START, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07003835 }
3836 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003837 if (mWakeLockNesting == 0) {
3838 mHistoryCur.states |= HistoryItem.STATE_WAKE_LOCK_FLAG;
3839 if (DEBUG_HISTORY) Slog.v(TAG, "Start wake lock to: "
3840 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08003841 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003842 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07003843 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003844 mWakeLockImportant = !unimportantForLogging;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003845 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornfc064132014-06-02 12:42:12 -07003846 } else if (!mWakeLockImportant && !unimportantForLogging
3847 && mHistoryLastWritten.cmd == HistoryItem.CMD_UPDATE) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003848 if (mHistoryLastWritten.wakelockTag != null) {
3849 // We'll try to update the last tag.
3850 mHistoryLastWritten.wakelockTag = null;
3851 mHistoryCur.wakelockTag = mHistoryCur.localWakelockTag;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003852 mHistoryCur.wakelockTag.string = mInitialAcquireWakeName = historyName;
Dianne Hackborn37de0982014-05-09 09:32:18 -07003853 mHistoryCur.wakelockTag.uid = mInitialAcquireWakeUid = uid;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003854 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003855 }
3856 mWakeLockImportant = true;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003857 }
3858 mWakeLockNesting++;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003859 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003860 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07003861 if (mOnBatteryScreenOffTimeBase.isRunning()) {
3862 // We only update the cpu time when a wake lock is acquired if the screen is off.
3863 // If the screen is on, we don't distribute the power amongst partial wakelocks.
3864 if (DEBUG_ENERGY_CPU) {
3865 Slog.d(TAG, "Updating cpu time because of +wake_lock");
3866 }
3867 requestWakelockCpuUpdate();
3868 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08003869 getUidStatsLocked(uid).noteStartWakeLocked(pid, name, type, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003870 }
3871 }
3872
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003873 public void noteStopWakeLocked(int uid, int pid, String name, String historyName, int type,
3874 long elapsedRealtime, long uptime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08003875 uid = mapUid(uid);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003876 if (type == WAKE_TYPE_PARTIAL) {
3877 mWakeLockNesting--;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07003878 if (mRecordAllHistory) {
Dianne Hackbornfc064132014-06-02 12:42:12 -07003879 if (historyName == null) {
3880 historyName = name;
3881 }
3882 if (mActiveEvents.updateState(HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName,
3883 uid, 0)) {
Dianne Hackborn536456f2014-05-23 16:51:05 -07003884 addHistoryEventLocked(elapsedRealtime, uptime,
Dianne Hackbornfc064132014-06-02 12:42:12 -07003885 HistoryItem.EVENT_WAKE_LOCK_FINISH, historyName, uid);
Dianne Hackborn536456f2014-05-23 16:51:05 -07003886 }
3887 }
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003888 if (mWakeLockNesting == 0) {
3889 mHistoryCur.states &= ~HistoryItem.STATE_WAKE_LOCK_FLAG;
3890 if (DEBUG_HISTORY) Slog.v(TAG, "Stop wake lock to: "
3891 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn37de0982014-05-09 09:32:18 -07003892 mInitialAcquireWakeName = null;
3893 mInitialAcquireWakeUid = -1;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003894 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07003895 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003896 }
3897 if (uid >= 0) {
Adam Lesinski72478f02015-06-17 15:39:43 -07003898 if (mOnBatteryScreenOffTimeBase.isRunning()) {
3899 if (DEBUG_ENERGY_CPU) {
3900 Slog.d(TAG, "Updating cpu time because of -wake_lock");
3901 }
3902 requestWakelockCpuUpdate();
3903 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08003904 getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003905 }
3906 }
3907
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003908 public void noteStartWakeFromSourceLocked(WorkSource ws, int pid, String name,
3909 String historyName, int type, boolean unimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08003910 final long elapsedRealtime = mClocks.elapsedRealtime();
3911 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003912 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003913 for (int i=0; i<N; i++) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003914 noteStartWakeLocked(ws.get(i), pid, name, historyName, type, unimportantForLogging,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003915 elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003916 }
3917 }
3918
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003919 public void noteChangeWakelockFromSourceLocked(WorkSource ws, int pid, String name,
3920 String historyName, int type, WorkSource newWs, int newPid, String newName,
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003921 String newHistoryName, int newType, boolean newUnimportantForLogging) {
Joe Onoratoabded112016-02-08 16:49:39 -08003922 final long elapsedRealtime = mClocks.elapsedRealtime();
3923 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003924 // For correct semantics, we start the need worksources first, so that we won't
3925 // make inappropriate history items as if all wake locks went away and new ones
3926 // appeared. This is okay because tracking of wake locks allows nesting.
Dianne Hackborn40c87252014-03-19 16:55:40 -07003927 final int NN = newWs.size();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003928 for (int i=0; i<NN; i++) {
3929 noteStartWakeLocked(newWs.get(i), newPid, newName, newHistoryName, newType,
Dianne Hackborn40c87252014-03-19 16:55:40 -07003930 newUnimportantForLogging, elapsedRealtime, uptime);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003931 }
3932 final int NO = ws.size();
3933 for (int i=0; i<NO; i++) {
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003934 noteStopWakeLocked(ws.get(i), pid, name, historyName, type, elapsedRealtime, uptime);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003935 }
3936 }
3937
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003938 public void noteStopWakeFromSourceLocked(WorkSource ws, int pid, String name,
3939 String historyName, int type) {
Joe Onoratoabded112016-02-08 16:49:39 -08003940 final long elapsedRealtime = mClocks.elapsedRealtime();
3941 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -08003942 final int N = ws.size();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003943 for (int i=0; i<N; i++) {
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07003944 noteStopWakeLocked(ws.get(i), pid, name, historyName, type, elapsedRealtime, uptime);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07003945 }
3946 }
3947
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003948 public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
3949 uid = mapUid(uid);
3950 final long elapsedRealtime = mClocks.elapsedRealtime();
3951 final long uptime = mClocks.uptimeMillis();
3952 if (historyName == null) {
3953 historyName = name;
3954 }
3955 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_START, historyName, uid,
3956 0)) {
3957 return;
3958 }
3959 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_START,
3960 historyName, uid);
3961 }
3962
3963 public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
3964 uid = mapUid(uid);
3965 final long elapsedRealtime = mClocks.elapsedRealtime();
3966 final long uptime = mClocks.uptimeMillis();
3967 if (historyName == null) {
3968 historyName = name;
3969 }
3970 if (!mActiveEvents.updateState(HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH, historyName, uid,
3971 0)) {
3972 return;
3973 }
3974 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_LONG_WAKE_LOCK_FINISH,
3975 historyName, uid);
3976 }
3977
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003978 void aggregateLastWakeupUptimeLocked(long uptimeMs) {
3979 if (mLastWakeupReason != null) {
3980 long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003981 SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
Adam Lesinski757c6ea2016-04-21 09:55:41 -07003982 timer.add(deltaUptime * 1000, 1); // time in in microseconds
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003983 mLastWakeupReason = null;
3984 }
3985 }
3986
3987 public void noteWakeupReasonLocked(String reason) {
Joe Onoratoabded112016-02-08 16:49:39 -08003988 final long elapsedRealtime = mClocks.elapsedRealtime();
3989 final long uptime = mClocks.uptimeMillis();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07003990 if (DEBUG_HISTORY) Slog.v(TAG, "Wakeup reason \"" + reason +"\": "
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003991 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003992 aggregateLastWakeupUptimeLocked(uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003993 mHistoryCur.wakeReasonTag = mHistoryCur.localWakeReasonTag;
3994 mHistoryCur.wakeReasonTag.string = reason;
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003995 mHistoryCur.wakeReasonTag.uid = 0;
3996 mLastWakeupReason = reason;
3997 mLastWakeupUptimeMs = uptime;
Dianne Hackborn40c87252014-03-19 16:55:40 -07003998 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornc51cf032014-03-02 19:08:15 -08003999 }
4000
Adam Lesinski72478f02015-06-17 15:39:43 -07004001 public boolean startAddingCpuLocked() {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004002 mHandler.removeMessages(MSG_UPDATE_WAKELOCKS);
Adam Lesinski72478f02015-06-17 15:39:43 -07004003 return mOnBatteryInternal;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004004 }
4005
Adam Lesinski72478f02015-06-17 15:39:43 -07004006 public void finishAddingCpuLocked(int totalUTime, int totalSTime, int statUserTime,
4007 int statSystemTime, int statIOWaitTime, int statIrqTime,
4008 int statSoftIrqTime, int statIdleTime) {
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08004009 if (DEBUG) Slog.d(TAG, "Adding cpu: tuser=" + totalUTime + " tsys=" + totalSTime
4010 + " user=" + statUserTime + " sys=" + statSystemTime
4011 + " io=" + statIOWaitTime + " irq=" + statIrqTime
4012 + " sirq=" + statSoftIrqTime + " idle=" + statIdleTime);
4013 mCurStepCpuUserTime += totalUTime;
4014 mCurStepCpuSystemTime += totalSTime;
4015 mCurStepStatUserTime += statUserTime;
4016 mCurStepStatSystemTime += statSystemTime;
4017 mCurStepStatIOWaitTime += statIOWaitTime;
4018 mCurStepStatIrqTime += statIrqTime;
4019 mCurStepStatSoftIrqTime += statSoftIrqTime;
4020 mCurStepStatIdleTime += statIdleTime;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07004021 }
4022
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004023 public void noteProcessDiedLocked(int uid, int pid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004024 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004025 Uid u = mUidStats.get(uid);
4026 if (u != null) {
4027 u.mPids.remove(pid);
4028 }
4029 }
4030
4031 public long getProcessWakeTime(int uid, int pid, long realtime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004032 uid = mapUid(uid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004033 Uid u = mUidStats.get(uid);
4034 if (u != null) {
4035 Uid.Pid p = u.mPids.get(pid);
4036 if (p != null) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004037 return p.mWakeSumMs + (p.mWakeNesting > 0 ? (realtime - p.mWakeStartMs) : 0);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004038 }
4039 }
4040 return 0;
4041 }
4042
Dianne Hackborn287952c2010-09-22 22:34:31 -07004043 public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004044 uid = mapUid(uid);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004045 Uid u = mUidStats.get(uid);
4046 if (u != null) {
4047 u.reportExcessiveCpuLocked(proc, overTime, usedTime);
4048 }
4049 }
4050
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004051 int mSensorNesting;
4052
4053 public void noteStartSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004054 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004055 final long elapsedRealtime = mClocks.elapsedRealtime();
4056 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004057 if (mSensorNesting == 0) {
4058 mHistoryCur.states |= HistoryItem.STATE_SENSOR_ON_FLAG;
4059 if (DEBUG_HISTORY) Slog.v(TAG, "Start sensor to: "
4060 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004061 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004062 }
4063 mSensorNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004064 getUidStatsLocked(uid).noteStartSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004065 }
4066
4067 public void noteStopSensorLocked(int uid, int sensor) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004068 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004069 final long elapsedRealtime = mClocks.elapsedRealtime();
4070 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004071 mSensorNesting--;
4072 if (mSensorNesting == 0) {
4073 mHistoryCur.states &= ~HistoryItem.STATE_SENSOR_ON_FLAG;
4074 if (DEBUG_HISTORY) Slog.v(TAG, "Stop sensor to: "
4075 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004076 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004077 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004078 getUidStatsLocked(uid).noteStopSensor(sensor, elapsedRealtime);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004079 }
4080
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004081 int mGpsNesting;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004082
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004083 public void noteStartGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004084 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004085 final long elapsedRealtime = mClocks.elapsedRealtime();
4086 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004087 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004088 mHistoryCur.states |= HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004089 if (DEBUG_HISTORY) Slog.v(TAG, "Start GPS to: "
4090 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004091 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004092 }
4093 mGpsNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004094 getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004096
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004097 public void noteStopGpsLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004098 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004099 final long elapsedRealtime = mClocks.elapsedRealtime();
4100 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004101 mGpsNesting--;
4102 if (mGpsNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004103 mHistoryCur.states &= ~HistoryItem.STATE_GPS_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004104 if (DEBUG_HISTORY) Slog.v(TAG, "Stop GPS to: "
4105 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004106 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004107 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004108 getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004110
Jeff Browne95c3cd2014-05-02 16:59:26 -07004111 public void noteScreenStateLocked(int state) {
Amith Yamasani674c9bb2017-02-01 09:45:17 -08004112 state = mPretendScreenOff ? Display.STATE_OFF : state;
Santos Cordone94f0502017-02-24 12:31:20 -08004113
4114 // Battery stats relies on there being 4 states. To accommodate this, new states beyond the
4115 // original 4 are mapped to one of the originals.
4116 if (state > MAX_TRACKED_SCREEN_STATE) {
4117 switch (state) {
4118 case Display.STATE_VR:
4119 state = Display.STATE_ON;
4120 break;
4121 default:
4122 Slog.wtf(TAG, "Unknown screen state (not mapped): " + state);
4123 break;
4124 }
4125 }
4126
Jeff Browne95c3cd2014-05-02 16:59:26 -07004127 if (mScreenState != state) {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08004128 recordDailyStatsIfNeededLocked(true);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004129 final int oldState = mScreenState;
4130 mScreenState = state;
4131 if (DEBUG) Slog.v(TAG, "Screen state: oldState=" + Display.stateToString(oldState)
4132 + ", newState=" + Display.stateToString(state));
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004133
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004134 if (state != Display.STATE_UNKNOWN) {
4135 int stepState = state-1;
Santos Cordone94f0502017-02-24 12:31:20 -08004136 if ((stepState & STEP_LEVEL_MODE_SCREEN_STATE) == stepState) {
4137 mModStepMode |= (mCurStepMode & STEP_LEVEL_MODE_SCREEN_STATE) ^ stepState;
4138 mCurStepMode = (mCurStepMode & ~STEP_LEVEL_MODE_SCREEN_STATE) | stepState;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004139 } else {
4140 Slog.wtf(TAG, "Unexpected screen state: " + state);
4141 }
4142 }
4143
Jeff Browne95c3cd2014-05-02 16:59:26 -07004144 if (state == Display.STATE_ON) {
4145 // Screen turning on.
Joe Onoratoabded112016-02-08 16:49:39 -08004146 final long elapsedRealtime = mClocks.elapsedRealtime();
4147 final long uptime = mClocks.uptimeMillis();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004148 mHistoryCur.states |= HistoryItem.STATE_SCREEN_ON_FLAG;
4149 if (DEBUG_HISTORY) Slog.v(TAG, "Screen on to: "
4150 + Integer.toHexString(mHistoryCur.states));
4151 addHistoryRecordLocked(elapsedRealtime, uptime);
4152 mScreenOnTimer.startRunningLocked(elapsedRealtime);
4153 if (mScreenBrightnessBin >= 0) {
4154 mScreenBrightnessTimer[mScreenBrightnessBin].startRunningLocked(elapsedRealtime);
4155 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004156
Jeff Browne95c3cd2014-05-02 16:59:26 -07004157 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), false,
Joe Onoratoabded112016-02-08 16:49:39 -08004158 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08004159
Jeff Browne95c3cd2014-05-02 16:59:26 -07004160 // Fake a wake lock, so we consider the device waked as long
4161 // as the screen is on.
4162 noteStartWakeLocked(-1, -1, "screen", null, WAKE_TYPE_PARTIAL, false,
4163 elapsedRealtime, uptime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004164
Jeff Browne95c3cd2014-05-02 16:59:26 -07004165 // Update discharge amounts.
4166 if (mOnBatteryInternal) {
4167 updateDischargeScreenLevelsLocked(false, true);
4168 }
4169 } else if (oldState == Display.STATE_ON) {
4170 // Screen turning off or dozing.
Joe Onoratoabded112016-02-08 16:49:39 -08004171 final long elapsedRealtime = mClocks.elapsedRealtime();
4172 final long uptime = mClocks.uptimeMillis();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004173 mHistoryCur.states &= ~HistoryItem.STATE_SCREEN_ON_FLAG;
4174 if (DEBUG_HISTORY) Slog.v(TAG, "Screen off to: "
4175 + Integer.toHexString(mHistoryCur.states));
4176 addHistoryRecordLocked(elapsedRealtime, uptime);
4177 mScreenOnTimer.stopRunningLocked(elapsedRealtime);
4178 if (mScreenBrightnessBin >= 0) {
4179 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
4180 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004181
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004182 noteStopWakeLocked(-1, -1, "screen", "screen", WAKE_TYPE_PARTIAL,
Jeff Browne95c3cd2014-05-02 16:59:26 -07004183 elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004184
Jeff Browne95c3cd2014-05-02 16:59:26 -07004185 updateTimeBasesLocked(mOnBatteryTimeBase.isRunning(), true,
Joe Onoratoabded112016-02-08 16:49:39 -08004186 mClocks.uptimeMillis() * 1000, elapsedRealtime * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004187
Jeff Browne95c3cd2014-05-02 16:59:26 -07004188 // Update discharge amounts.
4189 if (mOnBatteryInternal) {
4190 updateDischargeScreenLevelsLocked(true, false);
4191 }
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08004192 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07004193 }
4194 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004195
Dianne Hackborn617f8772009-03-31 15:04:46 -07004196 public void noteScreenBrightnessLocked(int brightness) {
4197 // Bin the brightness.
4198 int bin = brightness / (256/NUM_SCREEN_BRIGHTNESS_BINS);
4199 if (bin < 0) bin = 0;
4200 else if (bin >= NUM_SCREEN_BRIGHTNESS_BINS) bin = NUM_SCREEN_BRIGHTNESS_BINS-1;
4201 if (mScreenBrightnessBin != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004202 final long elapsedRealtime = mClocks.elapsedRealtime();
4203 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004204 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_BRIGHTNESS_MASK)
4205 | (bin << HistoryItem.STATE_BRIGHTNESS_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004206 if (DEBUG_HISTORY) Slog.v(TAG, "Screen brightness " + bin + " to: "
4207 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004208 addHistoryRecordLocked(elapsedRealtime, uptime);
Jeff Browne95c3cd2014-05-02 16:59:26 -07004209 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07004210 if (mScreenBrightnessBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004211 mScreenBrightnessTimer[mScreenBrightnessBin].stopRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004212 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004213 mScreenBrightnessTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn617f8772009-03-31 15:04:46 -07004214 }
4215 mScreenBrightnessBin = bin;
4216 }
4217 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004218
Dianne Hackborn617f8772009-03-31 15:04:46 -07004219 public void noteUserActivityLocked(int uid, int event) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08004220 if (mOnBatteryInternal) {
4221 uid = mapUid(uid);
4222 getUidStatsLocked(uid).noteUserActivityLocked(event);
4223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004225
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004226 public void noteWakeUpLocked(String reason, int reasonUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004227 final long elapsedRealtime = mClocks.elapsedRealtime();
4228 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004229 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_SCREEN_WAKE_UP,
4230 reason, reasonUid);
4231 }
4232
Jeff Browne95c3cd2014-05-02 16:59:26 -07004233 public void noteInteractiveLocked(boolean interactive) {
4234 if (mInteractive != interactive) {
Joe Onoratoabded112016-02-08 16:49:39 -08004235 final long elapsedRealtime = mClocks.elapsedRealtime();
Jeff Browne95c3cd2014-05-02 16:59:26 -07004236 mInteractive = interactive;
4237 if (DEBUG) Slog.v(TAG, "Interactive: " + interactive);
4238 if (interactive) {
4239 mInteractiveTimer.startRunningLocked(elapsedRealtime);
4240 } else {
4241 mInteractiveTimer.stopRunningLocked(elapsedRealtime);
4242 }
4243 }
4244 }
4245
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004246 public void noteConnectivityChangedLocked(int type, String extra) {
Joe Onoratoabded112016-02-08 16:49:39 -08004247 final long elapsedRealtime = mClocks.elapsedRealtime();
4248 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08004249 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_CONNECTIVITY_CHANGED,
4250 extra, type);
4251 mNumConnectivityChange++;
4252 }
4253
Adam Lesinski5f056f62016-07-14 16:56:08 -07004254 private void noteMobileRadioApWakeupLocked(final long elapsedRealtimeMillis,
4255 final long uptimeMillis, int uid) {
4256 uid = mapUid(uid);
4257 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4258 uid);
4259 getUidStatsLocked(uid).noteMobileRadioApWakeupLocked();
4260 }
4261
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004262 /**
4263 * Updates the radio power state and returns true if an external stats collection should occur.
4264 */
4265 public boolean noteMobileRadioPowerStateLocked(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004266 final long elapsedRealtime = mClocks.elapsedRealtime();
4267 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004268 if (mMobileRadioPowerState != powerState) {
4269 long realElapsedRealtimeMs;
4270 final boolean active =
4271 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4272 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4273 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004274 if (uid > 0) {
4275 noteMobileRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4276 }
4277
Adam Lesinski9acfd812016-04-19 18:29:50 -07004278 mMobileRadioActiveStartTime = realElapsedRealtimeMs = timestampNs / (1000 * 1000);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004279 mHistoryCur.states |= HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4280 } else {
4281 realElapsedRealtimeMs = timestampNs / (1000*1000);
Dianne Hackbornf7097a52014-05-13 09:56:14 -07004282 long lastUpdateTimeMs = mMobileRadioActiveStartTime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004283 if (realElapsedRealtimeMs < lastUpdateTimeMs) {
4284 Slog.wtf(TAG, "Data connection inactive timestamp " + realElapsedRealtimeMs
4285 + " is before start time " + lastUpdateTimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004286 realElapsedRealtimeMs = elapsedRealtime;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004287 } else if (realElapsedRealtimeMs < elapsedRealtime) {
4288 mMobileRadioActiveAdjustedTime.addCountLocked(elapsedRealtime
4289 - realElapsedRealtimeMs);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004290 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004291 mHistoryCur.states &= ~HistoryItem.STATE_MOBILE_RADIO_ACTIVE_FLAG;
4292 }
4293 if (DEBUG_HISTORY) Slog.v(TAG, "Mobile network active " + active + " to: "
4294 + Integer.toHexString(mHistoryCur.states));
4295 addHistoryRecordLocked(elapsedRealtime, uptime);
4296 mMobileRadioPowerState = powerState;
4297 if (active) {
4298 mMobileRadioActiveTimer.startRunningLocked(elapsedRealtime);
4299 mMobileRadioActivePerAppTimer.startRunningLocked(elapsedRealtime);
4300 } else {
4301 mMobileRadioActiveTimer.stopRunningLocked(realElapsedRealtimeMs);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07004302 mMobileRadioActivePerAppTimer.stopRunningLocked(realElapsedRealtimeMs);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004303 // Tell the caller to collect radio network/power stats.
4304 return true;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004305 }
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004306 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004307 return false;
Dianne Hackborne13c4c02014-02-11 17:18:35 -08004308 }
4309
Adam Lesinski14ae39a2017-05-26 11:50:40 -07004310 public void notePowerSaveModeLocked(boolean enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004311 if (mPowerSaveModeEnabled != enabled) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07004312 int stepState = enabled ? STEP_LEVEL_MODE_POWER_SAVE : 0;
4313 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_POWER_SAVE) ^ stepState;
4314 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_POWER_SAVE) | stepState;
Joe Onoratoabded112016-02-08 16:49:39 -08004315 final long elapsedRealtime = mClocks.elapsedRealtime();
4316 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004317 mPowerSaveModeEnabled = enabled;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004318 if (enabled) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004319 mHistoryCur.states2 |= HistoryItem.STATE2_POWER_SAVE_FLAG;
4320 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode enabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004321 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004322 mPowerSaveModeEnabledTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004323 } else {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004324 mHistoryCur.states2 &= ~HistoryItem.STATE2_POWER_SAVE_FLAG;
4325 if (DEBUG_HISTORY) Slog.v(TAG, "Power save mode disabled to: "
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004326 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004327 mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004328 }
4329 addHistoryRecordLocked(elapsedRealtime, uptime);
4330 }
4331 }
4332
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004333 public void noteDeviceIdleModeLocked(int mode, String activeReason, int activeUid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004334 final long elapsedRealtime = mClocks.elapsedRealtime();
4335 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004336 boolean nowIdling = mode == DEVICE_IDLE_MODE_DEEP;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004337 if (mDeviceIdling && !nowIdling && activeReason == null) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004338 // We don't go out of general idling mode until explicitly taken out of
4339 // device idle through going active or significant motion.
4340 nowIdling = true;
4341 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004342 boolean nowLightIdling = mode == DEVICE_IDLE_MODE_LIGHT;
4343 if (mDeviceLightIdling && !nowLightIdling && !nowIdling && activeReason == null) {
4344 // We don't go out of general light idling mode until explicitly taken out of
4345 // device idle through going active or significant motion.
4346 nowLightIdling = true;
4347 }
4348 if (activeReason != null && (mDeviceIdling || mDeviceLightIdling)) {
4349 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_ACTIVE,
4350 activeReason, activeUid);
4351 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004352 if (mDeviceIdling != nowIdling) {
4353 mDeviceIdling = nowIdling;
4354 int stepState = nowIdling ? STEP_LEVEL_MODE_DEVICE_IDLE : 0;
4355 mModStepMode |= (mCurStepMode&STEP_LEVEL_MODE_DEVICE_IDLE) ^ stepState;
4356 mCurStepMode = (mCurStepMode&~STEP_LEVEL_MODE_DEVICE_IDLE) | stepState;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004357 if (nowIdling) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004358 mDeviceIdlingTimer.startRunningLocked(elapsedRealtime);
4359 } else {
4360 mDeviceIdlingTimer.stopRunningLocked(elapsedRealtime);
4361 }
4362 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004363 if (mDeviceLightIdling != nowLightIdling) {
4364 mDeviceLightIdling = nowLightIdling;
4365 if (nowLightIdling) {
4366 mDeviceLightIdlingTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004367 } else {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004368 mDeviceLightIdlingTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004369 }
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004370 }
4371 if (mDeviceIdleMode != mode) {
4372 mHistoryCur.states2 = (mHistoryCur.states2 & ~HistoryItem.STATE2_DEVICE_IDLE_MASK)
4373 | (mode << HistoryItem.STATE2_DEVICE_IDLE_SHIFT);
4374 if (DEBUG_HISTORY) Slog.v(TAG, "Device idle mode changed to: "
4375 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004376 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004377 long lastDuration = elapsedRealtime - mLastIdleTimeStart;
4378 mLastIdleTimeStart = elapsedRealtime;
4379 if (mDeviceIdleMode == DEVICE_IDLE_MODE_LIGHT) {
4380 if (lastDuration > mLongestLightIdleTime) {
4381 mLongestLightIdleTime = lastDuration;
4382 }
4383 mDeviceIdleModeLightTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004384 } else if (mDeviceIdleMode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004385 if (lastDuration > mLongestFullIdleTime) {
4386 mLongestFullIdleTime = lastDuration;
4387 }
4388 mDeviceIdleModeFullTimer.stopRunningLocked(elapsedRealtime);
4389 }
4390 if (mode == DEVICE_IDLE_MODE_LIGHT) {
4391 mDeviceIdleModeLightTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07004392 } else if (mode == DEVICE_IDLE_MODE_DEEP) {
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004393 mDeviceIdleModeFullTimer.startRunningLocked(elapsedRealtime);
4394 }
4395 mDeviceIdleMode = mode;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004396 }
4397 }
4398
4399 public void notePackageInstalledLocked(String pkgName, int versionCode) {
Joe Onoratoabded112016-02-08 16:49:39 -08004400 final long elapsedRealtime = mClocks.elapsedRealtime();
4401 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004402 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_INSTALLED,
4403 pkgName, versionCode);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004404 PackageChange pc = new PackageChange();
4405 pc.mPackageName = pkgName;
4406 pc.mUpdate = true;
4407 pc.mVersionCode = versionCode;
4408 addPackageChange(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004409 }
4410
4411 public void notePackageUninstalledLocked(String pkgName) {
Joe Onoratoabded112016-02-08 16:49:39 -08004412 final long elapsedRealtime = mClocks.elapsedRealtime();
4413 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004414 addHistoryEventLocked(elapsedRealtime, uptime, HistoryItem.EVENT_PACKAGE_UNINSTALLED,
4415 pkgName, 0);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004416 PackageChange pc = new PackageChange();
4417 pc.mPackageName = pkgName;
4418 pc.mUpdate = true;
4419 addPackageChange(pc);
4420 }
4421
4422 private void addPackageChange(PackageChange pc) {
4423 if (mDailyPackageChanges == null) {
4424 mDailyPackageChanges = new ArrayList<>();
4425 }
4426 mDailyPackageChanges.add(pc);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07004427 }
4428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429 public void notePhoneOnLocked() {
4430 if (!mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004431 final long elapsedRealtime = mClocks.elapsedRealtime();
4432 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004433 mHistoryCur.states2 |= HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004434 if (DEBUG_HISTORY) Slog.v(TAG, "Phone on to: "
4435 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004436 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004437 mPhoneOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004438 mPhoneOnTimer.startRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004439 }
4440 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004442 public void notePhoneOffLocked() {
4443 if (mPhoneOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004444 final long elapsedRealtime = mClocks.elapsedRealtime();
4445 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004446 mHistoryCur.states2 &= ~HistoryItem.STATE2_PHONE_IN_CALL_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004447 if (DEBUG_HISTORY) Slog.v(TAG, "Phone off to: "
4448 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004449 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450 mPhoneOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004451 mPhoneOnTimer.stopRunningLocked(elapsedRealtime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 }
4453 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07004454
Dianne Hackborn3251b902014-06-20 14:40:53 -07004455 void stopAllPhoneSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08004456 final long elapsedRealtime = mClocks.elapsedRealtime();
Wink Saville52840902011-02-18 12:40:47 -08004457 for (int i = 0; i < SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004458 if (i == except) {
4459 continue;
4460 }
4461 while (mPhoneSignalStrengthsTimer[i].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004462 mPhoneSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004463 }
4464 }
4465 }
4466
Dianne Hackborne4a59512010-12-07 11:08:07 -08004467 private int fixPhoneServiceState(int state, int signalBin) {
4468 if (mPhoneSimStateRaw == TelephonyManager.SIM_STATE_ABSENT) {
4469 // In this case we will always be STATE_OUT_OF_SERVICE, so need
4470 // to infer that we are scanning from other data.
4471 if (state == ServiceState.STATE_OUT_OF_SERVICE
Wink Saville52840902011-02-18 12:40:47 -08004472 && signalBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004473 state = ServiceState.STATE_IN_SERVICE;
4474 }
4475 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004476
Dianne Hackborne4a59512010-12-07 11:08:07 -08004477 return state;
4478 }
4479
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004480 private void updateAllPhoneStateLocked(int state, int simState, int strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004481 boolean scanning = false;
4482 boolean newHistory = false;
4483
4484 mPhoneServiceStateRaw = state;
4485 mPhoneSimStateRaw = simState;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004486 mPhoneSignalStrengthBinRaw = strengthBin;
4487
Joe Onoratoabded112016-02-08 16:49:39 -08004488 final long elapsedRealtime = mClocks.elapsedRealtime();
4489 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne4a59512010-12-07 11:08:07 -08004490
4491 if (simState == TelephonyManager.SIM_STATE_ABSENT) {
4492 // In this case we will always be STATE_OUT_OF_SERVICE, so need
4493 // to infer that we are scanning from other data.
4494 if (state == ServiceState.STATE_OUT_OF_SERVICE
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004495 && strengthBin > SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004496 state = ServiceState.STATE_IN_SERVICE;
4497 }
4498 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004499
4500 // If the phone is powered off, stop all timers.
4501 if (state == ServiceState.STATE_POWER_OFF) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004502 strengthBin = -1;
Amith Yamasanif37447b2009-10-08 18:28:01 -07004503
Dianne Hackborne4a59512010-12-07 11:08:07 -08004504 // If we are in service, make sure the correct signal string timer is running.
4505 } else if (state == ServiceState.STATE_IN_SERVICE) {
4506 // Bin will be changed below.
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004507
4508 // If we're out of service, we are in the lowest signal strength
4509 // bin and have the scanning bit set.
Amith Yamasanif37447b2009-10-08 18:28:01 -07004510 } else if (state == ServiceState.STATE_OUT_OF_SERVICE) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004511 scanning = true;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004512 strengthBin = SignalStrength.SIGNAL_STRENGTH_NONE_OR_UNKNOWN;
Amith Yamasanif37447b2009-10-08 18:28:01 -07004513 if (!mPhoneSignalScanningTimer.isRunningLocked()) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004514 mHistoryCur.states |= HistoryItem.STATE_PHONE_SCANNING_FLAG;
Dianne Hackborne4a59512010-12-07 11:08:07 -08004515 newHistory = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004516 if (DEBUG_HISTORY) Slog.v(TAG, "Phone started scanning to: "
4517 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004518 mPhoneSignalScanningTimer.startRunningLocked(elapsedRealtime);
Amith Yamasanif37447b2009-10-08 18:28:01 -07004519 }
4520 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004521
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004522 if (!scanning) {
4523 // If we are no longer scanning, then stop the scanning timer.
4524 if (mPhoneSignalScanningTimer.isRunningLocked()) {
4525 mHistoryCur.states &= ~HistoryItem.STATE_PHONE_SCANNING_FLAG;
4526 if (DEBUG_HISTORY) Slog.v(TAG, "Phone stopped scanning to: "
4527 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08004528 newHistory = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004529 mPhoneSignalScanningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07004530 }
4531 }
4532
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004533 if (mPhoneServiceState != state) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004534 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_STATE_MASK)
4535 | (state << HistoryItem.STATE_PHONE_STATE_SHIFT);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004536 if (DEBUG_HISTORY) Slog.v(TAG, "Phone state " + state + " to: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004537 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborne4a59512010-12-07 11:08:07 -08004538 newHistory = true;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004539 mPhoneServiceState = state;
4540 }
Dianne Hackborne4a59512010-12-07 11:08:07 -08004541
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004542 if (mPhoneSignalStrengthBin != strengthBin) {
Dianne Hackborne4a59512010-12-07 11:08:07 -08004543 if (mPhoneSignalStrengthBin >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004544 mPhoneSignalStrengthsTimer[mPhoneSignalStrengthBin].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004545 elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004546 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004547 if (strengthBin >= 0) {
4548 if (!mPhoneSignalStrengthsTimer[strengthBin].isRunningLocked()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004549 mPhoneSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004550 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07004551 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_MASK)
4552 | (strengthBin << HistoryItem.STATE_PHONE_SIGNAL_STRENGTH_SHIFT);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004553 if (DEBUG_HISTORY) Slog.v(TAG, "Signal strength " + strengthBin + " to: "
Dianne Hackborne4a59512010-12-07 11:08:07 -08004554 + Integer.toHexString(mHistoryCur.states));
4555 newHistory = true;
4556 } else {
Dianne Hackborn3251b902014-06-20 14:40:53 -07004557 stopAllPhoneSignalStrengthTimersLocked(-1);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004558 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004559 mPhoneSignalStrengthBin = strengthBin;
Dianne Hackborne4a59512010-12-07 11:08:07 -08004560 }
4561
4562 if (newHistory) {
Dianne Hackborn40c87252014-03-19 16:55:40 -07004563 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborne4a59512010-12-07 11:08:07 -08004564 }
4565 }
4566
4567 /**
4568 * Telephony stack updates the phone state.
4569 * @param state phone state from ServiceState.getState()
4570 */
4571 public void notePhoneStateLocked(int state, int simState) {
4572 updateAllPhoneStateLocked(state, simState, mPhoneSignalStrengthBinRaw);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07004573 }
4574
Wink Savillee9b06d72009-05-18 21:47:50 -07004575 public void notePhoneSignalStrengthLocked(SignalStrength signalStrength) {
Dianne Hackborn627bba72009-03-24 22:32:56 -07004576 // Bin the strength.
Wink Saville52840902011-02-18 12:40:47 -08004577 int bin = signalStrength.getLevel();
Dianne Hackborne4a59512010-12-07 11:08:07 -08004578 updateAllPhoneStateLocked(mPhoneServiceStateRaw, mPhoneSimStateRaw, bin);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004579 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004580
Dianne Hackborn627bba72009-03-24 22:32:56 -07004581 public void notePhoneDataConnectionStateLocked(int dataType, boolean hasData) {
4582 int bin = DATA_CONNECTION_NONE;
4583 if (hasData) {
4584 switch (dataType) {
4585 case TelephonyManager.NETWORK_TYPE_EDGE:
4586 bin = DATA_CONNECTION_EDGE;
4587 break;
4588 case TelephonyManager.NETWORK_TYPE_GPRS:
4589 bin = DATA_CONNECTION_GPRS;
4590 break;
4591 case TelephonyManager.NETWORK_TYPE_UMTS:
4592 bin = DATA_CONNECTION_UMTS;
4593 break;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004594 case TelephonyManager.NETWORK_TYPE_CDMA:
4595 bin = DATA_CONNECTION_CDMA;
4596 break;
4597 case TelephonyManager.NETWORK_TYPE_EVDO_0:
4598 bin = DATA_CONNECTION_EVDO_0;
4599 break;
4600 case TelephonyManager.NETWORK_TYPE_EVDO_A:
4601 bin = DATA_CONNECTION_EVDO_A;
4602 break;
4603 case TelephonyManager.NETWORK_TYPE_1xRTT:
4604 bin = DATA_CONNECTION_1xRTT;
4605 break;
4606 case TelephonyManager.NETWORK_TYPE_HSDPA:
4607 bin = DATA_CONNECTION_HSDPA;
4608 break;
4609 case TelephonyManager.NETWORK_TYPE_HSUPA:
4610 bin = DATA_CONNECTION_HSUPA;
4611 break;
4612 case TelephonyManager.NETWORK_TYPE_HSPA:
4613 bin = DATA_CONNECTION_HSPA;
4614 break;
4615 case TelephonyManager.NETWORK_TYPE_IDEN:
4616 bin = DATA_CONNECTION_IDEN;
4617 break;
4618 case TelephonyManager.NETWORK_TYPE_EVDO_B:
4619 bin = DATA_CONNECTION_EVDO_B;
4620 break;
Robert Greenwalt962a9902010-11-02 11:10:25 -07004621 case TelephonyManager.NETWORK_TYPE_LTE:
4622 bin = DATA_CONNECTION_LTE;
4623 break;
4624 case TelephonyManager.NETWORK_TYPE_EHRPD:
4625 bin = DATA_CONNECTION_EHRPD;
4626 break;
Patrick Tjinb71703c2013-11-06 09:27:03 -08004627 case TelephonyManager.NETWORK_TYPE_HSPAP:
4628 bin = DATA_CONNECTION_HSPAP;
4629 break;
Dianne Hackborn627bba72009-03-24 22:32:56 -07004630 default:
4631 bin = DATA_CONNECTION_OTHER;
4632 break;
4633 }
4634 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -07004635 if (DEBUG) Log.i(TAG, "Phone Data Connection -> " + dataType + " = " + hasData);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004636 if (mPhoneDataConnectionType != bin) {
Joe Onoratoabded112016-02-08 16:49:39 -08004637 final long elapsedRealtime = mClocks.elapsedRealtime();
4638 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004639 mHistoryCur.states = (mHistoryCur.states&~HistoryItem.STATE_DATA_CONNECTION_MASK)
4640 | (bin << HistoryItem.STATE_DATA_CONNECTION_SHIFT);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004641 if (DEBUG_HISTORY) Slog.v(TAG, "Data connection " + bin + " to: "
4642 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004643 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004644 if (mPhoneDataConnectionType >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004645 mPhoneDataConnectionsTimer[mPhoneDataConnectionType].stopRunningLocked(
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004646 elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004647 }
4648 mPhoneDataConnectionType = bin;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004649 mPhoneDataConnectionsTimer[bin].startRunningLocked(elapsedRealtime);
Dianne Hackborn627bba72009-03-24 22:32:56 -07004650 }
4651 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004652
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004653 public void noteWifiOnLocked() {
The Android Open Source Project10592532009-03-18 17:39:46 -07004654 if (!mWifiOn) {
Joe Onoratoabded112016-02-08 16:49:39 -08004655 final long elapsedRealtime = mClocks.elapsedRealtime();
4656 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07004657 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004658 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI on to: "
4659 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004660 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07004661 mWifiOn = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004662 mWifiOnTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004663 scheduleSyncExternalStatsLocked("wifi-off", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07004664 }
4665 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004666
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004667 public void noteWifiOffLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08004668 final long elapsedRealtime = mClocks.elapsedRealtime();
4669 final long uptime = mClocks.uptimeMillis();
The Android Open Source Project10592532009-03-18 17:39:46 -07004670 if (mWifiOn) {
Dianne Hackborn3251b902014-06-20 14:40:53 -07004671 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004672 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI off to: "
4673 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004674 addHistoryRecordLocked(elapsedRealtime, uptime);
The Android Open Source Project10592532009-03-18 17:39:46 -07004675 mWifiOn = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004676 mWifiOnTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004677 scheduleSyncExternalStatsLocked("wifi-on", ExternalStatsSync.UPDATE_WIFI);
The Android Open Source Project10592532009-03-18 17:39:46 -07004678 }
4679 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004680
4681 public void noteAudioOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004682 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004683 final long elapsedRealtime = mClocks.elapsedRealtime();
4684 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004685 if (mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004686 mHistoryCur.states |= HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004687 if (DEBUG_HISTORY) Slog.v(TAG, "Audio on to: "
4688 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004689 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004690 mAudioOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004691 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004692 mAudioOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004693 getUidStatsLocked(uid).noteAudioTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004694 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004695
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004696 public void noteAudioOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004697 if (mAudioOnNesting == 0) {
4698 return;
4699 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004700 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004701 final long elapsedRealtime = mClocks.elapsedRealtime();
4702 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004703 if (--mAudioOnNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07004704 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004705 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
4706 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004707 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004708 mAudioOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004709 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004710 getUidStatsLocked(uid).noteAudioTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004711 }
4712
4713 public void noteVideoOnLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004714 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004715 final long elapsedRealtime = mClocks.elapsedRealtime();
4716 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004717 if (mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004718 mHistoryCur.states2 |= HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004719 if (DEBUG_HISTORY) Slog.v(TAG, "Video on to: "
4720 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004721 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004722 mVideoOnTimer.startRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004723 }
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004724 mVideoOnNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004725 getUidStatsLocked(uid).noteVideoTurnedOnLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004726 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07004727
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004728 public void noteVideoOffLocked(int uid) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004729 if (mVideoOnNesting == 0) {
4730 return;
4731 }
Dianne Hackborn099bc622014-01-22 13:39:16 -08004732 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004733 final long elapsedRealtime = mClocks.elapsedRealtime();
4734 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004735 if (--mVideoOnNesting == 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07004736 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004737 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
4738 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07004739 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08004740 mVideoOnTimer.stopRunningLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004741 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08004742 getUidStatsLocked(uid).noteVideoTurnedOffLocked(elapsedRealtime);
Amith Yamasani244fa5c2009-05-22 14:36:07 -07004743 }
4744
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004745 public void noteResetAudioLocked() {
4746 if (mAudioOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004747 final long elapsedRealtime = mClocks.elapsedRealtime();
4748 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004749 mAudioOnNesting = 0;
4750 mHistoryCur.states &= ~HistoryItem.STATE_AUDIO_ON_FLAG;
4751 if (DEBUG_HISTORY) Slog.v(TAG, "Audio off to: "
4752 + Integer.toHexString(mHistoryCur.states));
4753 addHistoryRecordLocked(elapsedRealtime, uptime);
4754 mAudioOnTimer.stopAllRunningLocked(elapsedRealtime);
4755 for (int i=0; i<mUidStats.size(); i++) {
4756 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4757 uid.noteResetAudioLocked(elapsedRealtime);
4758 }
4759 }
4760 }
4761
4762 public void noteResetVideoLocked() {
4763 if (mVideoOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004764 final long elapsedRealtime = mClocks.elapsedRealtime();
4765 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn10eaa852014-07-22 22:54:55 -07004766 mAudioOnNesting = 0;
4767 mHistoryCur.states2 &= ~HistoryItem.STATE2_VIDEO_ON_FLAG;
4768 if (DEBUG_HISTORY) Slog.v(TAG, "Video off to: "
4769 + Integer.toHexString(mHistoryCur.states));
4770 addHistoryRecordLocked(elapsedRealtime, uptime);
4771 mVideoOnTimer.stopAllRunningLocked(elapsedRealtime);
4772 for (int i=0; i<mUidStats.size(); i++) {
4773 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4774 uid.noteResetVideoLocked(elapsedRealtime);
4775 }
4776 }
4777 }
4778
Jeff Sharkey3e013e82013-04-25 14:48:19 -07004779 public void noteActivityResumedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004780 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004781 getUidStatsLocked(uid).noteActivityResumedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07004782 }
4783
4784 public void noteActivityPausedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004785 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004786 getUidStatsLocked(uid).noteActivityPausedLocked(mClocks.elapsedRealtime());
Jeff Sharkey3e013e82013-04-25 14:48:19 -07004787 }
4788
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004789 public void noteVibratorOnLocked(int uid, long durationMillis) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004790 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004791 getUidStatsLocked(uid).noteVibratorOnLocked(durationMillis);
4792 }
4793
4794 public void noteVibratorOffLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08004795 uid = mapUid(uid);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08004796 getUidStatsLocked(uid).noteVibratorOffLocked();
4797 }
4798
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004799 public void noteFlashlightOnLocked(int uid) {
4800 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004801 final long elapsedRealtime = mClocks.elapsedRealtime();
4802 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004803 if (mFlashlightOnNesting++ == 0) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004804 mHistoryCur.states2 |= HistoryItem.STATE2_FLASHLIGHT_FLAG;
4805 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight on to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004806 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004807 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004808 mFlashlightOnTimer.startRunningLocked(elapsedRealtime);
4809 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004810 getUidStatsLocked(uid).noteFlashlightTurnedOnLocked(elapsedRealtime);
4811 }
4812
4813 public void noteFlashlightOffLocked(int uid) {
4814 if (mFlashlightOnNesting == 0) {
4815 return;
4816 }
4817 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004818 final long elapsedRealtime = mClocks.elapsedRealtime();
4819 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004820 if (--mFlashlightOnNesting == 0) {
4821 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
4822 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
4823 + Integer.toHexString(mHistoryCur.states2));
4824 addHistoryRecordLocked(elapsedRealtime, uptime);
4825 mFlashlightOnTimer.stopRunningLocked(elapsedRealtime);
4826 }
4827 getUidStatsLocked(uid).noteFlashlightTurnedOffLocked(elapsedRealtime);
4828 }
4829
4830 public void noteCameraOnLocked(int uid) {
4831 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004832 final long elapsedRealtime = mClocks.elapsedRealtime();
4833 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004834 if (mCameraOnNesting++ == 0) {
4835 mHistoryCur.states2 |= HistoryItem.STATE2_CAMERA_FLAG;
4836 if (DEBUG_HISTORY) Slog.v(TAG, "Camera on to: "
4837 + Integer.toHexString(mHistoryCur.states2));
4838 addHistoryRecordLocked(elapsedRealtime, uptime);
4839 mCameraOnTimer.startRunningLocked(elapsedRealtime);
4840 }
4841 getUidStatsLocked(uid).noteCameraTurnedOnLocked(elapsedRealtime);
4842 }
4843
4844 public void noteCameraOffLocked(int uid) {
4845 if (mCameraOnNesting == 0) {
4846 return;
4847 }
4848 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08004849 final long elapsedRealtime = mClocks.elapsedRealtime();
4850 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004851 if (--mCameraOnNesting == 0) {
4852 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
4853 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
4854 + Integer.toHexString(mHistoryCur.states2));
4855 addHistoryRecordLocked(elapsedRealtime, uptime);
4856 mCameraOnTimer.stopRunningLocked(elapsedRealtime);
4857 }
4858 getUidStatsLocked(uid).noteCameraTurnedOffLocked(elapsedRealtime);
4859 }
4860
4861 public void noteResetCameraLocked() {
4862 if (mCameraOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004863 final long elapsedRealtime = mClocks.elapsedRealtime();
4864 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004865 mCameraOnNesting = 0;
4866 mHistoryCur.states2 &= ~HistoryItem.STATE2_CAMERA_FLAG;
4867 if (DEBUG_HISTORY) Slog.v(TAG, "Camera off to: "
4868 + Integer.toHexString(mHistoryCur.states2));
4869 addHistoryRecordLocked(elapsedRealtime, uptime);
4870 mCameraOnTimer.stopAllRunningLocked(elapsedRealtime);
4871 for (int i=0; i<mUidStats.size(); i++) {
4872 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4873 uid.noteResetCameraLocked(elapsedRealtime);
4874 }
4875 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004876 }
4877
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004878 public void noteResetFlashlightLocked() {
4879 if (mFlashlightOnNesting > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08004880 final long elapsedRealtime = mClocks.elapsedRealtime();
4881 final long uptime = mClocks.uptimeMillis();
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004882 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004883 mHistoryCur.states2 &= ~HistoryItem.STATE2_FLASHLIGHT_FLAG;
4884 if (DEBUG_HISTORY) Slog.v(TAG, "Flashlight off to: "
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004885 + Integer.toHexString(mHistoryCur.states2));
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004886 addHistoryRecordLocked(elapsedRealtime, uptime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07004887 mFlashlightOnTimer.stopAllRunningLocked(elapsedRealtime);
4888 for (int i=0; i<mUidStats.size(); i++) {
4889 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4890 uid.noteResetFlashlightLocked(elapsedRealtime);
4891 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -07004892 }
4893 }
4894
Bookatzb1f04f32017-05-19 13:57:32 -07004895 private void noteBluetoothScanStartedLocked(int uid, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004896 uid = mapUid(uid);
Bookatz867c0d72017-03-07 18:23:42 -08004897 final long elapsedRealtime = mClocks.elapsedRealtime();
4898 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004899 if (mBluetoothScanNesting == 0) {
4900 mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
4901 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan started for: "
4902 + Integer.toHexString(mHistoryCur.states2));
4903 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07004904 mBluetoothScanTimer.startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004905 }
4906 mBluetoothScanNesting++;
Bookatzb1f04f32017-05-19 13:57:32 -07004907 getUidStatsLocked(uid).noteBluetoothScanStartedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004908 }
4909
Bookatzb1f04f32017-05-19 13:57:32 -07004910 public void noteBluetoothScanStartedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004911 final int N = ws.size();
4912 for (int i = 0; i < N; i++) {
Bookatzb1f04f32017-05-19 13:57:32 -07004913 noteBluetoothScanStartedLocked(ws.get(i), isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004914 }
4915 }
4916
Bookatz94c5a312017-07-11 16:49:17 -07004917 private void noteBluetoothScanStoppedLocked(int uid, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004918 uid = mapUid(uid);
Bookatz867c0d72017-03-07 18:23:42 -08004919 final long elapsedRealtime = mClocks.elapsedRealtime();
4920 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004921 mBluetoothScanNesting--;
4922 if (mBluetoothScanNesting == 0) {
4923 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
4924 if (DEBUG_HISTORY) Slog.v(TAG, "BLE scan stopped for: "
4925 + Integer.toHexString(mHistoryCur.states2));
4926 addHistoryRecordLocked(elapsedRealtime, uptime);
Adam Lesinskid9b99be2016-03-30 16:58:51 -07004927 mBluetoothScanTimer.stopRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004928 }
Bookatz94c5a312017-07-11 16:49:17 -07004929 getUidStatsLocked(uid).noteBluetoothScanStoppedLocked(elapsedRealtime, isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004930 }
4931
Bookatz94c5a312017-07-11 16:49:17 -07004932 public void noteBluetoothScanStoppedFromSourceLocked(WorkSource ws, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004933 final int N = ws.size();
4934 for (int i = 0; i < N; i++) {
Bookatz94c5a312017-07-11 16:49:17 -07004935 noteBluetoothScanStoppedLocked(ws.get(i), isUnoptimized);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004936 }
4937 }
4938
4939 public void noteResetBluetoothScanLocked() {
4940 if (mBluetoothScanNesting > 0) {
Bookatz867c0d72017-03-07 18:23:42 -08004941 final long elapsedRealtime = mClocks.elapsedRealtime();
4942 final long uptime = mClocks.uptimeMillis();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08004943 mBluetoothScanNesting = 0;
4944 mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_SCAN_FLAG;
4945 if (DEBUG_HISTORY) Slog.v(TAG, "BLE can stopped for: "
4946 + Integer.toHexString(mHistoryCur.states2));
4947 addHistoryRecordLocked(elapsedRealtime, uptime);
4948 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtime);
4949 for (int i=0; i<mUidStats.size(); i++) {
4950 BatteryStatsImpl.Uid uid = mUidStats.valueAt(i);
4951 uid.noteResetBluetoothScanLocked(elapsedRealtime);
4952 }
4953 }
4954 }
4955
Bookatz4ebc0642017-05-11 12:21:19 -07004956 public void noteBluetoothScanResultsFromSourceLocked(WorkSource ws, int numNewResults) {
Bookatz956f36bf2017-04-28 09:48:17 -07004957 final int N = ws.size();
4958 for (int i = 0; i < N; i++) {
4959 int uid = mapUid(ws.get(i));
Bookatz4ebc0642017-05-11 12:21:19 -07004960 getUidStatsLocked(uid).noteBluetoothScanResultsLocked(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07004961 }
4962 }
4963
Adam Lesinski5f056f62016-07-14 16:56:08 -07004964 private void noteWifiRadioApWakeupLocked(final long elapsedRealtimeMillis,
4965 final long uptimeMillis, int uid) {
4966 uid = mapUid(uid);
4967 addHistoryEventLocked(elapsedRealtimeMillis, uptimeMillis, HistoryItem.EVENT_WAKEUP_AP, "",
4968 uid);
4969 getUidStatsLocked(uid).noteWifiRadioApWakeupLocked();
4970 }
4971
4972 public void noteWifiRadioPowerState(int powerState, long timestampNs, int uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08004973 final long elapsedRealtime = mClocks.elapsedRealtime();
4974 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004975 if (mWifiRadioPowerState != powerState) {
4976 final boolean active =
4977 powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
4978 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
4979 if (active) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07004980 if (uid > 0) {
4981 noteWifiRadioApWakeupLocked(elapsedRealtime, uptime, uid);
4982 }
Dianne Hackborn0c820db2015-04-14 17:47:34 -07004983 mHistoryCur.states |= HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
4984 } else {
4985 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_RADIO_ACTIVE_FLAG;
4986 }
4987 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi network active " + active + " to: "
4988 + Integer.toHexString(mHistoryCur.states));
4989 addHistoryRecordLocked(elapsedRealtime, uptime);
4990 mWifiRadioPowerState = powerState;
4991 }
4992 }
4993
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07004994 public void noteWifiRunningLocked(WorkSource ws) {
4995 if (!mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08004996 final long elapsedRealtime = mClocks.elapsedRealtime();
4997 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07004998 mHistoryCur.states2 |= HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07004999 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI running to: "
5000 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005001 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005002 mGlobalWifiRunning = true;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005003 mGlobalWifiRunningTimer.startRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005004 int N = ws.size();
5005 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005006 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005007 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005008 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005009 scheduleSyncExternalStatsLocked("wifi-running", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005010 } else {
5011 Log.w(TAG, "noteWifiRunningLocked -- called while WIFI running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005012 }
5013 }
5014
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005015 public void noteWifiRunningChangedLocked(WorkSource oldWs, WorkSource newWs) {
5016 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005017 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005018 int N = oldWs.size();
5019 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005020 int uid = mapUid(oldWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005021 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005022 }
5023 N = newWs.size();
5024 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005025 int uid = mapUid(newWs.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005026 getUidStatsLocked(uid).noteWifiRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005027 }
5028 } else {
5029 Log.w(TAG, "noteWifiRunningChangedLocked -- called while WIFI not running");
5030 }
5031 }
5032
5033 public void noteWifiStoppedLocked(WorkSource ws) {
5034 if (mGlobalWifiRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08005035 final long elapsedRealtime = mClocks.elapsedRealtime();
5036 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005037 mHistoryCur.states2 &= ~HistoryItem.STATE2_WIFI_RUNNING_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005038 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI stopped to: "
5039 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005040 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005041 mGlobalWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005042 mGlobalWifiRunningTimer.stopRunningLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005043 int N = ws.size();
5044 for (int i=0; i<N; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005045 int uid = mapUid(ws.get(i));
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005046 getUidStatsLocked(uid).noteWifiStoppedLocked(elapsedRealtime);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005047 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005048 scheduleSyncExternalStatsLocked("wifi-stopped", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005049 } else {
5050 Log.w(TAG, "noteWifiStoppedLocked -- called while WIFI not running");
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005051 }
5052 }
5053
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005054 public void noteWifiStateLocked(int wifiState, String accessPoint) {
5055 if (DEBUG) Log.i(TAG, "WiFi state -> " + wifiState);
5056 if (mWifiState != wifiState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005057 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005058 if (mWifiState >= 0) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005059 mWifiStateTimer[mWifiState].stopRunningLocked(elapsedRealtime);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005060 }
5061 mWifiState = wifiState;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005062 mWifiStateTimer[wifiState].startRunningLocked(elapsedRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005063 scheduleSyncExternalStatsLocked("wifi-state", ExternalStatsSync.UPDATE_WIFI);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005064 }
5065 }
5066
Dianne Hackborn3251b902014-06-20 14:40:53 -07005067 public void noteWifiSupplicantStateChangedLocked(int supplState, boolean failedAuth) {
5068 if (DEBUG) Log.i(TAG, "WiFi suppl state -> " + supplState);
5069 if (mWifiSupplState != supplState) {
Joe Onoratoabded112016-02-08 16:49:39 -08005070 final long elapsedRealtime = mClocks.elapsedRealtime();
5071 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005072 if (mWifiSupplState >= 0) {
5073 mWifiSupplStateTimer[mWifiSupplState].stopRunningLocked(elapsedRealtime);
5074 }
5075 mWifiSupplState = supplState;
5076 mWifiSupplStateTimer[supplState].startRunningLocked(elapsedRealtime);
5077 mHistoryCur.states2 =
5078 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK)
5079 | (supplState << HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT);
5080 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi suppl state " + supplState + " to: "
5081 + Integer.toHexString(mHistoryCur.states2));
5082 addHistoryRecordLocked(elapsedRealtime, uptime);
5083 }
5084 }
5085
5086 void stopAllWifiSignalStrengthTimersLocked(int except) {
Joe Onoratoabded112016-02-08 16:49:39 -08005087 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005088 for (int i = 0; i < NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
5089 if (i == except) {
5090 continue;
5091 }
5092 while (mWifiSignalStrengthsTimer[i].isRunningLocked()) {
5093 mWifiSignalStrengthsTimer[i].stopRunningLocked(elapsedRealtime);
5094 }
5095 }
5096 }
5097
5098 public void noteWifiRssiChangedLocked(int newRssi) {
5099 int strengthBin = WifiManager.calculateSignalLevel(newRssi, NUM_WIFI_SIGNAL_STRENGTH_BINS);
5100 if (DEBUG) Log.i(TAG, "WiFi rssi -> " + newRssi + " bin=" + strengthBin);
5101 if (mWifiSignalStrengthBin != strengthBin) {
Joe Onoratoabded112016-02-08 16:49:39 -08005102 final long elapsedRealtime = mClocks.elapsedRealtime();
5103 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn3251b902014-06-20 14:40:53 -07005104 if (mWifiSignalStrengthBin >= 0) {
5105 mWifiSignalStrengthsTimer[mWifiSignalStrengthBin].stopRunningLocked(
5106 elapsedRealtime);
5107 }
5108 if (strengthBin >= 0) {
5109 if (!mWifiSignalStrengthsTimer[strengthBin].isRunningLocked()) {
5110 mWifiSignalStrengthsTimer[strengthBin].startRunningLocked(elapsedRealtime);
5111 }
5112 mHistoryCur.states2 =
5113 (mHistoryCur.states2&~HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_MASK)
5114 | (strengthBin << HistoryItem.STATE2_WIFI_SIGNAL_STRENGTH_SHIFT);
5115 if (DEBUG_HISTORY) Slog.v(TAG, "Wifi signal strength " + strengthBin + " to: "
5116 + Integer.toHexString(mHistoryCur.states2));
5117 addHistoryRecordLocked(elapsedRealtime, uptime);
5118 } else {
5119 stopAllWifiSignalStrengthTimersLocked(-1);
5120 }
5121 mWifiSignalStrengthBin = strengthBin;
5122 }
5123 }
5124
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005125 int mWifiFullLockNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005126
The Android Open Source Project10592532009-03-18 17:39:46 -07005127 public void noteFullWifiLockAcquiredLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005128 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005129 final long elapsedRealtime = mClocks.elapsedRealtime();
5130 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005131 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005132 mHistoryCur.states |= HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005133 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock on to: "
5134 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005135 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005136 }
5137 mWifiFullLockNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005138 getUidStatsLocked(uid).noteFullWifiLockAcquiredLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005139 }
5140
5141 public void noteFullWifiLockReleasedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005142 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005143 final long elapsedRealtime = mClocks.elapsedRealtime();
5144 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005145 mWifiFullLockNesting--;
5146 if (mWifiFullLockNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005147 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_FULL_LOCK_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005148 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI full lock off to: "
5149 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005150 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005151 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005152 getUidStatsLocked(uid).noteFullWifiLockReleasedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005153 }
5154
Nick Pelly6ccaa542012-06-15 15:22:47 -07005155 int mWifiScanNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005156
Nick Pelly6ccaa542012-06-15 15:22:47 -07005157 public void noteWifiScanStartedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005158 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005159 final long elapsedRealtime = mClocks.elapsedRealtime();
5160 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005161 if (mWifiScanNesting == 0) {
5162 mHistoryCur.states |= HistoryItem.STATE_WIFI_SCAN_FLAG;
5163 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan started for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005164 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005165 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005166 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07005167 mWifiScanNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005168 getUidStatsLocked(uid).noteWifiScanStartedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005169 }
5170
Nick Pelly6ccaa542012-06-15 15:22:47 -07005171 public void noteWifiScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005172 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005173 final long elapsedRealtime = mClocks.elapsedRealtime();
5174 final long uptime = mClocks.uptimeMillis();
Nick Pelly6ccaa542012-06-15 15:22:47 -07005175 mWifiScanNesting--;
5176 if (mWifiScanNesting == 0) {
5177 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_SCAN_FLAG;
5178 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI scan stopped for: "
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005179 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005180 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005181 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005182 getUidStatsLocked(uid).noteWifiScanStoppedLocked(elapsedRealtime);
The Android Open Source Project10592532009-03-18 17:39:46 -07005183 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005184
Robert Greenwalta029ea12013-09-25 16:38:12 -07005185 public void noteWifiBatchedScanStartedLocked(int uid, int csph) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005186 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005187 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005188 getUidStatsLocked(uid).noteWifiBatchedScanStartedLocked(csph, elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005189 }
5190
5191 public void noteWifiBatchedScanStoppedLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005192 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005193 final long elapsedRealtime = mClocks.elapsedRealtime();
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005194 getUidStatsLocked(uid).noteWifiBatchedScanStoppedLocked(elapsedRealtime);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005195 }
5196
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005197 int mWifiMulticastNesting = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005198
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005199 public void noteWifiMulticastEnabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005200 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005201 final long elapsedRealtime = mClocks.elapsedRealtime();
5202 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005203 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005204 mHistoryCur.states |= HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005205 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast on to: "
5206 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005207 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005208 }
5209 mWifiMulticastNesting++;
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005210 getUidStatsLocked(uid).noteWifiMulticastEnabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005211 }
5212
5213 public void noteWifiMulticastDisabledLocked(int uid) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08005214 uid = mapUid(uid);
Joe Onoratoabded112016-02-08 16:49:39 -08005215 final long elapsedRealtime = mClocks.elapsedRealtime();
5216 final long uptime = mClocks.uptimeMillis();
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005217 mWifiMulticastNesting--;
5218 if (mWifiMulticastNesting == 0) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005219 mHistoryCur.states &= ~HistoryItem.STATE_WIFI_MULTICAST_ON_FLAG;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005220 if (DEBUG_HISTORY) Slog.v(TAG, "WIFI multicast off to: "
5221 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -07005222 addHistoryRecordLocked(elapsedRealtime, uptime);
Dianne Hackborn32907cf2010-06-10 17:50:20 -07005223 }
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005224 getUidStatsLocked(uid).noteWifiMulticastDisabledLocked(elapsedRealtime);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005225 }
5226
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005227 public void noteFullWifiLockAcquiredFromSourceLocked(WorkSource ws) {
5228 int N = ws.size();
5229 for (int i=0; i<N; i++) {
5230 noteFullWifiLockAcquiredLocked(ws.get(i));
5231 }
5232 }
5233
5234 public void noteFullWifiLockReleasedFromSourceLocked(WorkSource ws) {
5235 int N = ws.size();
5236 for (int i=0; i<N; i++) {
5237 noteFullWifiLockReleasedLocked(ws.get(i));
5238 }
5239 }
5240
Nick Pelly6ccaa542012-06-15 15:22:47 -07005241 public void noteWifiScanStartedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005242 int N = ws.size();
5243 for (int i=0; i<N; i++) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005244 noteWifiScanStartedLocked(ws.get(i));
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005245 }
5246 }
5247
Nick Pelly6ccaa542012-06-15 15:22:47 -07005248 public void noteWifiScanStoppedFromSourceLocked(WorkSource ws) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005249 int N = ws.size();
5250 for (int i=0; i<N; i++) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005251 noteWifiScanStoppedLocked(ws.get(i));
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005252 }
5253 }
5254
Robert Greenwalta029ea12013-09-25 16:38:12 -07005255 public void noteWifiBatchedScanStartedFromSourceLocked(WorkSource ws, int csph) {
5256 int N = ws.size();
5257 for (int i=0; i<N; i++) {
5258 noteWifiBatchedScanStartedLocked(ws.get(i), csph);
5259 }
5260 }
5261
5262 public void noteWifiBatchedScanStoppedFromSourceLocked(WorkSource ws) {
5263 int N = ws.size();
5264 for (int i=0; i<N; i++) {
5265 noteWifiBatchedScanStoppedLocked(ws.get(i));
5266 }
5267 }
5268
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07005269 public void noteWifiMulticastEnabledFromSourceLocked(WorkSource ws) {
5270 int N = ws.size();
5271 for (int i=0; i<N; i++) {
5272 noteWifiMulticastEnabledLocked(ws.get(i));
5273 }
5274 }
5275
5276 public void noteWifiMulticastDisabledFromSourceLocked(WorkSource ws) {
5277 int N = ws.size();
5278 for (int i=0; i<N; i++) {
5279 noteWifiMulticastDisabledLocked(ws.get(i));
5280 }
5281 }
5282
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08005283 private static String[] includeInStringArray(String[] array, String str) {
5284 if (ArrayUtils.indexOf(array, str) >= 0) {
5285 return array;
5286 }
5287 String[] newArray = new String[array.length+1];
5288 System.arraycopy(array, 0, newArray, 0, array.length);
5289 newArray[array.length] = str;
5290 return newArray;
5291 }
5292
5293 private static String[] excludeFromStringArray(String[] array, String str) {
5294 int index = ArrayUtils.indexOf(array, str);
5295 if (index >= 0) {
5296 String[] newArray = new String[array.length-1];
5297 if (index > 0) {
5298 System.arraycopy(array, 0, newArray, 0, index);
5299 }
5300 if (index < array.length-1) {
5301 System.arraycopy(array, index+1, newArray, index, array.length-index-1);
5302 }
5303 return newArray;
5304 }
5305 return array;
5306 }
5307
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07005308 public void noteNetworkInterfaceTypeLocked(String iface, int networkType) {
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07005309 if (TextUtils.isEmpty(iface)) return;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005310
Adam Lesinski14ae39a2017-05-26 11:50:40 -07005311 synchronized (mModemNetworkLock) {
5312 if (ConnectivityManager.isNetworkTypeMobile(networkType)) {
5313 mModemIfaces = includeInStringArray(mModemIfaces, iface);
5314 if (DEBUG) Slog.d(TAG, "Note mobile iface " + iface + ": " + mModemIfaces);
5315 } else {
5316 mModemIfaces = excludeFromStringArray(mModemIfaces, iface);
5317 if (DEBUG) Slog.d(TAG, "Note non-mobile iface " + iface + ": " + mModemIfaces);
5318 }
5319 }
5320
5321 synchronized (mWifiNetworkLock) {
5322 if (ConnectivityManager.isNetworkTypeWifi(networkType)) {
5323 mWifiIfaces = includeInStringArray(mWifiIfaces, iface);
5324 if (DEBUG) Slog.d(TAG, "Note wifi iface " + iface + ": " + mWifiIfaces);
5325 } else {
5326 mWifiIfaces = excludeFromStringArray(mWifiIfaces, iface);
5327 if (DEBUG) Slog.d(TAG, "Note non-wifi iface " + iface + ": " + mWifiIfaces);
5328 }
5329 }
Jeff Sharkey1059c3c2011-10-04 16:54:49 -07005330 }
5331
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005332 @Override public long getScreenOnTime(long elapsedRealtimeUs, int which) {
5333 return mScreenOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005334 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005335
Dianne Hackborn77b987f2014-02-26 16:20:52 -08005336 @Override public int getScreenOnCount(int which) {
5337 return mScreenOnTimer.getCountLocked(which);
5338 }
5339
Dianne Hackborn617f8772009-03-31 15:04:46 -07005340 @Override public long getScreenBrightnessTime(int brightnessBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005341 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005342 return mScreenBrightnessTimer[brightnessBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005343 elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005344 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005345
Jeff Browne95c3cd2014-05-02 16:59:26 -07005346 @Override public long getInteractiveTime(long elapsedRealtimeUs, int which) {
5347 return mInteractiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005348 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005349
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005350 @Override public long getPowerSaveModeEnabledTime(long elapsedRealtimeUs, int which) {
5351 return mPowerSaveModeEnabledTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005352 }
5353
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005354 @Override public int getPowerSaveModeEnabledCount(int which) {
5355 return mPowerSaveModeEnabledTimer.getCountLocked(which);
5356 }
5357
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005358 @Override public long getDeviceIdleModeTime(int mode, long elapsedRealtimeUs,
5359 int which) {
5360 switch (mode) {
5361 case DEVICE_IDLE_MODE_LIGHT:
5362 return mDeviceIdleModeLightTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005363 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005364 return mDeviceIdleModeFullTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5365 }
5366 return 0;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07005367 }
5368
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005369 @Override public int getDeviceIdleModeCount(int mode, int which) {
5370 switch (mode) {
5371 case DEVICE_IDLE_MODE_LIGHT:
5372 return mDeviceIdleModeLightTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005373 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005374 return mDeviceIdleModeFullTimer.getCountLocked(which);
5375 }
5376 return 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005377 }
5378
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005379 @Override public long getLongestDeviceIdleModeTime(int mode) {
5380 switch (mode) {
5381 case DEVICE_IDLE_MODE_LIGHT:
5382 return mLongestLightIdleTime;
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005383 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005384 return mLongestFullIdleTime;
5385 }
5386 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005387 }
5388
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005389 @Override public long getDeviceIdlingTime(int mode, long elapsedRealtimeUs, int which) {
5390 switch (mode) {
5391 case DEVICE_IDLE_MODE_LIGHT:
5392 return mDeviceLightIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005393 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005394 return mDeviceIdlingTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5395 }
5396 return 0;
5397 }
5398
5399 @Override public int getDeviceIdlingCount(int mode, int which) {
5400 switch (mode) {
5401 case DEVICE_IDLE_MODE_LIGHT:
5402 return mDeviceLightIdlingTimer.getCountLocked(which);
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07005403 case DEVICE_IDLE_MODE_DEEP:
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005404 return mDeviceIdlingTimer.getCountLocked(which);
5405 }
5406 return 0;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005407 }
5408
Dianne Hackborn1e01d162014-12-04 17:46:42 -08005409 @Override public int getNumConnectivityChange(int which) {
5410 int val = mNumConnectivityChange;
5411 if (which == STATS_CURRENT) {
5412 val -= mLoadedNumConnectivityChange;
5413 } else if (which == STATS_SINCE_UNPLUGGED) {
5414 val -= mUnpluggedNumConnectivityChange;
5415 }
5416 return val;
5417 }
5418
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005419 @Override public long getPhoneOnTime(long elapsedRealtimeUs, int which) {
5420 return mPhoneOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005422
Dianne Hackborn77b987f2014-02-26 16:20:52 -08005423 @Override public int getPhoneOnCount(int which) {
5424 return mPhoneOnTimer.getCountLocked(which);
5425 }
5426
Dianne Hackborn627bba72009-03-24 22:32:56 -07005427 @Override public long getPhoneSignalStrengthTime(int strengthBin,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005428 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005429 return mPhoneSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005430 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005431 }
Amith Yamasanif37447b2009-10-08 18:28:01 -07005432
5433 @Override public long getPhoneSignalScanningTime(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005434 long elapsedRealtimeUs, int which) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07005435 return mPhoneSignalScanningTimer.getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005436 elapsedRealtimeUs, which);
Amith Yamasanif37447b2009-10-08 18:28:01 -07005437 }
5438
Catherine Liufb900812012-07-17 14:12:56 -05005439 @Override public int getPhoneSignalStrengthCount(int strengthBin, int which) {
5440 return mPhoneSignalStrengthsTimer[strengthBin].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005441 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005442
Dianne Hackborn627bba72009-03-24 22:32:56 -07005443 @Override public long getPhoneDataConnectionTime(int dataType,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005444 long elapsedRealtimeUs, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005445 return mPhoneDataConnectionsTimer[dataType].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005446 elapsedRealtimeUs, which);
Dianne Hackborn627bba72009-03-24 22:32:56 -07005447 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005448
Dianne Hackborn617f8772009-03-31 15:04:46 -07005449 @Override public int getPhoneDataConnectionCount(int dataType, int which) {
Evan Millarc64edde2009-04-18 12:26:32 -07005450 return mPhoneDataConnectionsTimer[dataType].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005451 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005452
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005453 @Override public long getMobileRadioActiveTime(long elapsedRealtimeUs, int which) {
5454 return mMobileRadioActiveTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborne13c4c02014-02-11 17:18:35 -08005455 }
5456
Dianne Hackbornd45665b2014-02-26 12:35:32 -08005457 @Override public int getMobileRadioActiveCount(int which) {
5458 return mMobileRadioActiveTimer.getCountLocked(which);
5459 }
5460
Dianne Hackborna1bd7922014-03-21 11:07:11 -07005461 @Override public long getMobileRadioActiveAdjustedTime(int which) {
5462 return mMobileRadioActiveAdjustedTime.getCountLocked(which);
5463 }
5464
Dianne Hackbornd45665b2014-02-26 12:35:32 -08005465 @Override public long getMobileRadioActiveUnknownTime(int which) {
5466 return mMobileRadioActiveUnknownTime.getCountLocked(which);
5467 }
5468
5469 @Override public int getMobileRadioActiveUnknownCount(int which) {
5470 return (int)mMobileRadioActiveUnknownCount.getCountLocked(which);
5471 }
5472
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005473 @Override public long getWifiOnTime(long elapsedRealtimeUs, int which) {
5474 return mWifiOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07005475 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005476
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005477 @Override public long getGlobalWifiRunningTime(long elapsedRealtimeUs, int which) {
5478 return mGlobalWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Eric Shienbroodd4c5f892009-03-24 18:13:20 -07005479 }
5480
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005481 @Override public long getWifiStateTime(int wifiState,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005482 long elapsedRealtimeUs, int which) {
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005483 return mWifiStateTimer[wifiState].getTotalTimeLocked(
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005484 elapsedRealtimeUs, which);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08005485 }
5486
5487 @Override public int getWifiStateCount(int wifiState, int which) {
5488 return mWifiStateTimer[wifiState].getCountLocked(which);
5489 }
5490
Dianne Hackborn3251b902014-06-20 14:40:53 -07005491 @Override public long getWifiSupplStateTime(int state,
5492 long elapsedRealtimeUs, int which) {
5493 return mWifiSupplStateTimer[state].getTotalTimeLocked(
5494 elapsedRealtimeUs, which);
5495 }
5496
5497 @Override public int getWifiSupplStateCount(int state, int which) {
5498 return mWifiSupplStateTimer[state].getCountLocked(which);
5499 }
5500
5501 @Override public long getWifiSignalStrengthTime(int strengthBin,
5502 long elapsedRealtimeUs, int which) {
5503 return mWifiSignalStrengthsTimer[strengthBin].getTotalTimeLocked(
5504 elapsedRealtimeUs, which);
5505 }
5506
5507 @Override public int getWifiSignalStrengthCount(int strengthBin, int which) {
5508 return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
5509 }
5510
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005511 @Override
5512 public ControllerActivityCounter getBluetoothControllerActivity() {
5513 return mBluetoothActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07005514 }
5515
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005516 @Override
5517 public ControllerActivityCounter getWifiControllerActivity() {
5518 return mWifiActivity;
Adam Lesinski33dac552015-03-09 15:24:48 -07005519 }
5520
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005521 @Override
5522 public ControllerActivityCounter getModemControllerActivity() {
5523 return mModemActivity;
Adam Lesinski17390762015-04-10 13:17:47 -07005524 }
5525
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005526 @Override
5527 public boolean hasBluetoothActivityReporting() {
5528 return mHasBluetoothReporting;
5529 }
5530
5531 @Override
5532 public boolean hasWifiActivityReporting() {
5533 return mHasWifiReporting;
5534 }
5535
5536 @Override
5537 public boolean hasModemActivityReporting() {
5538 return mHasModemReporting;
Adam Lesinski33dac552015-03-09 15:24:48 -07005539 }
5540
Ruben Brunk5b1308f2015-06-03 18:49:27 -07005541 @Override
5542 public long getFlashlightOnTime(long elapsedRealtimeUs, int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005543 return mFlashlightOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5544 }
5545
Ruben Brunk5b1308f2015-06-03 18:49:27 -07005546 @Override
5547 public long getFlashlightOnCount(int which) {
Dianne Hackbornabc7c492014-06-30 16:57:46 -07005548 return mFlashlightOnTimer.getCountLocked(which);
5549 }
5550
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005551 @Override
Ruben Brunk5b1308f2015-06-03 18:49:27 -07005552 public long getCameraOnTime(long elapsedRealtimeUs, int which) {
5553 return mCameraOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5554 }
5555
5556 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08005557 public long getBluetoothScanTime(long elapsedRealtimeUs, int which) {
5558 return mBluetoothScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
5559 }
5560
5561 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08005562 public long getNetworkActivityBytes(int type, int which) {
5563 if (type >= 0 && type < mNetworkByteActivityCounters.length) {
5564 return mNetworkByteActivityCounters[type].getCountLocked(which);
5565 } else {
5566 return 0;
5567 }
5568 }
5569
5570 @Override
5571 public long getNetworkActivityPackets(int type, int which) {
5572 if (type >= 0 && type < mNetworkPacketActivityCounters.length) {
5573 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005574 } else {
5575 return 0;
5576 }
5577 }
5578
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08005579 @Override public long getStartClockTime() {
Dianne Hackbornd48954f2015-07-22 17:20:33 -07005580 final long currentTime = System.currentTimeMillis();
5581 if (ensureStartClockTime(currentTime)) {
Joe Onoratoabded112016-02-08 16:49:39 -08005582 recordCurrentTimeChangeLocked(currentTime, mClocks.elapsedRealtime(),
5583 mClocks.uptimeMillis());
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -07005584 }
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08005585 return mStartClockTime;
5586 }
5587
Dianne Hackborncd0e3352014-08-07 17:08:09 -07005588 @Override public String getStartPlatformVersion() {
5589 return mStartPlatformVersion;
5590 }
5591
5592 @Override public String getEndPlatformVersion() {
5593 return mEndPlatformVersion;
5594 }
5595
5596 @Override public int getParcelVersion() {
5597 return VERSION;
5598 }
5599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005600 @Override public boolean getIsOnBattery() {
5601 return mOnBattery;
5602 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005604 @Override public SparseArray<? extends BatteryStats.Uid> getUidStats() {
5605 return mUidStats;
5606 }
5607
Adam Lesinski5f056f62016-07-14 16:56:08 -07005608 private static void detachTimerIfNotNull(BatteryStatsImpl.Timer timer) {
5609 if (timer != null) {
5610 timer.detach();
5611 }
5612 }
5613
5614 private static boolean resetTimerIfNotNull(BatteryStatsImpl.Timer timer,
5615 boolean detachIfReset) {
5616 if (timer != null) {
5617 return timer.reset(detachIfReset);
5618 }
5619 return true;
5620 }
5621
Bookatz867c0d72017-03-07 18:23:42 -08005622 private static boolean resetTimerIfNotNull(DualTimer timer, boolean detachIfReset) {
5623 if (timer != null) {
5624 return timer.reset(detachIfReset);
5625 }
5626 return true;
5627 }
5628
Adam Lesinski5f056f62016-07-14 16:56:08 -07005629 private static void detachLongCounterIfNotNull(LongSamplingCounter counter) {
5630 if (counter != null) {
5631 counter.detach();
5632 }
5633 }
5634
5635 private static void resetLongCounterIfNotNull(LongSamplingCounter counter,
5636 boolean detachIfReset) {
5637 if (counter != null) {
5638 counter.reset(detachIfReset);
5639 }
5640 }
5641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 /**
5643 * The statistics associated with a particular uid.
5644 */
Joe Onoratoabded112016-02-08 16:49:39 -08005645 public static class Uid extends BatteryStats.Uid {
5646 /**
5647 * BatteryStatsImpl that we are associated with.
5648 */
5649 protected BatteryStatsImpl mBsi;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 final int mUid;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005652
Bookatz867c0d72017-03-07 18:23:42 -08005653 /** TimeBase for when uid is in background and device is on battery. */
5654 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
5655 public final TimeBase mOnBatteryBackgroundTimeBase;
Bookatzc8c44962017-05-11 12:12:54 -07005656 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
5657 public final TimeBase mOnBatteryScreenOffBackgroundTimeBase;
Bookatz867c0d72017-03-07 18:23:42 -08005658
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005659 boolean mWifiRunning;
5660 StopwatchTimer mWifiRunningTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005661
The Android Open Source Project10592532009-03-18 17:39:46 -07005662 boolean mFullWifiLockOut;
Evan Millarc64edde2009-04-18 12:26:32 -07005663 StopwatchTimer mFullWifiLockTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005664
Nick Pelly6ccaa542012-06-15 15:22:47 -07005665 boolean mWifiScanStarted;
Bookatz867c0d72017-03-07 18:23:42 -08005666 DualTimer mWifiScanTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005667
Dianne Hackborn61659e52014-07-09 16:13:01 -07005668 static final int NO_BATCHED_SCAN_STARTED = -1;
Robert Greenwalta029ea12013-09-25 16:38:12 -07005669 int mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
5670 StopwatchTimer[] mWifiBatchedScanTimer;
5671
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005672 boolean mWifiMulticastEnabled;
5673 StopwatchTimer mWifiMulticastTimer;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005674
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005675 StopwatchTimer mAudioTurnedOnTimer;
Amith Yamasani244fa5c2009-05-22 14:36:07 -07005676 StopwatchTimer mVideoTurnedOnTimer;
Ruben Brunk6d2c3632015-05-26 17:32:16 -07005677 StopwatchTimer mFlashlightTurnedOnTimer;
5678 StopwatchTimer mCameraTurnedOnTimer;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005679 StopwatchTimer mForegroundActivityTimer;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07005680 StopwatchTimer mForegroundServiceTimer;
Bookatzc8c44962017-05-11 12:12:54 -07005681 /** Total time spent by the uid holding any partial wakelocks. */
5682 DualTimer mAggregatedPartialWakelockTimer;
Bookatz867c0d72017-03-07 18:23:42 -08005683 DualTimer mBluetoothScanTimer;
Bookatzb1f04f32017-05-19 13:57:32 -07005684 DualTimer mBluetoothUnoptimizedScanTimer;
Bookatz956f36bf2017-04-28 09:48:17 -07005685 Counter mBluetoothScanResultCounter;
Bookatzb1f04f32017-05-19 13:57:32 -07005686 Counter mBluetoothScanResultBgCounter;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07005687
Dianne Hackborna8d10942015-11-19 17:55:19 -08005688 int mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07005689 StopwatchTimer[] mProcessStateTimer;
5690
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07005691 boolean mInForegroundService = false;
5692
Dianne Hackborna06de0f2012-12-11 16:34:47 -08005693 BatchTimer mVibratorOnTimer;
5694
Dianne Hackborn617f8772009-03-31 15:04:46 -07005695 Counter[] mUserActivityCounters;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005696
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08005697 LongSamplingCounter[] mNetworkByteActivityCounters;
5698 LongSamplingCounter[] mNetworkPacketActivityCounters;
Dianne Hackbornd45665b2014-02-26 12:35:32 -08005699 LongSamplingCounter mMobileRadioActiveTime;
5700 LongSamplingCounter mMobileRadioActiveCount;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07005701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 /**
Adam Lesinski5f056f62016-07-14 16:56:08 -07005703 * How many times this UID woke up the Application Processor due to a Mobile radio packet.
5704 */
5705 private LongSamplingCounter mMobileRadioApWakeupCount;
5706
5707 /**
5708 * How many times this UID woke up the Application Processor due to a Wifi packet.
5709 */
5710 private LongSamplingCounter mWifiRadioApWakeupCount;
5711
5712 /**
Adam Lesinskie08af192015-03-25 16:42:59 -07005713 * The amount of time this uid has kept the WiFi controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005714 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07005715 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005716 private ControllerActivityCounterImpl mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07005717
5718 /**
5719 * The amount of time this uid has kept the Bluetooth controller in idle, tx, and rx mode.
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005720 * Can be null if the UID has had no such activity.
Adam Lesinskie08af192015-03-25 16:42:59 -07005721 */
Adam Lesinski21f76aa2016-01-25 12:27:06 -08005722 private ControllerActivityCounterImpl mBluetoothControllerActivity;
5723
5724 /**
5725 * The amount of time this uid has kept the Modem controller in idle, tx, and rx mode.
5726 * Can be null if the UID has had no such activity.
5727 */
5728 private ControllerActivityCounterImpl mModemControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07005729
5730 /**
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08005731 * The CPU times we had at the last history details update.
5732 */
5733 long mLastStepUserTime;
5734 long mLastStepSystemTime;
5735 long mCurStepUserTime;
5736 long mCurStepSystemTime;
5737
Joe Onoratoabded112016-02-08 16:49:39 -08005738 LongSamplingCounter mUserCpuTime;
5739 LongSamplingCounter mSystemCpuTime;
Sudheer Shankaaf857412017-07-21 00:14:24 -07005740 LongSamplingCounter[][] mCpuClusterSpeedTimesUs;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07005741
Sudheer Shanka9b735c52017-05-09 18:26:18 -07005742 LongSamplingCounterArray mCpuFreqTimeMs;
5743 LongSamplingCounterArray mScreenOffCpuFreqTimeMs;
5744
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08005745 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005746 * The statistics we have collected for this uid's wake locks.
5747 */
Joe Onoratoabded112016-02-08 16:49:39 -08005748 final OverflowArrayMap<Wakelock> mWakelockStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749
5750 /**
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005751 * The statistics we have collected for this uid's syncs.
5752 */
Bookatz2bffb5b2017-04-13 11:59:33 -07005753 final OverflowArrayMap<DualTimer> mSyncStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005754
5755 /**
5756 * The statistics we have collected for this uid's jobs.
5757 */
Bookatzaa4594a2017-03-24 12:39:56 -07005758 final OverflowArrayMap<DualTimer> mJobStats;
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005759
5760 /**
Dianne Hackborn94326cb2017-06-28 16:17:20 -07005761 * Count of the jobs that have completed and the reasons why they completed.
5762 */
5763 final ArrayMap<String, SparseIntArray> mJobCompletions = new ArrayMap<>();
5764
5765 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005766 * The statistics we have collected for this uid's sensor activations.
5767 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005768 final SparseArray<Sensor> mSensorStats = new SparseArray<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769
5770 /**
5771 * The statistics we have collected for this uid's processes.
5772 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005773 final ArrayMap<String, Proc> mProcessStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774
5775 /**
5776 * The statistics we have collected for this uid's processes.
5777 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005778 final ArrayMap<String, Pkg> mPackageStats = new ArrayMap<>();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005779
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005780 /**
5781 * The transient wake stats we have collected for this uid's pids.
5782 */
Adam Lesinskie08af192015-03-25 16:42:59 -07005783 final SparseArray<Pid> mPids = new SparseArray<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07005784
Joe Onoratoabded112016-02-08 16:49:39 -08005785 public Uid(BatteryStatsImpl bsi, int uid) {
5786 mBsi = bsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 mUid = uid;
Joe Onoratoabded112016-02-08 16:49:39 -08005788
Bookatz867c0d72017-03-07 18:23:42 -08005789 mOnBatteryBackgroundTimeBase = new TimeBase();
5790 mOnBatteryBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
5791 mBsi.mClocks.elapsedRealtime() * 1000);
5792
Bookatzc8c44962017-05-11 12:12:54 -07005793 mOnBatteryScreenOffBackgroundTimeBase = new TimeBase();
5794 mOnBatteryScreenOffBackgroundTimeBase.init(mBsi.mClocks.uptimeMillis() * 1000,
5795 mBsi.mClocks.elapsedRealtime() * 1000);
5796
Joe Onoratoabded112016-02-08 16:49:39 -08005797 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
5798 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08005799
Dianne Hackborn657153b2016-07-29 14:54:14 -07005800 mWakelockStats = mBsi.new OverflowArrayMap<Wakelock>(uid) {
Joe Onoratoabded112016-02-08 16:49:39 -08005801 @Override public Wakelock instantiateObject() {
5802 return new Wakelock(mBsi, Uid.this);
5803 }
5804 };
Bookatz2bffb5b2017-04-13 11:59:33 -07005805 mSyncStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
5806 @Override public DualTimer instantiateObject() {
5807 return new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
5808 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08005809 }
5810 };
Bookatzaa4594a2017-03-24 12:39:56 -07005811 mJobStats = mBsi.new OverflowArrayMap<DualTimer>(uid) {
5812 @Override public DualTimer instantiateObject() {
5813 return new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
5814 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08005815 }
5816 };
5817
5818 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_RUNNING,
5819 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
5820 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, this, FULL_WIFI_LOCK,
5821 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Bookatz867c0d72017-03-07 18:23:42 -08005822 mWifiScanTimer = new DualTimer(mBsi.mClocks, this, WIFI_SCAN,
5823 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005824 mWifiBatchedScanTimer = new StopwatchTimer[NUM_WIFI_BATCHED_SCAN_BINS];
Joe Onoratoabded112016-02-08 16:49:39 -08005825 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, this, WIFI_MULTICAST_ENABLED,
5826 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07005827 mProcessStateTimer = new StopwatchTimer[NUM_PROCESS_STATE];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 }
5829
5830 @Override
Sudheer Shanka9b735c52017-05-09 18:26:18 -07005831 public long[] getCpuFreqTimes(int which) {
5832 if (mCpuFreqTimeMs == null) {
5833 return null;
5834 }
5835 final long[] cpuFreqTimes = mCpuFreqTimeMs.getCountsLocked(which);
5836 if (cpuFreqTimes == null) {
5837 return null;
5838 }
5839 // Return cpuFreqTimes only if atleast one of the elements in non-zero.
5840 for (int i = 0; i < cpuFreqTimes.length; ++i) {
5841 if (cpuFreqTimes[i] != 0) {
5842 return cpuFreqTimes;
5843 }
5844 }
5845 return null;
5846 }
5847
5848 @Override
5849 public long[] getScreenOffCpuFreqTimes(int which) {
5850 if (mScreenOffCpuFreqTimeMs == null) {
5851 return null;
5852 }
5853 final long[] cpuFreqTimes = mScreenOffCpuFreqTimeMs.getCountsLocked(which);
5854 if (cpuFreqTimes == null) {
5855 return null;
5856 }
5857 // Return cpuFreqTimes only if atleast one of the elements in non-zero.
5858 for (int i = 0; i < cpuFreqTimes.length; ++i) {
5859 if (cpuFreqTimes[i] != 0) {
5860 return cpuFreqTimes;
5861 }
5862 }
5863 return null;
5864 }
5865
5866 @Override
Bookatzc8c44962017-05-11 12:12:54 -07005867 public Timer getAggregatedPartialWakelockTimer() {
5868 return mAggregatedPartialWakelockTimer;
5869 }
5870
5871 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005872 public ArrayMap<String, ? extends BatteryStats.Uid.Wakelock> getWakelockStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07005873 return mWakelockStats.getMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 }
5875
5876 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005877 public ArrayMap<String, ? extends BatteryStats.Timer> getSyncStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07005878 return mSyncStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005879 }
5880
5881 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005882 public ArrayMap<String, ? extends BatteryStats.Timer> getJobStats() {
Dianne Hackbornd953c532014-08-16 18:17:38 -07005883 return mJobStats.getMap();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07005884 }
5885
5886 @Override
Dianne Hackborn94326cb2017-06-28 16:17:20 -07005887 public ArrayMap<String, SparseIntArray> getJobCompletionStats() {
5888 return mJobCompletions;
5889 }
5890
5891 @Override
Dianne Hackborn61659e52014-07-09 16:13:01 -07005892 public SparseArray<? extends BatteryStats.Uid.Sensor> getSensorStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 return mSensorStats;
5894 }
5895
5896 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005897 public ArrayMap<String, ? extends BatteryStats.Uid.Proc> getProcessStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005898 return mProcessStats;
5899 }
5900
5901 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07005902 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg> getPackageStats() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005903 return mPackageStats;
5904 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07005905
5906 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 public int getUid() {
5908 return mUid;
5909 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07005910
5911 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005912 public void noteWifiRunningLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005913 if (!mWifiRunning) {
5914 mWifiRunning = true;
5915 if (mWifiRunningTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005916 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
5917 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005918 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005919 mWifiRunningTimer.startRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005920 }
5921 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005922
Dianne Hackborn617f8772009-03-31 15:04:46 -07005923 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005924 public void noteWifiStoppedLocked(long elapsedRealtimeMs) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07005925 if (mWifiRunning) {
5926 mWifiRunning = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005927 mWifiRunningTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07005928 }
5929 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005930
Dianne Hackborn617f8772009-03-31 15:04:46 -07005931 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005932 public void noteFullWifiLockAcquiredLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005933 if (!mFullWifiLockOut) {
5934 mFullWifiLockOut = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005935 if (mFullWifiLockTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08005936 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
5937 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005938 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005939 mFullWifiLockTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07005940 }
5941 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005942
The Android Open Source Project10592532009-03-18 17:39:46 -07005943 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005944 public void noteFullWifiLockReleasedLocked(long elapsedRealtimeMs) {
The Android Open Source Project10592532009-03-18 17:39:46 -07005945 if (mFullWifiLockOut) {
5946 mFullWifiLockOut = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005947 mFullWifiLockTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07005948 }
5949 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005950
The Android Open Source Project10592532009-03-18 17:39:46 -07005951 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005952 public void noteWifiScanStartedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005953 if (!mWifiScanStarted) {
5954 mWifiScanStarted = true;
5955 if (mWifiScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08005956 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
5957 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase,
5958 mOnBatteryBackgroundTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07005959 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005960 mWifiScanTimer.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07005961 }
5962 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07005963
The Android Open Source Project10592532009-03-18 17:39:46 -07005964 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005965 public void noteWifiScanStoppedLocked(long elapsedRealtimeMs) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07005966 if (mWifiScanStarted) {
5967 mWifiScanStarted = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005968 mWifiScanTimer.stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project10592532009-03-18 17:39:46 -07005969 }
5970 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07005971
5972 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005973 public void noteWifiBatchedScanStartedLocked(int csph, long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07005974 int bin = 0;
Navtej Singh Mann3c0ce5c2015-06-11 16:53:11 -07005975 while (csph > 8 && bin < NUM_WIFI_BATCHED_SCAN_BINS-1) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07005976 csph = csph >> 3;
5977 bin++;
5978 }
5979
5980 if (mWifiBatchedScanBinStarted == bin) return;
5981
5982 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
5983 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005984 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005985 }
5986 mWifiBatchedScanBinStarted = bin;
5987 if (mWifiBatchedScanTimer[bin] == null) {
5988 makeWifiBatchedScanBin(bin, null);
5989 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005990 mWifiBatchedScanTimer[bin].startRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005991 }
5992
5993 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005994 public void noteWifiBatchedScanStoppedLocked(long elapsedRealtimeMs) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07005995 if (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED) {
5996 mWifiBatchedScanTimer[mWifiBatchedScanBinStarted].
Dianne Hackborn97ae5382014-03-05 16:43:25 -08005997 stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07005998 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
5999 }
6000 }
6001
6002 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006003 public void noteWifiMulticastEnabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006004 if (!mWifiMulticastEnabled) {
6005 mWifiMulticastEnabled = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006006 if (mWifiMulticastTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006007 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6008 WIFI_MULTICAST_ENABLED, mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006009 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006010 mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006011 }
6012 }
6013
6014 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006015 public void noteWifiMulticastDisabledLocked(long elapsedRealtimeMs) {
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006016 if (mWifiMulticastEnabled) {
6017 mWifiMulticastEnabled = false;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006018 mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006019 }
6020 }
6021
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006022 @Override
6023 public ControllerActivityCounter getWifiControllerActivity() {
6024 return mWifiControllerActivity;
Adam Lesinskie08af192015-03-25 16:42:59 -07006025 }
6026
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006027 @Override
6028 public ControllerActivityCounter getBluetoothControllerActivity() {
6029 return mBluetoothControllerActivity;
6030 }
6031
6032 @Override
6033 public ControllerActivityCounter getModemControllerActivity() {
6034 return mModemControllerActivity;
6035 }
6036
6037 public ControllerActivityCounterImpl getOrCreateWifiControllerActivityLocked() {
6038 if (mWifiControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006039 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006040 NUM_BT_TX_LEVELS);
Adam Lesinski50e47602015-12-04 17:04:54 -08006041 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006042 return mWifiControllerActivity;
6043 }
6044
6045 public ControllerActivityCounterImpl getOrCreateBluetoothControllerActivityLocked() {
6046 if (mBluetoothControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006047 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006048 NUM_BT_TX_LEVELS);
6049 }
6050 return mBluetoothControllerActivity;
6051 }
6052
6053 public ControllerActivityCounterImpl getOrCreateModemControllerActivityLocked() {
6054 if (mModemControllerActivity == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006055 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006056 ModemActivityInfo.TX_POWER_LEVELS);
6057 }
6058 return mModemControllerActivity;
Adam Lesinski50e47602015-12-04 17:04:54 -08006059 }
6060
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006061 public StopwatchTimer createAudioTurnedOnTimerLocked() {
6062 if (mAudioTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006063 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
6064 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006065 }
6066 return mAudioTurnedOnTimer;
6067 }
6068
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006069 public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006070 createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
6071 }
6072
6073 public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
6074 if (mAudioTurnedOnTimer != null) {
6075 mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006076 }
6077 }
6078
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006079 public void noteResetAudioLocked(long elapsedRealtimeMs) {
6080 if (mAudioTurnedOnTimer != null) {
6081 mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006082 }
6083 }
6084
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006085 public StopwatchTimer createVideoTurnedOnTimerLocked() {
6086 if (mVideoTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006087 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
6088 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006089 }
6090 return mVideoTurnedOnTimer;
6091 }
6092
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006093 public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006094 createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
6095 }
6096
6097 public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
6098 if (mVideoTurnedOnTimer != null) {
6099 mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006100 }
6101 }
6102
Dianne Hackborn10eaa852014-07-22 22:54:55 -07006103 public void noteResetVideoLocked(long elapsedRealtimeMs) {
6104 if (mVideoTurnedOnTimer != null) {
6105 mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006106 }
6107 }
6108
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006109 public StopwatchTimer createFlashlightTurnedOnTimerLocked() {
6110 if (mFlashlightTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006111 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6112 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006113 }
6114 return mFlashlightTurnedOnTimer;
6115 }
6116
6117 public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
6118 createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
6119 }
6120
6121 public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
6122 if (mFlashlightTurnedOnTimer != null) {
6123 mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
6124 }
6125 }
6126
6127 public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
6128 if (mFlashlightTurnedOnTimer != null) {
6129 mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
6130 }
6131 }
6132
6133 public StopwatchTimer createCameraTurnedOnTimerLocked() {
6134 if (mCameraTurnedOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006135 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
6136 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006137 }
6138 return mCameraTurnedOnTimer;
6139 }
6140
6141 public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
6142 createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
6143 }
6144
6145 public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
6146 if (mCameraTurnedOnTimer != null) {
6147 mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
6148 }
6149 }
6150
6151 public void noteResetCameraLocked(long elapsedRealtimeMs) {
6152 if (mCameraTurnedOnTimer != null) {
6153 mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
6154 }
6155 }
6156
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006157 public StopwatchTimer createForegroundActivityTimerLocked() {
6158 if (mForegroundActivityTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006159 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6160 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006161 }
6162 return mForegroundActivityTimer;
6163 }
6164
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006165 public StopwatchTimer createForegroundServiceTimerLocked() {
6166 if (mForegroundServiceTimer == null) {
6167 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
6168 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase);
6169 }
6170 return mForegroundServiceTimer;
6171 }
6172
Bookatzc8c44962017-05-11 12:12:54 -07006173 public DualTimer createAggregatedPartialWakelockTimerLocked() {
6174 if (mAggregatedPartialWakelockTimer == null) {
6175 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
6176 AGGREGATED_WAKE_TYPE_PARTIAL, null,
6177 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase);
6178 }
6179 return mAggregatedPartialWakelockTimer;
6180 }
6181
Bookatz867c0d72017-03-07 18:23:42 -08006182 public DualTimer createBluetoothScanTimerLocked() {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006183 if (mBluetoothScanTimer == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006184 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
6185 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
6186 mOnBatteryBackgroundTimeBase);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006187 }
6188 return mBluetoothScanTimer;
6189 }
6190
Bookatzb1f04f32017-05-19 13:57:32 -07006191 public DualTimer createBluetoothUnoptimizedScanTimerLocked() {
6192 if (mBluetoothUnoptimizedScanTimer == null) {
6193 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
6194 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
6195 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
6196 }
6197 return mBluetoothUnoptimizedScanTimer;
6198 }
6199
6200 public void noteBluetoothScanStartedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006201 createBluetoothScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
Bookatzb1f04f32017-05-19 13:57:32 -07006202 if (isUnoptimized) {
6203 createBluetoothUnoptimizedScanTimerLocked().startRunningLocked(elapsedRealtimeMs);
6204 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006205 }
6206
Bookatz94c5a312017-07-11 16:49:17 -07006207 public void noteBluetoothScanStoppedLocked(long elapsedRealtimeMs, boolean isUnoptimized) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006208 if (mBluetoothScanTimer != null) {
6209 mBluetoothScanTimer.stopRunningLocked(elapsedRealtimeMs);
6210 }
Bookatz94c5a312017-07-11 16:49:17 -07006211 if (isUnoptimized && mBluetoothUnoptimizedScanTimer != null) {
Bookatzb1f04f32017-05-19 13:57:32 -07006212 mBluetoothUnoptimizedScanTimer.stopRunningLocked(elapsedRealtimeMs);
6213 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006214 }
6215
6216 public void noteResetBluetoothScanLocked(long elapsedRealtimeMs) {
6217 if (mBluetoothScanTimer != null) {
6218 mBluetoothScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
6219 }
Bookatzb1f04f32017-05-19 13:57:32 -07006220 if (mBluetoothUnoptimizedScanTimer != null) {
6221 mBluetoothUnoptimizedScanTimer.stopAllRunningLocked(elapsedRealtimeMs);
6222 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006223 }
6224
Bookatz956f36bf2017-04-28 09:48:17 -07006225 public Counter createBluetoothScanResultCounterLocked() {
6226 if (mBluetoothScanResultCounter == null) {
6227 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase);
6228 }
6229 return mBluetoothScanResultCounter;
6230 }
6231
Bookatzb1f04f32017-05-19 13:57:32 -07006232 public Counter createBluetoothScanResultBgCounterLocked() {
6233 if (mBluetoothScanResultBgCounter == null) {
6234 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase);
6235 }
6236 return mBluetoothScanResultBgCounter;
6237 }
6238
Bookatz4ebc0642017-05-11 12:21:19 -07006239 public void noteBluetoothScanResultsLocked(int numNewResults) {
6240 createBluetoothScanResultCounterLocked().addAtomic(numNewResults);
Bookatzb1f04f32017-05-19 13:57:32 -07006241 // Uses background timebase, so the count will only be incremented if uid in background.
6242 createBluetoothScanResultBgCounterLocked().addAtomic(numNewResults);
Bookatz956f36bf2017-04-28 09:48:17 -07006243 }
6244
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006245 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006246 public void noteActivityResumedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006247 // We always start, since we want multiple foreground PIDs to nest
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006248 createForegroundActivityTimerLocked().startRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006249 }
6250
6251 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006252 public void noteActivityPausedLocked(long elapsedRealtimeMs) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006253 if (mForegroundActivityTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006254 mForegroundActivityTimer.stopRunningLocked(elapsedRealtimeMs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006255 }
6256 }
6257
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006258 public void noteForegroundServiceResumedLocked(long elapsedRealtimeMs) {
6259 createForegroundServiceTimerLocked().startRunningLocked(elapsedRealtimeMs);
6260 }
6261
6262 public void noteForegroundServicePausedLocked(long elapsedRealtimeMs) {
6263 if (mForegroundServiceTimer != null) {
6264 mForegroundServiceTimer.stopRunningLocked(elapsedRealtimeMs);
6265 }
6266 }
6267
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006268 public BatchTimer createVibratorOnTimerLocked() {
6269 if (mVibratorOnTimer == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006270 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
6271 mBsi.mOnBatteryTimeBase);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006272 }
6273 return mVibratorOnTimer;
6274 }
6275
6276 public void noteVibratorOnLocked(long durationMillis) {
Joe Onoratoabded112016-02-08 16:49:39 -08006277 createVibratorOnTimerLocked().addDuration(mBsi, durationMillis);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006278 }
6279
6280 public void noteVibratorOffLocked() {
6281 if (mVibratorOnTimer != null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006282 mVibratorOnTimer.abortLastDuration(mBsi);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006283 }
6284 }
6285
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006286 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006287 public long getWifiRunningTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006288 if (mWifiRunningTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006289 return 0;
6290 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006291 return mWifiRunningTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006292 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006293
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006294 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006295 public long getFullWifiLockTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006296 if (mFullWifiLockTimer == null) {
6297 return 0;
6298 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006299 return mFullWifiLockTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006300 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006301
6302 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006303 public long getWifiScanTime(long elapsedRealtimeUs, int which) {
Nick Pelly6ccaa542012-06-15 15:22:47 -07006304 if (mWifiScanTimer == null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006305 return 0;
6306 }
Bookatzaa4594a2017-03-24 12:39:56 -07006307 return mWifiScanTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
The Android Open Source Project10592532009-03-18 17:39:46 -07006308 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006309
6310 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07006311 public int getWifiScanCount(int which) {
6312 if (mWifiScanTimer == null) {
6313 return 0;
6314 }
Bookatzaa4594a2017-03-24 12:39:56 -07006315 return mWifiScanTimer.getCountLocked(which);
Bookatz867c0d72017-03-07 18:23:42 -08006316 }
6317
6318 @Override
6319 public int getWifiScanBackgroundCount(int which) {
Bookatzaa4594a2017-03-24 12:39:56 -07006320 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006321 return 0;
6322 }
6323 return mWifiScanTimer.getSubTimer().getCountLocked(which);
6324 }
6325
6326 @Override
6327 public long getWifiScanActualTime(final long elapsedRealtimeUs) {
6328 if (mWifiScanTimer == null) {
6329 return 0;
6330 }
6331 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
Bookatzaa4594a2017-03-24 12:39:56 -07006332 return mWifiScanTimer.getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Bookatz867c0d72017-03-07 18:23:42 -08006333 }
6334
6335 @Override
6336 public long getWifiScanBackgroundTime(final long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07006337 if (mWifiScanTimer == null || mWifiScanTimer.getSubTimer() == null) {
Bookatz867c0d72017-03-07 18:23:42 -08006338 return 0;
6339 }
6340 final long elapsedRealtimeMs = (elapsedRealtimeUs + 500) / 1000;
6341 return mWifiScanTimer.getSubTimer().getTotalDurationMsLocked(elapsedRealtimeMs) * 1000;
Dianne Hackborn62793e42015-03-09 11:15:41 -07006342 }
6343
6344 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006345 public long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which) {
Robert Greenwalta029ea12013-09-25 16:38:12 -07006346 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
6347 if (mWifiBatchedScanTimer[csphBin] == null) {
6348 return 0;
6349 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006350 return mWifiBatchedScanTimer[csphBin].getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006351 }
6352
6353 @Override
Dianne Hackborn62793e42015-03-09 11:15:41 -07006354 public int getWifiBatchedScanCount(int csphBin, int which) {
6355 if (csphBin < 0 || csphBin >= NUM_WIFI_BATCHED_SCAN_BINS) return 0;
6356 if (mWifiBatchedScanTimer[csphBin] == null) {
6357 return 0;
6358 }
6359 return mWifiBatchedScanTimer[csphBin].getCountLocked(which);
6360 }
6361
6362 @Override
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006363 public long getWifiMulticastTime(long elapsedRealtimeUs, int which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006364 if (mWifiMulticastTimer == null) {
6365 return 0;
6366 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006367 return mWifiMulticastTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
Robert Greenwalt5347bd42009-05-13 15:10:16 -07006368 }
6369
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006370 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006371 public Timer getAudioTurnedOnTimer() {
6372 return mAudioTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006373 }
6374
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006375 @Override
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006376 public Timer getVideoTurnedOnTimer() {
6377 return mVideoTurnedOnTimer;
6378 }
6379
6380 @Override
6381 public Timer getFlashlightTurnedOnTimer() {
6382 return mFlashlightTurnedOnTimer;
6383 }
6384
6385 @Override
6386 public Timer getCameraTurnedOnTimer() {
6387 return mCameraTurnedOnTimer;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006388 }
6389
Dianne Hackborn617f8772009-03-31 15:04:46 -07006390 @Override
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006391 public Timer getForegroundActivityTimer() {
6392 return mForegroundActivityTimer;
6393 }
6394
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006395 @Override
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006396 public Timer getForegroundServiceTimer() {
6397 return mForegroundServiceTimer;
6398 }
6399
6400 @Override
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006401 public Timer getBluetoothScanTimer() {
Bookatzaa4594a2017-03-24 12:39:56 -07006402 return mBluetoothScanTimer;
Bookatz867c0d72017-03-07 18:23:42 -08006403 }
6404
6405 @Override
6406 public Timer getBluetoothScanBackgroundTimer() {
6407 if (mBluetoothScanTimer == null) {
6408 return null;
6409 }
6410 return mBluetoothScanTimer.getSubTimer();
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006411 }
6412
Bookatz956f36bf2017-04-28 09:48:17 -07006413 @Override
Bookatzb1f04f32017-05-19 13:57:32 -07006414 public Timer getBluetoothUnoptimizedScanTimer() {
6415 return mBluetoothUnoptimizedScanTimer;
6416 }
6417
6418 @Override
6419 public Timer getBluetoothUnoptimizedScanBackgroundTimer() {
6420 if (mBluetoothUnoptimizedScanTimer == null) {
6421 return null;
6422 }
6423 return mBluetoothUnoptimizedScanTimer.getSubTimer();
6424 }
6425
6426 @Override
Bookatz956f36bf2017-04-28 09:48:17 -07006427 public Counter getBluetoothScanResultCounter() {
6428 return mBluetoothScanResultCounter;
6429 }
6430
Bookatzb1f04f32017-05-19 13:57:32 -07006431 @Override
6432 public Counter getBluetoothScanResultBgCounter() {
6433 return mBluetoothScanResultBgCounter;
6434 }
6435
Dianne Hackborn61659e52014-07-09 16:13:01 -07006436 void makeProcessState(int i, Parcel in) {
6437 if (i < 0 || i >= NUM_PROCESS_STATE) return;
6438
6439 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006440 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
6441 mBsi.mOnBatteryTimeBase);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006442 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08006443 mProcessStateTimer[i] = new StopwatchTimer(mBsi.mClocks, this, PROCESS_STATE, null,
6444 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006445 }
6446 }
6447
6448 @Override
6449 public long getProcessStateTime(int state, long elapsedRealtimeUs, int which) {
6450 if (state < 0 || state >= NUM_PROCESS_STATE) return 0;
6451 if (mProcessStateTimer[state] == null) {
6452 return 0;
6453 }
6454 return mProcessStateTimer[state].getTotalTimeLocked(elapsedRealtimeUs, which);
6455 }
6456
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006457 @Override
Joe Onorato713fec82016-03-04 10:34:02 -08006458 public Timer getProcessStateTimer(int state) {
6459 if (state < 0 || state >= NUM_PROCESS_STATE) return null;
6460 return mProcessStateTimer[state];
6461 }
6462
6463 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006464 public Timer getVibratorOnTimer() {
6465 return mVibratorOnTimer;
6466 }
6467
6468 @Override
Dianne Hackborn617f8772009-03-31 15:04:46 -07006469 public void noteUserActivityLocked(int type) {
6470 if (mUserActivityCounters == null) {
6471 initUserActivityLocked();
6472 }
Jeff Browndf693de2012-07-27 12:03:38 -07006473 if (type >= 0 && type < NUM_USER_ACTIVITY_TYPES) {
6474 mUserActivityCounters[type].stepAtomic();
6475 } else {
6476 Slog.w(TAG, "Unknown user activity type " + type + " was specified.",
6477 new Throwable());
6478 }
Dianne Hackborn617f8772009-03-31 15:04:46 -07006479 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006480
Dianne Hackborn617f8772009-03-31 15:04:46 -07006481 @Override
6482 public boolean hasUserActivity() {
6483 return mUserActivityCounters != null;
6484 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006485
Dianne Hackborn617f8772009-03-31 15:04:46 -07006486 @Override
6487 public int getUserActivityCount(int type, int which) {
6488 if (mUserActivityCounters == null) {
6489 return 0;
6490 }
Evan Millarc64edde2009-04-18 12:26:32 -07006491 return mUserActivityCounters[type].getCountLocked(which);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006492 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006493
Robert Greenwalta029ea12013-09-25 16:38:12 -07006494 void makeWifiBatchedScanBin(int i, Parcel in) {
6495 if (i < 0 || i >= NUM_WIFI_BATCHED_SCAN_BINS) return;
6496
Joe Onoratoabded112016-02-08 16:49:39 -08006497 ArrayList<StopwatchTimer> collected = mBsi.mWifiBatchedScanTimers.get(i);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006498 if (collected == null) {
6499 collected = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08006500 mBsi.mWifiBatchedScanTimers.put(i, collected);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006501 }
6502 if (in == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08006503 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
6504 collected, mBsi.mOnBatteryTimeBase);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006505 } else {
Joe Onoratoabded112016-02-08 16:49:39 -08006506 mWifiBatchedScanTimer[i] = new StopwatchTimer(mBsi.mClocks, this, WIFI_BATCHED_SCAN,
6507 collected, mBsi.mOnBatteryTimeBase, in);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006508 }
6509 }
6510
6511
Dianne Hackborn617f8772009-03-31 15:04:46 -07006512 void initUserActivityLocked() {
6513 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
6514 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08006515 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07006516 }
6517 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006518
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006519 void noteNetworkActivityLocked(int type, long deltaBytes, long deltaPackets) {
6520 if (mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006521 initNetworkActivityLocked();
6522 }
6523 if (type >= 0 && type < NUM_NETWORK_ACTIVITY_TYPES) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006524 mNetworkByteActivityCounters[type].addCountLocked(deltaBytes);
6525 mNetworkPacketActivityCounters[type].addCountLocked(deltaPackets);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006526 } else {
6527 Slog.w(TAG, "Unknown network activity type " + type + " was specified.",
6528 new Throwable());
6529 }
6530 }
6531
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006532 void noteMobileRadioActiveTimeLocked(long batteryUptime) {
6533 if (mNetworkByteActivityCounters == null) {
6534 initNetworkActivityLocked();
6535 }
6536 mMobileRadioActiveTime.addCountLocked(batteryUptime);
6537 mMobileRadioActiveCount.addCountLocked(1);
6538 }
6539
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006540 @Override
6541 public boolean hasNetworkActivity() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006542 return mNetworkByteActivityCounters != null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006543 }
6544
6545 @Override
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006546 public long getNetworkActivityBytes(int type, int which) {
6547 if (mNetworkByteActivityCounters != null && type >= 0
6548 && type < mNetworkByteActivityCounters.length) {
6549 return mNetworkByteActivityCounters[type].getCountLocked(which);
6550 } else {
6551 return 0;
6552 }
6553 }
6554
6555 @Override
6556 public long getNetworkActivityPackets(int type, int which) {
6557 if (mNetworkPacketActivityCounters != null && type >= 0
6558 && type < mNetworkPacketActivityCounters.length) {
6559 return mNetworkPacketActivityCounters[type].getCountLocked(which);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006560 } else {
6561 return 0;
6562 }
6563 }
6564
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006565 @Override
6566 public long getMobileRadioActiveTime(int which) {
6567 return mMobileRadioActiveTime != null
6568 ? mMobileRadioActiveTime.getCountLocked(which) : 0;
6569 }
6570
6571 @Override
6572 public int getMobileRadioActiveCount(int which) {
6573 return mMobileRadioActiveCount != null
6574 ? (int)mMobileRadioActiveCount.getCountLocked(which) : 0;
6575 }
6576
Adam Lesinskie08af192015-03-25 16:42:59 -07006577 @Override
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006578 public long getUserCpuTimeUs(int which) {
6579 return mUserCpuTime.getCountLocked(which);
6580 }
6581
6582 @Override
6583 public long getSystemCpuTimeUs(int which) {
6584 return mSystemCpuTime.getCountLocked(which);
6585 }
6586
6587 @Override
Adam Lesinski6832f392015-09-05 18:05:40 -07006588 public long getTimeAtCpuSpeed(int cluster, int step, int which) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07006589 if (mCpuClusterSpeedTimesUs != null) {
6590 if (cluster >= 0 && cluster < mCpuClusterSpeedTimesUs.length) {
6591 final LongSamplingCounter[] cpuSpeedTimesUs = mCpuClusterSpeedTimesUs[cluster];
6592 if (cpuSpeedTimesUs != null) {
6593 if (step >= 0 && step < cpuSpeedTimesUs.length) {
6594 final LongSamplingCounter c = cpuSpeedTimesUs[step];
Adam Lesinski6832f392015-09-05 18:05:40 -07006595 if (c != null) {
6596 return c.getCountLocked(which);
6597 }
6598 }
6599 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006600 }
6601 }
6602 return 0;
6603 }
6604
Adam Lesinski5f056f62016-07-14 16:56:08 -07006605 public void noteMobileRadioApWakeupLocked() {
6606 if (mMobileRadioApWakeupCount == null) {
6607 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6608 }
6609 mMobileRadioApWakeupCount.addCountLocked(1);
6610 }
6611
6612 @Override
6613 public long getMobileRadioApWakeupCount(int which) {
6614 if (mMobileRadioApWakeupCount != null) {
6615 return mMobileRadioApWakeupCount.getCountLocked(which);
6616 }
6617 return 0;
6618 }
6619
6620 public void noteWifiRadioApWakeupLocked() {
6621 if (mWifiRadioApWakeupCount == null) {
6622 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6623 }
6624 mWifiRadioApWakeupCount.addCountLocked(1);
6625 }
6626
6627 @Override
6628 public long getWifiRadioApWakeupCount(int which) {
6629 if (mWifiRadioApWakeupCount != null) {
6630 return mWifiRadioApWakeupCount.getCountLocked(which);
6631 }
6632 return 0;
6633 }
6634
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006635 void initNetworkActivityLocked() {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006636 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
6637 mNetworkPacketActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006638 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08006639 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6640 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006641 }
Joe Onoratoabded112016-02-08 16:49:39 -08006642 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
6643 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 }
Amith Yamasani244fa5c2009-05-22 14:36:07 -07006645
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006646 /**
6647 * Clear all stats for this uid. Returns true if the uid is completely
6648 * inactive so can be dropped.
6649 */
Adam Lesinski5f212c82017-03-13 12:25:13 -07006650 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
Bookatz993a0be2017-07-21 09:03:23 -07006651 public boolean reset(long uptime, long realtime) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006652 boolean active = false;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006653
Bookatz993a0be2017-07-21 09:03:23 -07006654 mOnBatteryBackgroundTimeBase.init(uptime, realtime);
6655 mOnBatteryScreenOffBackgroundTimeBase.init(uptime, realtime);
6656
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006657 if (mWifiRunningTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006658 active |= !mWifiRunningTimer.reset(false);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006659 active |= mWifiRunning;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006660 }
6661 if (mFullWifiLockTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006662 active |= !mFullWifiLockTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006663 active |= mFullWifiLockOut;
6664 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006665 if (mWifiScanTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006666 active |= !mWifiScanTimer.reset(false);
Nick Pelly6ccaa542012-06-15 15:22:47 -07006667 active |= mWifiScanStarted;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006668 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006669 if (mWifiBatchedScanTimer != null) {
6670 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
6671 if (mWifiBatchedScanTimer[i] != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006672 active |= !mWifiBatchedScanTimer[i].reset(false);
Robert Greenwalta029ea12013-09-25 16:38:12 -07006673 }
6674 }
6675 active |= (mWifiBatchedScanBinStarted != NO_BATCHED_SCAN_STARTED);
6676 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006677 if (mWifiMulticastTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006678 active |= !mWifiMulticastTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006679 active |= mWifiMulticastEnabled;
6680 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006681
6682 active |= !resetTimerIfNotNull(mAudioTurnedOnTimer, false);
6683 active |= !resetTimerIfNotNull(mVideoTurnedOnTimer, false);
6684 active |= !resetTimerIfNotNull(mFlashlightTurnedOnTimer, false);
6685 active |= !resetTimerIfNotNull(mCameraTurnedOnTimer, false);
6686 active |= !resetTimerIfNotNull(mForegroundActivityTimer, false);
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006687 active |= !resetTimerIfNotNull(mForegroundServiceTimer, false);
Bookatzc8c44962017-05-11 12:12:54 -07006688 active |= !resetTimerIfNotNull(mAggregatedPartialWakelockTimer, false);
Adam Lesinski5f056f62016-07-14 16:56:08 -07006689 active |= !resetTimerIfNotNull(mBluetoothScanTimer, false);
Bookatzb1f04f32017-05-19 13:57:32 -07006690 active |= !resetTimerIfNotNull(mBluetoothUnoptimizedScanTimer, false);
Bookatz956f36bf2017-04-28 09:48:17 -07006691 if (mBluetoothScanResultCounter != null) {
6692 mBluetoothScanResultCounter.reset(false);
6693 }
Bookatzb1f04f32017-05-19 13:57:32 -07006694 if (mBluetoothScanResultBgCounter != null) {
6695 mBluetoothScanResultBgCounter.reset(false);
6696 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006697
Dianne Hackborn61659e52014-07-09 16:13:01 -07006698 if (mProcessStateTimer != null) {
6699 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
6700 if (mProcessStateTimer[i] != null) {
6701 active |= !mProcessStateTimer[i].reset(false);
6702 }
6703 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08006704 active |= (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006705 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006706 if (mVibratorOnTimer != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006707 if (mVibratorOnTimer.reset(false)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006708 mVibratorOnTimer.detach();
6709 mVibratorOnTimer = null;
6710 } else {
6711 active = true;
6712 }
6713 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006714
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006715 if (mUserActivityCounters != null) {
6716 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
6717 mUserActivityCounters[i].reset(false);
6718 }
6719 }
6720
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006721 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006722 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006723 mNetworkByteActivityCounters[i].reset(false);
6724 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006725 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08006726 mMobileRadioActiveTime.reset(false);
6727 mMobileRadioActiveCount.reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006728 }
6729
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006730 if (mWifiControllerActivity != null) {
6731 mWifiControllerActivity.reset(false);
6732 }
Adam Lesinskie08af192015-03-25 16:42:59 -07006733
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07006734 if (mBluetoothControllerActivity != null) {
6735 mBluetoothControllerActivity.reset(false);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006736 }
6737
Adam Lesinski1a2b39e2016-04-29 17:56:58 -07006738 if (mModemControllerActivity != null) {
6739 mModemControllerActivity.reset(false);
Adam Lesinskie08af192015-03-25 16:42:59 -07006740 }
6741
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006742 mUserCpuTime.reset(false);
6743 mSystemCpuTime.reset(false);
Adam Lesinski6832f392015-09-05 18:05:40 -07006744
Sudheer Shankaaf857412017-07-21 00:14:24 -07006745 if (mCpuClusterSpeedTimesUs != null) {
6746 for (LongSamplingCounter[] speeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07006747 if (speeds != null) {
6748 for (LongSamplingCounter speed : speeds) {
6749 if (speed != null) {
6750 speed.reset(false);
6751 }
6752 }
6753 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006754 }
6755 }
6756
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006757 if (mCpuFreqTimeMs != null) {
6758 mCpuFreqTimeMs.reset(false);
6759 }
6760 if (mScreenOffCpuFreqTimeMs != null) {
6761 mScreenOffCpuFreqTimeMs.reset(false);
6762 }
6763
Adam Lesinski5f056f62016-07-14 16:56:08 -07006764 resetLongCounterIfNotNull(mMobileRadioApWakeupCount, false);
6765 resetLongCounterIfNotNull(mWifiRadioApWakeupCount, false);
6766
Dianne Hackbornd953c532014-08-16 18:17:38 -07006767 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
6768 for (int iw=wakeStats.size()-1; iw>=0; iw--) {
6769 Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006770 if (wl.reset()) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006771 wakeStats.removeAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -07006772 } else {
6773 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006774 }
6775 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07006776 mWakelockStats.cleanup();
Bookatz2bffb5b2017-04-13 11:59:33 -07006777 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07006778 for (int is=syncStats.size()-1; is>=0; is--) {
Bookatz2bffb5b2017-04-13 11:59:33 -07006779 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006780 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006781 syncStats.removeAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006782 timer.detach();
6783 } else {
6784 active = true;
6785 }
6786 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07006787 mSyncStats.cleanup();
Bookatzaa4594a2017-03-24 12:39:56 -07006788 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07006789 for (int ij=jobStats.size()-1; ij>=0; ij--) {
Bookatzaa4594a2017-03-24 12:39:56 -07006790 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006791 if (timer.reset(false)) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006792 jobStats.removeAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006793 timer.detach();
6794 } else {
6795 active = true;
6796 }
6797 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07006798 mJobStats.cleanup();
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006799 mJobCompletions.clear();
Dianne Hackborn61659e52014-07-09 16:13:01 -07006800 for (int ise=mSensorStats.size()-1; ise>=0; ise--) {
6801 Sensor s = mSensorStats.valueAt(ise);
6802 if (s.reset()) {
6803 mSensorStats.removeAt(ise);
6804 } else {
6805 active = true;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006806 }
6807 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07006808 for (int ip=mProcessStats.size()-1; ip>=0; ip--) {
6809 Proc proc = mProcessStats.valueAt(ip);
Dianne Hackborna8d10942015-11-19 17:55:19 -08006810 proc.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006811 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08006812 mProcessStats.clear();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006813 if (mPids.size() > 0) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006814 for (int i=mPids.size()-1; i>=0; i--) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006815 Pid pid = mPids.valueAt(i);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006816 if (pid.mWakeNesting > 0) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006817 active = true;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006818 } else {
6819 mPids.removeAt(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006820 }
6821 }
6822 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006823 if (mPackageStats.size() > 0) {
6824 Iterator<Map.Entry<String, Pkg>> it = mPackageStats.entrySet().iterator();
6825 while (it.hasNext()) {
6826 Map.Entry<String, Pkg> pkgEntry = it.next();
6827 Pkg p = pkgEntry.getValue();
6828 p.detach();
6829 if (p.mServiceStats.size() > 0) {
6830 Iterator<Map.Entry<String, Pkg.Serv>> it2
6831 = p.mServiceStats.entrySet().iterator();
6832 while (it2.hasNext()) {
6833 Map.Entry<String, Pkg.Serv> servEntry = it2.next();
6834 servEntry.getValue().detach();
6835 }
6836 }
6837 }
6838 mPackageStats.clear();
6839 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006840
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08006841 mLastStepUserTime = mLastStepSystemTime = 0;
6842 mCurStepUserTime = mCurStepSystemTime = 0;
6843
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006844 if (!active) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07006845 if (mWifiRunningTimer != null) {
6846 mWifiRunningTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006847 }
6848 if (mFullWifiLockTimer != null) {
6849 mFullWifiLockTimer.detach();
6850 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07006851 if (mWifiScanTimer != null) {
6852 mWifiScanTimer.detach();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006853 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07006854 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
6855 if (mWifiBatchedScanTimer[i] != null) {
6856 mWifiBatchedScanTimer[i].detach();
6857 }
6858 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006859 if (mWifiMulticastTimer != null) {
6860 mWifiMulticastTimer.detach();
6861 }
6862 if (mAudioTurnedOnTimer != null) {
6863 mAudioTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006864 mAudioTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006865 }
6866 if (mVideoTurnedOnTimer != null) {
6867 mVideoTurnedOnTimer.detach();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08006868 mVideoTurnedOnTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006869 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07006870 if (mFlashlightTurnedOnTimer != null) {
6871 mFlashlightTurnedOnTimer.detach();
6872 mFlashlightTurnedOnTimer = null;
6873 }
6874 if (mCameraTurnedOnTimer != null) {
6875 mCameraTurnedOnTimer.detach();
6876 mCameraTurnedOnTimer = null;
6877 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07006878 if (mForegroundActivityTimer != null) {
6879 mForegroundActivityTimer.detach();
6880 mForegroundActivityTimer = null;
6881 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07006882 if (mForegroundServiceTimer != null) {
6883 mForegroundServiceTimer.detach();
6884 mForegroundServiceTimer = null;
6885 }
Bookatzc8c44962017-05-11 12:12:54 -07006886 if (mAggregatedPartialWakelockTimer != null) {
6887 mAggregatedPartialWakelockTimer.detach();
6888 mAggregatedPartialWakelockTimer = null;
6889 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08006890 if (mBluetoothScanTimer != null) {
6891 mBluetoothScanTimer.detach();
6892 mBluetoothScanTimer = null;
6893 }
Bookatzb1f04f32017-05-19 13:57:32 -07006894 if (mBluetoothUnoptimizedScanTimer != null) {
6895 mBluetoothUnoptimizedScanTimer.detach();
6896 mBluetoothUnoptimizedScanTimer = null;
6897 }
Bookatz956f36bf2017-04-28 09:48:17 -07006898 if (mBluetoothScanResultCounter != null) {
6899 mBluetoothScanResultCounter.detach();
6900 mBluetoothScanResultCounter = null;
6901 }
Bookatzb1f04f32017-05-19 13:57:32 -07006902 if (mBluetoothScanResultBgCounter != null) {
6903 mBluetoothScanResultBgCounter.detach();
6904 mBluetoothScanResultBgCounter = null;
6905 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006906 if (mUserActivityCounters != null) {
6907 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
6908 mUserActivityCounters[i].detach();
6909 }
6910 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006911 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006912 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08006913 mNetworkByteActivityCounters[i].detach();
6914 mNetworkPacketActivityCounters[i].detach();
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07006915 }
6916 }
Adam Lesinskie08af192015-03-25 16:42:59 -07006917
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006918 if (mWifiControllerActivity != null) {
6919 mWifiControllerActivity.detach();
Adam Lesinskie08af192015-03-25 16:42:59 -07006920 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08006921
6922 if (mBluetoothControllerActivity != null) {
6923 mBluetoothControllerActivity.detach();
6924 }
6925
6926 if (mModemControllerActivity != null) {
6927 mModemControllerActivity.detach();
6928 }
6929
Dianne Hackborne5167ca2014-03-08 14:39:10 -08006930 mPids.clear();
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006931
6932 mUserCpuTime.detach();
6933 mSystemCpuTime.detach();
Adam Lesinski6832f392015-09-05 18:05:40 -07006934
Sudheer Shankaaf857412017-07-21 00:14:24 -07006935 if (mCpuClusterSpeedTimesUs != null) {
6936 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07006937 if (cpuSpeeds != null) {
6938 for (LongSamplingCounter c : cpuSpeeds) {
6939 if (c != null) {
6940 c.detach();
6941 }
6942 }
6943 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07006944 }
6945 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07006946
Sudheer Shanka9b735c52017-05-09 18:26:18 -07006947 if (mCpuFreqTimeMs != null) {
6948 mCpuFreqTimeMs.detach();
6949 }
6950 if (mScreenOffCpuFreqTimeMs != null) {
6951 mScreenOffCpuFreqTimeMs.detach();
6952 }
6953
Adam Lesinski5f056f62016-07-14 16:56:08 -07006954 detachLongCounterIfNotNull(mMobileRadioApWakeupCount);
6955 detachLongCounterIfNotNull(mWifiRadioApWakeupCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006956 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006957
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07006958 return !active;
6959 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07006960
Dianne Hackborn94326cb2017-06-28 16:17:20 -07006961 void writeJobCompletionsToParcelLocked(Parcel out) {
6962 int NJC = mJobCompletions.size();
6963 out.writeInt(NJC);
6964 for (int ijc=0; ijc<NJC; ijc++) {
6965 out.writeString(mJobCompletions.keyAt(ijc));
6966 SparseIntArray types = mJobCompletions.valueAt(ijc);
6967 int NT = types.size();
6968 out.writeInt(NT);
6969 for (int it=0; it<NT; it++) {
6970 out.writeInt(types.keyAt(it));
6971 out.writeInt(types.valueAt(it));
6972 }
6973 }
6974 }
6975
Bookatz867c0d72017-03-07 18:23:42 -08006976 void writeToParcelLocked(Parcel out, long uptimeUs, long elapsedRealtimeUs) {
6977 mOnBatteryBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatzc8c44962017-05-11 12:12:54 -07006978 mOnBatteryScreenOffBackgroundTimeBase.writeToParcel(out, uptimeUs, elapsedRealtimeUs);
Bookatz867c0d72017-03-07 18:23:42 -08006979
Dianne Hackbornd953c532014-08-16 18:17:38 -07006980 final ArrayMap<String, Wakelock> wakeStats = mWakelockStats.getMap();
6981 int NW = wakeStats.size();
Dianne Hackborn61659e52014-07-09 16:13:01 -07006982 out.writeInt(NW);
6983 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006984 out.writeString(wakeStats.keyAt(iw));
6985 Uid.Wakelock wakelock = wakeStats.valueAt(iw);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08006986 wakelock.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006987 }
6988
Bookatz2bffb5b2017-04-13 11:59:33 -07006989 final ArrayMap<String, DualTimer> syncStats = mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07006990 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006991 out.writeInt(NS);
6992 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07006993 out.writeString(syncStats.keyAt(is));
Bookatz2bffb5b2017-04-13 11:59:33 -07006994 DualTimer timer = syncStats.valueAt(is);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07006995 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
6996 }
6997
Bookatzaa4594a2017-03-24 12:39:56 -07006998 final ArrayMap<String, DualTimer> jobStats = mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -07006999 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007000 out.writeInt(NJ);
7001 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07007002 out.writeString(jobStats.keyAt(ij));
Bookatzaa4594a2017-03-24 12:39:56 -07007003 DualTimer timer = jobStats.valueAt(ij);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007004 Timer.writeTimerToParcel(out, timer, elapsedRealtimeUs);
7005 }
7006
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007007 writeJobCompletionsToParcelLocked(out);
7008
Dianne Hackborn61659e52014-07-09 16:13:01 -07007009 int NSE = mSensorStats.size();
7010 out.writeInt(NSE);
7011 for (int ise=0; ise<NSE; ise++) {
7012 out.writeInt(mSensorStats.keyAt(ise));
7013 Uid.Sensor sensor = mSensorStats.valueAt(ise);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007014 sensor.writeToParcelLocked(out, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 }
7016
Dianne Hackborn61659e52014-07-09 16:13:01 -07007017 int NP = mProcessStats.size();
7018 out.writeInt(NP);
7019 for (int ip=0; ip<NP; ip++) {
7020 out.writeString(mProcessStats.keyAt(ip));
7021 Uid.Proc proc = mProcessStats.valueAt(ip);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 proc.writeToParcelLocked(out);
7023 }
7024
7025 out.writeInt(mPackageStats.size());
7026 for (Map.Entry<String, Uid.Pkg> pkgEntry : mPackageStats.entrySet()) {
7027 out.writeString(pkgEntry.getKey());
7028 Uid.Pkg pkg = pkgEntry.getValue();
7029 pkg.writeToParcelLocked(out);
7030 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007031
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007032 if (mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007033 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007034 mWifiRunningTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007035 } else {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007036 out.writeInt(0);
7037 }
7038 if (mFullWifiLockTimer != null) {
7039 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007040 mFullWifiLockTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007041 } else {
7042 out.writeInt(0);
7043 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007044 if (mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007045 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007046 mWifiScanTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007047 } else {
7048 out.writeInt(0);
7049 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007050 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7051 if (mWifiBatchedScanTimer[i] != null) {
7052 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007053 mWifiBatchedScanTimer[i].writeToParcel(out, elapsedRealtimeUs);
Robert Greenwalta029ea12013-09-25 16:38:12 -07007054 } else {
7055 out.writeInt(0);
7056 }
7057 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007058 if (mWifiMulticastTimer != null) {
7059 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007060 mWifiMulticastTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007061 } else {
7062 out.writeInt(0);
7063 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007064
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007065 if (mAudioTurnedOnTimer != null) {
7066 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007067 mAudioTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007068 } else {
7069 out.writeInt(0);
7070 }
7071 if (mVideoTurnedOnTimer != null) {
7072 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007073 mVideoTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007074 } else {
7075 out.writeInt(0);
7076 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007077 if (mFlashlightTurnedOnTimer != null) {
7078 out.writeInt(1);
7079 mFlashlightTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
7080 } else {
7081 out.writeInt(0);
7082 }
7083 if (mCameraTurnedOnTimer != null) {
7084 out.writeInt(1);
7085 mCameraTurnedOnTimer.writeToParcel(out, elapsedRealtimeUs);
7086 } else {
7087 out.writeInt(0);
7088 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007089 if (mForegroundActivityTimer != null) {
7090 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007091 mForegroundActivityTimer.writeToParcel(out, elapsedRealtimeUs);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007092 } else {
7093 out.writeInt(0);
7094 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007095 if (mForegroundServiceTimer != null) {
7096 out.writeInt(1);
7097 mForegroundServiceTimer.writeToParcel(out, elapsedRealtimeUs);
7098 } else {
7099 out.writeInt(0);
7100 }
Bookatzc8c44962017-05-11 12:12:54 -07007101 if (mAggregatedPartialWakelockTimer != null) {
7102 out.writeInt(1);
7103 mAggregatedPartialWakelockTimer.writeToParcel(out, elapsedRealtimeUs);
7104 } else {
7105 out.writeInt(0);
7106 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007107 if (mBluetoothScanTimer != null) {
7108 out.writeInt(1);
7109 mBluetoothScanTimer.writeToParcel(out, elapsedRealtimeUs);
7110 } else {
7111 out.writeInt(0);
7112 }
Bookatzb1f04f32017-05-19 13:57:32 -07007113 if (mBluetoothUnoptimizedScanTimer != null) {
7114 out.writeInt(1);
7115 mBluetoothUnoptimizedScanTimer.writeToParcel(out, elapsedRealtimeUs);
7116 } else {
7117 out.writeInt(0);
7118 }
Bookatz956f36bf2017-04-28 09:48:17 -07007119 if (mBluetoothScanResultCounter != null) {
7120 out.writeInt(1);
7121 mBluetoothScanResultCounter.writeToParcel(out);
7122 } else {
7123 out.writeInt(0);
7124 }
Bookatzb1f04f32017-05-19 13:57:32 -07007125 if (mBluetoothScanResultBgCounter != null) {
7126 out.writeInt(1);
7127 mBluetoothScanResultBgCounter.writeToParcel(out);
7128 } else {
7129 out.writeInt(0);
7130 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07007131 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7132 if (mProcessStateTimer[i] != null) {
7133 out.writeInt(1);
7134 mProcessStateTimer[i].writeToParcel(out, elapsedRealtimeUs);
7135 } else {
7136 out.writeInt(0);
7137 }
7138 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007139 if (mVibratorOnTimer != null) {
7140 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007141 mVibratorOnTimer.writeToParcel(out, elapsedRealtimeUs);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007142 } else {
7143 out.writeInt(0);
7144 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007145 if (mUserActivityCounters != null) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07007146 out.writeInt(1);
7147 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
7148 mUserActivityCounters[i].writeToParcel(out);
7149 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007150 } else {
7151 out.writeInt(0);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007152 }
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007153 if (mNetworkByteActivityCounters != null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007154 out.writeInt(1);
7155 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007156 mNetworkByteActivityCounters[i].writeToParcel(out);
7157 mNetworkPacketActivityCounters[i].writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007158 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -08007159 mMobileRadioActiveTime.writeToParcel(out);
7160 mMobileRadioActiveCount.writeToParcel(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007161 } else {
7162 out.writeInt(0);
7163 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007164
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007165 if (mWifiControllerActivity != null) {
7166 out.writeInt(1);
7167 mWifiControllerActivity.writeToParcel(out, 0);
7168 } else {
7169 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07007170 }
7171
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007172 if (mBluetoothControllerActivity != null) {
7173 out.writeInt(1);
7174 mBluetoothControllerActivity.writeToParcel(out, 0);
7175 } else {
7176 out.writeInt(0);
7177 }
7178
7179 if (mModemControllerActivity != null) {
7180 out.writeInt(1);
7181 mModemControllerActivity.writeToParcel(out, 0);
7182 } else {
7183 out.writeInt(0);
Adam Lesinskie08af192015-03-25 16:42:59 -07007184 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007185
7186 mUserCpuTime.writeToParcel(out);
7187 mSystemCpuTime.writeToParcel(out);
7188
Sudheer Shankaaf857412017-07-21 00:14:24 -07007189 if (mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007190 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -07007191 out.writeInt(mCpuClusterSpeedTimesUs.length);
7192 for (LongSamplingCounter[] cpuSpeeds : mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007193 if (cpuSpeeds != null) {
7194 out.writeInt(1);
7195 out.writeInt(cpuSpeeds.length);
7196 for (LongSamplingCounter c : cpuSpeeds) {
7197 if (c != null) {
7198 out.writeInt(1);
7199 c.writeToParcel(out);
7200 } else {
7201 out.writeInt(0);
7202 }
7203 }
7204 } else {
7205 out.writeInt(0);
7206 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007207 }
Adam Lesinski6832f392015-09-05 18:05:40 -07007208 } else {
7209 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007210 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007211
Sudheer Shanka59f5c002017-05-15 10:57:15 -07007212 LongSamplingCounterArray.writeToParcel(out, mCpuFreqTimeMs);
7213 LongSamplingCounterArray.writeToParcel(out, mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007214
Adam Lesinski5f056f62016-07-14 16:56:08 -07007215 if (mMobileRadioApWakeupCount != null) {
7216 out.writeInt(1);
7217 mMobileRadioApWakeupCount.writeToParcel(out);
7218 } else {
7219 out.writeInt(0);
7220 }
7221
7222 if (mWifiRadioApWakeupCount != null) {
7223 out.writeInt(1);
7224 mWifiRadioApWakeupCount.writeToParcel(out);
7225 } else {
7226 out.writeInt(0);
7227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007228 }
7229
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007230 void readJobCompletionsFromParcelLocked(Parcel in) {
7231 int numJobCompletions = in.readInt();
7232 mJobCompletions.clear();
7233 for (int j = 0; j < numJobCompletions; j++) {
7234 String jobName = in.readString();
7235 int numTypes = in.readInt();
7236 if (numTypes > 0) {
7237 SparseIntArray types = new SparseIntArray();
7238 for (int k = 0; k < numTypes; k++) {
7239 int type = in.readInt();
7240 int count = in.readInt();
7241 types.put(type, count);
7242 }
7243 mJobCompletions.put(jobName, types);
7244 }
7245 }
7246 }
7247
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007248 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase, Parcel in) {
Bookatz867c0d72017-03-07 18:23:42 -08007249 mOnBatteryBackgroundTimeBase.readFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -07007250 mOnBatteryScreenOffBackgroundTimeBase.readFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -08007251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007252 int numWakelocks = in.readInt();
7253 mWakelockStats.clear();
7254 for (int j = 0; j < numWakelocks; j++) {
7255 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08007256 Uid.Wakelock wakelock = new Wakelock(mBsi, this);
Bookatz5b5ec322017-05-26 09:40:38 -07007257 wakelock.readFromParcelLocked(
7258 timeBase, screenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase, in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07007259 mWakelockStats.add(wakelockName, wakelock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007260 }
7261
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007262 int numSyncs = in.readInt();
7263 mSyncStats.clear();
7264 for (int j = 0; j < numSyncs; j++) {
7265 String syncName = in.readString();
7266 if (in.readInt() != 0) {
Bookatz2bffb5b2017-04-13 11:59:33 -07007267 mSyncStats.add(syncName, new DualTimer(mBsi.mClocks, Uid.this, SYNC, null,
7268 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007269 }
7270 }
7271
7272 int numJobs = in.readInt();
7273 mJobStats.clear();
7274 for (int j = 0; j < numJobs; j++) {
7275 String jobName = in.readString();
7276 if (in.readInt() != 0) {
Bookatzaa4594a2017-03-24 12:39:56 -07007277 mJobStats.add(jobName, new DualTimer(mBsi.mClocks, Uid.this, JOB, null,
7278 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in));
Dianne Hackbornfdb19562014-07-11 16:03:36 -07007279 }
7280 }
7281
Dianne Hackborn94326cb2017-06-28 16:17:20 -07007282 readJobCompletionsFromParcelLocked(in);
7283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 int numSensors = in.readInt();
7285 mSensorStats.clear();
7286 for (int k = 0; k < numSensors; k++) {
7287 int sensorNumber = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08007288 Uid.Sensor sensor = new Sensor(mBsi, this, sensorNumber);
Bookatz867c0d72017-03-07 18:23:42 -08007289 sensor.readFromParcelLocked(mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
7290 in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007291 mSensorStats.put(sensorNumber, sensor);
7292 }
7293
7294 int numProcs = in.readInt();
7295 mProcessStats.clear();
7296 for (int k = 0; k < numProcs; k++) {
7297 String processName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08007298 Uid.Proc proc = new Proc(mBsi, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007299 proc.readFromParcelLocked(in);
7300 mProcessStats.put(processName, proc);
7301 }
7302
7303 int numPkgs = in.readInt();
7304 mPackageStats.clear();
7305 for (int l = 0; l < numPkgs; l++) {
7306 String packageName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08007307 Uid.Pkg pkg = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007308 pkg.readFromParcelLocked(in);
7309 mPackageStats.put(packageName, pkg);
7310 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007311
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007312 mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007313 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007314 mWifiRunningTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_RUNNING,
7315 mBsi.mWifiRunningTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007316 } else {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -07007317 mWifiRunningTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007318 }
7319 mFullWifiLockOut = false;
7320 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007321 mFullWifiLockTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, FULL_WIFI_LOCK,
7322 mBsi.mFullWifiLockTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007323 } else {
7324 mFullWifiLockTimer = null;
7325 }
Nick Pelly6ccaa542012-06-15 15:22:47 -07007326 mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007327 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08007328 mWifiScanTimer = new DualTimer(mBsi.mClocks, Uid.this, WIFI_SCAN,
7329 mBsi.mWifiScanTimers, mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase,
7330 in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007331 } else {
Nick Pelly6ccaa542012-06-15 15:22:47 -07007332 mWifiScanTimer = null;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007333 }
Robert Greenwalta029ea12013-09-25 16:38:12 -07007334 mWifiBatchedScanBinStarted = NO_BATCHED_SCAN_STARTED;
7335 for (int i = 0; i < NUM_WIFI_BATCHED_SCAN_BINS; i++) {
7336 if (in.readInt() != 0) {
7337 makeWifiBatchedScanBin(i, in);
7338 } else {
7339 mWifiBatchedScanTimer[i] = null;
7340 }
7341 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007342 mWifiMulticastEnabled = false;
7343 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007344 mWifiMulticastTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, WIFI_MULTICAST_ENABLED,
7345 mBsi.mWifiMulticastTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007346 } else {
7347 mWifiMulticastTimer = null;
7348 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007349 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007350 mAudioTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, AUDIO_TURNED_ON,
7351 mBsi.mAudioTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007352 } else {
7353 mAudioTurnedOnTimer = null;
7354 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007355 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007356 mVideoTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, VIDEO_TURNED_ON,
7357 mBsi.mVideoTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007358 } else {
7359 mVideoTurnedOnTimer = null;
7360 }
7361 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007362 mFlashlightTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7363 FLASHLIGHT_TURNED_ON, mBsi.mFlashlightTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007364 } else {
7365 mFlashlightTurnedOnTimer = null;
7366 }
7367 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007368 mCameraTurnedOnTimer = new StopwatchTimer(mBsi.mClocks, Uid.this, CAMERA_TURNED_ON,
7369 mBsi.mCameraTurnedOnTimers, mBsi.mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07007370 } else {
7371 mCameraTurnedOnTimer = null;
7372 }
7373 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007374 mForegroundActivityTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7375 FOREGROUND_ACTIVITY, null, mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007376 } else {
7377 mForegroundActivityTimer = null;
7378 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007379 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07007380 mForegroundServiceTimer = new StopwatchTimer(mBsi.mClocks, Uid.this,
7381 FOREGROUND_SERVICE, null, mBsi.mOnBatteryTimeBase, in);
7382 } else {
7383 mForegroundServiceTimer = null;
7384 }
7385 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -07007386 mAggregatedPartialWakelockTimer = new DualTimer(mBsi.mClocks, this,
7387 AGGREGATED_WAKE_TYPE_PARTIAL, null,
7388 mBsi.mOnBatteryScreenOffTimeBase, mOnBatteryScreenOffBackgroundTimeBase,
7389 in);
7390 } else {
7391 mAggregatedPartialWakelockTimer = null;
7392 }
7393 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -08007394 mBluetoothScanTimer = new DualTimer(mBsi.mClocks, Uid.this, BLUETOOTH_SCAN_ON,
7395 mBsi.mBluetoothScanOnTimers, mBsi.mOnBatteryTimeBase,
7396 mOnBatteryBackgroundTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08007397 } else {
7398 mBluetoothScanTimer = null;
7399 }
Bookatz956f36bf2017-04-28 09:48:17 -07007400 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -07007401 mBluetoothUnoptimizedScanTimer = new DualTimer(mBsi.mClocks, Uid.this,
7402 BLUETOOTH_UNOPTIMIZED_SCAN_ON, null,
7403 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase, in);
7404 } else {
7405 mBluetoothUnoptimizedScanTimer = null;
7406 }
7407 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -07007408 mBluetoothScanResultCounter = new Counter(mBsi.mOnBatteryTimeBase, in);
7409 } else {
7410 mBluetoothScanResultCounter = null;
7411 }
Bookatzb1f04f32017-05-19 13:57:32 -07007412 if (in.readInt() != 0) {
7413 mBluetoothScanResultBgCounter = new Counter(mOnBatteryBackgroundTimeBase, in);
7414 } else {
7415 mBluetoothScanResultBgCounter = null;
7416 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08007417 mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -07007418 for (int i = 0; i < NUM_PROCESS_STATE; i++) {
7419 if (in.readInt() != 0) {
7420 makeProcessState(i, in);
7421 } else {
7422 mProcessStateTimer[i] = null;
7423 }
7424 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007425 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007426 mVibratorOnTimer = new BatchTimer(mBsi.mClocks, Uid.this, VIBRATOR_ON,
7427 mBsi.mOnBatteryTimeBase, in);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007428 } else {
7429 mVibratorOnTimer = null;
7430 }
7431 if (in.readInt() != 0) {
Dianne Hackborn617f8772009-03-31 15:04:46 -07007432 mUserActivityCounters = new Counter[NUM_USER_ACTIVITY_TYPES];
7433 for (int i=0; i<NUM_USER_ACTIVITY_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08007434 mUserActivityCounters[i] = new Counter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn617f8772009-03-31 15:04:46 -07007435 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007436 } else {
7437 mUserActivityCounters = null;
Dianne Hackborn617f8772009-03-31 15:04:46 -07007438 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007439 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007440 mNetworkByteActivityCounters = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
7441 mNetworkPacketActivityCounters
7442 = new LongSamplingCounter[NUM_NETWORK_ACTIVITY_TYPES];
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007443 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007444 mNetworkByteActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08007445 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007446 mNetworkPacketActivityCounters[i]
Joe Onoratoabded112016-02-08 16:49:39 -08007447 = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007448 }
Joe Onoratoabded112016-02-08 16:49:39 -08007449 mMobileRadioActiveTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
7450 mMobileRadioActiveCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007451 } else {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08007452 mNetworkByteActivityCounters = null;
7453 mNetworkPacketActivityCounters = null;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07007454 }
Adam Lesinskie08af192015-03-25 16:42:59 -07007455
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007456 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007457 mWifiControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007458 NUM_WIFI_TX_LEVELS, in);
7459 } else {
7460 mWifiControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07007461 }
7462
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007463 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007464 mBluetoothControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007465 NUM_BT_TX_LEVELS, in);
7466 } else {
7467 mBluetoothControllerActivity = null;
7468 }
7469
7470 if (in.readInt() != 0) {
Joe Onoratoabded112016-02-08 16:49:39 -08007471 mModemControllerActivity = new ControllerActivityCounterImpl(mBsi.mOnBatteryTimeBase,
Adam Lesinski21f76aa2016-01-25 12:27:06 -08007472 ModemActivityInfo.TX_POWER_LEVELS, in);
7473 } else {
7474 mModemControllerActivity = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07007475 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007476
Joe Onoratoabded112016-02-08 16:49:39 -08007477 mUserCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
7478 mSystemCpuTime = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007479
Adam Lesinski6832f392015-09-05 18:05:40 -07007480 if (in.readInt() != 0) {
7481 int numCpuClusters = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08007482 if (mBsi.mPowerProfile != null && mBsi.mPowerProfile.getNumCpuClusters() != numCpuClusters) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007483 throw new ParcelFormatException("Incompatible number of cpu clusters");
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007484 }
Adam Lesinski6832f392015-09-05 18:05:40 -07007485
Sudheer Shankaaf857412017-07-21 00:14:24 -07007486 mCpuClusterSpeedTimesUs = new LongSamplingCounter[numCpuClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -07007487 for (int cluster = 0; cluster < numCpuClusters; cluster++) {
7488 if (in.readInt() != 0) {
7489 int numSpeeds = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -08007490 if (mBsi.mPowerProfile != null &&
7491 mBsi.mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != numSpeeds) {
Adam Lesinski6832f392015-09-05 18:05:40 -07007492 throw new ParcelFormatException("Incompatible number of cpu speeds");
7493 }
7494
7495 final LongSamplingCounter[] cpuSpeeds = new LongSamplingCounter[numSpeeds];
Sudheer Shankaaf857412017-07-21 00:14:24 -07007496 mCpuClusterSpeedTimesUs[cluster] = cpuSpeeds;
Adam Lesinski6832f392015-09-05 18:05:40 -07007497 for (int speed = 0; speed < numSpeeds; speed++) {
7498 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007499 cpuSpeeds[speed] = new LongSamplingCounter(
7500 mBsi.mOnBatteryTimeBase, in);
Adam Lesinski6832f392015-09-05 18:05:40 -07007501 }
7502 }
Adam Lesinskia57a5402015-09-28 10:21:33 -07007503 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007504 mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -07007505 }
7506 }
7507 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -07007508 mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007509 }
Adam Lesinski5f056f62016-07-14 16:56:08 -07007510
Sudheer Shanka59f5c002017-05-15 10:57:15 -07007511 mCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(in, mBsi.mOnBatteryTimeBase);
7512 mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readFromParcel(
7513 in, mBsi.mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -07007514
7515 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -07007516 mMobileRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
7517 } else {
7518 mMobileRadioApWakeupCount = null;
7519 }
7520
7521 if (in.readInt() != 0) {
7522 mWifiRadioApWakeupCount = new LongSamplingCounter(mBsi.mOnBatteryTimeBase, in);
7523 } else {
7524 mWifiRadioApWakeupCount = null;
7525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007526 }
7527
7528 /**
7529 * The statistics associated with a particular wake lock.
7530 */
Joe Onoratoabded112016-02-08 16:49:39 -08007531 public static class Wakelock extends BatteryStats.Uid.Wakelock {
7532 /**
7533 * BatteryStatsImpl that we are associated with.
7534 */
7535 protected BatteryStatsImpl mBsi;
7536
7537 /**
7538 * BatteryStatsImpl that we are associated with.
7539 */
7540 protected Uid mUid;
7541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 /**
7543 * How long (in ms) this uid has been keeping the device partially awake.
Bookatz5b5ec322017-05-26 09:40:38 -07007544 * 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 -08007545 */
Bookatz5b5ec322017-05-26 09:40:38 -07007546 DualTimer mTimerPartial;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007547
7548 /**
7549 * How long (in ms) this uid has been keeping the device fully awake.
7550 */
Evan Millarc64edde2009-04-18 12:26:32 -07007551 StopwatchTimer mTimerFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552
7553 /**
7554 * How long (in ms) this uid has had a window keeping the device awake.
7555 */
Evan Millarc64edde2009-04-18 12:26:32 -07007556 StopwatchTimer mTimerWindow;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007557
7558 /**
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007559 * How long (in ms) this uid has had a draw wake lock.
Adam Lesinski9425fe22015-06-19 12:02:13 -07007560 */
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007561 StopwatchTimer mTimerDraw;
Adam Lesinski9425fe22015-06-19 12:02:13 -07007562
Joe Onoratoabded112016-02-08 16:49:39 -08007563 public Wakelock(BatteryStatsImpl bsi, Uid uid) {
7564 mBsi = bsi;
7565 mUid = uid;
7566 }
7567
Adam Lesinski9425fe22015-06-19 12:02:13 -07007568 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007569 * Reads a possibly null Timer from a Parcel. The timer is associated with the
7570 * proper timer pool from the given BatteryStatsImpl object.
7571 *
7572 * @param in the Parcel to be read from.
7573 * return a new Timer, or null.
7574 */
Joe Onorato92fd23f2016-07-25 11:18:42 -07007575 private StopwatchTimer readStopwatchTimerFromParcel(int type,
7576 ArrayList<StopwatchTimer> pool, TimeBase timeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007577 if (in.readInt() == 0) {
7578 return null;
7579 }
7580
Joe Onoratoabded112016-02-08 16:49:39 -08007581 return new StopwatchTimer(mBsi.mClocks, mUid, type, pool, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 }
7583
Joe Onorato92fd23f2016-07-25 11:18:42 -07007584 /**
7585 * Reads a possibly null Timer from a Parcel. The timer is associated with the
7586 * proper timer pool from the given BatteryStatsImpl object.
7587 *
7588 * @param in the Parcel to be read from.
7589 * return a new Timer, or null.
7590 */
Bookatz5b5ec322017-05-26 09:40:38 -07007591 private DualTimer readDualTimerFromParcel(int type, ArrayList<StopwatchTimer> pool,
7592 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
Joe Onorato92fd23f2016-07-25 11:18:42 -07007593 if (in.readInt() == 0) {
7594 return null;
7595 }
7596
Bookatz5b5ec322017-05-26 09:40:38 -07007597 return new DualTimer(mBsi.mClocks, mUid, type, pool, timeBase, bgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07007598 }
7599
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007600 boolean reset() {
7601 boolean wlactive = false;
7602 if (mTimerFull != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007603 wlactive |= !mTimerFull.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007604 }
7605 if (mTimerPartial != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007606 wlactive |= !mTimerPartial.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007607 }
7608 if (mTimerWindow != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007609 wlactive |= !mTimerWindow.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007610 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007611 if (mTimerDraw != null) {
7612 wlactive |= !mTimerDraw.reset(false);
Adam Lesinski9425fe22015-06-19 12:02:13 -07007613 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007614 if (!wlactive) {
7615 if (mTimerFull != null) {
7616 mTimerFull.detach();
7617 mTimerFull = null;
7618 }
7619 if (mTimerPartial != null) {
7620 mTimerPartial.detach();
7621 mTimerPartial = null;
7622 }
7623 if (mTimerWindow != null) {
7624 mTimerWindow.detach();
7625 mTimerWindow = null;
7626 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007627 if (mTimerDraw != null) {
7628 mTimerDraw.detach();
7629 mTimerDraw = null;
Adam Lesinski9425fe22015-06-19 12:02:13 -07007630 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007631 }
7632 return !wlactive;
7633 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007634
Bookatz5b5ec322017-05-26 09:40:38 -07007635 void readFromParcelLocked(TimeBase timeBase, TimeBase screenOffTimeBase,
7636 TimeBase screenOffBgTimeBase, Parcel in) {
7637 mTimerPartial = readDualTimerFromParcel(WAKE_TYPE_PARTIAL,
7638 mBsi.mPartialTimers, screenOffTimeBase, screenOffBgTimeBase, in);
Joe Onorato92fd23f2016-07-25 11:18:42 -07007639 mTimerFull = readStopwatchTimerFromParcel(WAKE_TYPE_FULL,
7640 mBsi.mFullTimers, timeBase, in);
7641 mTimerWindow = readStopwatchTimerFromParcel(WAKE_TYPE_WINDOW,
7642 mBsi.mWindowTimers, timeBase, in);
7643 mTimerDraw = readStopwatchTimerFromParcel(WAKE_TYPE_DRAW,
7644 mBsi.mDrawTimers, timeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 }
7646
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007647 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
7648 Timer.writeTimerToParcel(out, mTimerPartial, elapsedRealtimeUs);
7649 Timer.writeTimerToParcel(out, mTimerFull, elapsedRealtimeUs);
7650 Timer.writeTimerToParcel(out, mTimerWindow, elapsedRealtimeUs);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007651 Timer.writeTimerToParcel(out, mTimerDraw, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 }
7653
7654 @Override
7655 public Timer getWakeTime(int type) {
7656 switch (type) {
7657 case WAKE_TYPE_FULL: return mTimerFull;
7658 case WAKE_TYPE_PARTIAL: return mTimerPartial;
7659 case WAKE_TYPE_WINDOW: return mTimerWindow;
Jeff Brown6a8bd7b2015-06-19 15:07:51 -07007660 case WAKE_TYPE_DRAW: return mTimerDraw;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007661 default: throw new IllegalArgumentException("type = " + type);
7662 }
7663 }
7664 }
7665
Joe Onoratoabded112016-02-08 16:49:39 -08007666 public static class Sensor extends BatteryStats.Uid.Sensor {
7667 /**
7668 * BatteryStatsImpl that we are associated with.
7669 */
7670 protected BatteryStatsImpl mBsi;
7671
7672 /**
Bookatz867c0d72017-03-07 18:23:42 -08007673 * Uid that we are associated with.
Joe Onoratoabded112016-02-08 16:49:39 -08007674 */
7675 protected Uid mUid;
7676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677 final int mHandle;
Bookatz867c0d72017-03-07 18:23:42 -08007678 DualTimer mTimer;
Amith Yamasaniab9ad192016-12-06 12:46:59 -08007679
Joe Onoratoabded112016-02-08 16:49:39 -08007680 public Sensor(BatteryStatsImpl bsi, Uid uid, int handle) {
7681 mBsi = bsi;
7682 mUid = uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007683 mHandle = handle;
7684 }
7685
Bookatz867c0d72017-03-07 18:23:42 -08007686 private DualTimer readTimersFromParcel(
7687 TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 if (in.readInt() == 0) {
7689 return null;
7690 }
7691
Joe Onoratoabded112016-02-08 16:49:39 -08007692 ArrayList<StopwatchTimer> pool = mBsi.mSensorTimers.get(mHandle);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007693 if (pool == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07007694 pool = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08007695 mBsi.mSensorTimers.put(mHandle, pool);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007696 }
Bookatz867c0d72017-03-07 18:23:42 -08007697 return new DualTimer(mBsi.mClocks, mUid, 0, pool, timeBase, bgTimeBase, in);
Amith Yamasaniab9ad192016-12-06 12:46:59 -08007698 }
7699
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007700 boolean reset() {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007701 if (mTimer.reset(true)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007702 mTimer = null;
7703 return true;
7704 }
7705 return false;
7706 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007707
Bookatz867c0d72017-03-07 18:23:42 -08007708 void readFromParcelLocked(TimeBase timeBase, TimeBase bgTimeBase, Parcel in) {
7709 mTimer = readTimersFromParcel(timeBase, bgTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 }
7711
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007712 void writeToParcelLocked(Parcel out, long elapsedRealtimeUs) {
Bookatzaa4594a2017-03-24 12:39:56 -07007713 Timer.writeTimerToParcel(out, mTimer, elapsedRealtimeUs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 }
7715
7716 @Override
7717 public Timer getSensorTime() {
Bookatzaa4594a2017-03-24 12:39:56 -07007718 return mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007719 }
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007720
7721 @Override
Bookatz867c0d72017-03-07 18:23:42 -08007722 public Timer getSensorBackgroundTime() {
7723 if (mTimer == null) {
7724 return null;
7725 }
7726 return mTimer.getSubTimer();
Amith Yamasaniab9ad192016-12-06 12:46:59 -08007727 }
7728
7729 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 public int getHandle() {
7731 return mHandle;
7732 }
7733 }
7734
7735 /**
7736 * The statistics associated with a particular process.
7737 */
Joe Onoratoabded112016-02-08 16:49:39 -08007738 public static class Proc extends BatteryStats.Uid.Proc implements TimeBaseObs {
7739 /**
7740 * BatteryStatsImpl that we are associated with.
7741 */
7742 protected BatteryStatsImpl mBsi;
7743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007744 /**
Dianne Hackborncd0e3352014-08-07 17:08:09 -07007745 * The name of this process.
7746 */
7747 final String mName;
7748
7749 /**
Dianne Hackborn099bc622014-01-22 13:39:16 -08007750 * Remains true until removed from the stats.
7751 */
7752 boolean mActive = true;
7753
7754 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07007755 * Total time (in ms) spent executing in user code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007756 */
7757 long mUserTime;
7758
7759 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07007760 * Total time (in ms) spent executing in kernel code.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 */
7762 long mSystemTime;
7763
7764 /**
Dianne Hackborn62793e42015-03-09 11:15:41 -07007765 * Amount of time (in ms) the process was running in the foreground.
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007766 */
7767 long mForegroundTime;
7768
7769 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007770 * Number of times the process has been started.
7771 */
7772 int mStarts;
7773
7774 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007775 * Number of times the process has crashed.
7776 */
7777 int mNumCrashes;
7778
7779 /**
7780 * Number of times the process has had an ANR.
7781 */
7782 int mNumAnrs;
7783
7784 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 * The amount of user time loaded from a previous save.
7786 */
7787 long mLoadedUserTime;
7788
7789 /**
7790 * The amount of system time loaded from a previous save.
7791 */
7792 long mLoadedSystemTime;
7793
7794 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007795 * The amount of foreground time loaded from a previous save.
7796 */
7797 long mLoadedForegroundTime;
7798
7799 /**
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007800 * The number of times the process has started from a previous save.
7801 */
7802 int mLoadedStarts;
7803
7804 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007805 * Number of times the process has crashed from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007806 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007807 int mLoadedNumCrashes;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007808
7809 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007810 * Number of times the process has had an ANR from a previous save.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007811 */
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007812 int mLoadedNumAnrs;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007813
7814 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 * The amount of user time when last unplugged.
7816 */
7817 long mUnpluggedUserTime;
7818
7819 /**
7820 * The amount of system time when last unplugged.
7821 */
7822 long mUnpluggedSystemTime;
7823
7824 /**
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007825 * The amount of foreground time since unplugged.
7826 */
7827 long mUnpluggedForegroundTime;
7828
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007829 /**
7830 * The number of times the process has started before unplugged.
7831 */
7832 int mUnpluggedStarts;
7833
Dianne Hackborn61659e52014-07-09 16:13:01 -07007834 /**
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007835 * Number of times the process has crashed before unplugged.
7836 */
7837 int mUnpluggedNumCrashes;
7838
7839 /**
7840 * Number of times the process has had an ANR before unplugged.
7841 */
7842 int mUnpluggedNumAnrs;
7843
Dianne Hackborn287952c2010-09-22 22:34:31 -07007844 ArrayList<ExcessivePower> mExcessivePower;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007845
Joe Onoratoabded112016-02-08 16:49:39 -08007846 public Proc(BatteryStatsImpl bsi, String name) {
7847 mBsi = bsi;
Dianne Hackborncd0e3352014-08-07 17:08:09 -07007848 mName = name;
Joe Onoratoabded112016-02-08 16:49:39 -08007849 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007850 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07007851
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007852 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007853 mUnpluggedUserTime = mUserTime;
7854 mUnpluggedSystemTime = mSystemTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007855 mUnpluggedForegroundTime = mForegroundTime;
Jeff Sharkey3e013e82013-04-25 14:48:19 -07007856 mUnpluggedStarts = mStarts;
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007857 mUnpluggedNumCrashes = mNumCrashes;
7858 mUnpluggedNumAnrs = mNumAnrs;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007859 }
7860
Dianne Hackborn97ae5382014-03-05 16:43:25 -08007861 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007863
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007864 void detach() {
Dianne Hackborn099bc622014-01-22 13:39:16 -08007865 mActive = false;
Joe Onoratoabded112016-02-08 16:49:39 -08007866 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07007867 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07007868
Dianne Hackborn287952c2010-09-22 22:34:31 -07007869 public int countExcessivePowers() {
7870 return mExcessivePower != null ? mExcessivePower.size() : 0;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007871 }
7872
Dianne Hackborn287952c2010-09-22 22:34:31 -07007873 public ExcessivePower getExcessivePower(int i) {
7874 if (mExcessivePower != null) {
7875 return mExcessivePower.get(i);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007876 }
7877 return null;
7878 }
7879
Dianne Hackborn287952c2010-09-22 22:34:31 -07007880 public void addExcessiveCpu(long overTime, long usedTime) {
7881 if (mExcessivePower == null) {
7882 mExcessivePower = new ArrayList<ExcessivePower>();
7883 }
7884 ExcessivePower ew = new ExcessivePower();
7885 ew.type = ExcessivePower.TYPE_CPU;
7886 ew.overTime = overTime;
7887 ew.usedTime = usedTime;
7888 mExcessivePower.add(ew);
7889 }
7890
7891 void writeExcessivePowerToParcelLocked(Parcel out) {
7892 if (mExcessivePower == null) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007893 out.writeInt(0);
7894 return;
7895 }
7896
Dianne Hackborn287952c2010-09-22 22:34:31 -07007897 final int N = mExcessivePower.size();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007898 out.writeInt(N);
7899 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07007900 ExcessivePower ew = mExcessivePower.get(i);
7901 out.writeInt(ew.type);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007902 out.writeLong(ew.overTime);
7903 out.writeLong(ew.usedTime);
7904 }
7905 }
7906
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07007907 void readExcessivePowerFromParcelLocked(Parcel in) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007908 final int N = in.readInt();
7909 if (N == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07007910 mExcessivePower = null;
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07007911 return;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007912 }
7913
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08007914 if (N > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07007915 throw new ParcelFormatException(
7916 "File corrupt: too many excessive power entries " + N);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -08007917 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07007918
Adam Lesinski9ae9cba2015-07-08 17:09:34 -07007919 mExcessivePower = new ArrayList<>();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007920 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07007921 ExcessivePower ew = new ExcessivePower();
7922 ew.type = in.readInt();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007923 ew.overTime = in.readLong();
7924 ew.usedTime = in.readLong();
Dianne Hackborn287952c2010-09-22 22:34:31 -07007925 mExcessivePower.add(ew);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007926 }
7927 }
7928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007929 void writeToParcelLocked(Parcel out) {
7930 out.writeLong(mUserTime);
7931 out.writeLong(mSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007932 out.writeLong(mForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 out.writeInt(mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007934 out.writeInt(mNumCrashes);
7935 out.writeInt(mNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 out.writeLong(mLoadedUserTime);
7937 out.writeLong(mLoadedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007938 out.writeLong(mLoadedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007939 out.writeInt(mLoadedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007940 out.writeInt(mLoadedNumCrashes);
7941 out.writeInt(mLoadedNumAnrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007942 out.writeLong(mUnpluggedUserTime);
7943 out.writeLong(mUnpluggedSystemTime);
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007944 out.writeLong(mUnpluggedForegroundTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007945 out.writeInt(mUnpluggedStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007946 out.writeInt(mUnpluggedNumCrashes);
7947 out.writeInt(mUnpluggedNumAnrs);
Dianne Hackborn287952c2010-09-22 22:34:31 -07007948 writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007949 }
7950
7951 void readFromParcelLocked(Parcel in) {
7952 mUserTime = in.readLong();
7953 mSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007954 mForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 mStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007956 mNumCrashes = in.readInt();
7957 mNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007958 mLoadedUserTime = in.readLong();
7959 mLoadedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007960 mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007961 mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007962 mLoadedNumCrashes = in.readInt();
7963 mLoadedNumAnrs = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007964 mUnpluggedUserTime = in.readLong();
7965 mUnpluggedSystemTime = in.readLong();
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007966 mUnpluggedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007967 mUnpluggedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007968 mUnpluggedNumCrashes = in.readInt();
7969 mUnpluggedNumAnrs = in.readInt();
Dianne Hackborn287952c2010-09-22 22:34:31 -07007970 readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 }
7972
Adam Lesinski06af1fa2015-05-05 17:35:35 -07007973 public void addCpuTimeLocked(int utime, int stime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 mUserTime += utime;
7975 mSystemTime += stime;
7976 }
7977
Amith Yamasanieaeb6632009-06-03 15:16:10 -07007978 public void addForegroundTimeLocked(long ttime) {
7979 mForegroundTime += ttime;
7980 }
7981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 public void incStartsLocked() {
7983 mStarts++;
7984 }
7985
Dianne Hackborn1e01d162014-12-04 17:46:42 -08007986 public void incNumCrashesLocked() {
7987 mNumCrashes++;
7988 }
7989
7990 public void incNumAnrsLocked() {
7991 mNumAnrs++;
7992 }
7993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007994 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08007995 public boolean isActive() {
7996 return mActive;
7997 }
7998
7999 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 public long getUserTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008001 long val = mUserTime;
8002 if (which == STATS_CURRENT) {
8003 val -= mLoadedUserTime;
8004 } else if (which == STATS_SINCE_UNPLUGGED) {
8005 val -= mUnpluggedUserTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008006 }
8007 return val;
8008 }
8009
8010 @Override
8011 public long getSystemTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008012 long val = mSystemTime;
8013 if (which == STATS_CURRENT) {
8014 val -= mLoadedSystemTime;
8015 } else if (which == STATS_SINCE_UNPLUGGED) {
8016 val -= mUnpluggedSystemTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 }
8018 return val;
8019 }
8020
8021 @Override
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008022 public long getForegroundTime(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008023 long val = mForegroundTime;
8024 if (which == STATS_CURRENT) {
8025 val -= mLoadedForegroundTime;
8026 } else if (which == STATS_SINCE_UNPLUGGED) {
8027 val -= mUnpluggedForegroundTime;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07008028 }
8029 return val;
8030 }
8031
8032 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008034 int val = mStarts;
8035 if (which == STATS_CURRENT) {
8036 val -= mLoadedStarts;
8037 } else if (which == STATS_SINCE_UNPLUGGED) {
8038 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008039 }
8040 return val;
8041 }
Amith Yamasanie43530a2009-08-21 13:11:37 -07008042
Dianne Hackborn1e01d162014-12-04 17:46:42 -08008043 @Override
8044 public int getNumCrashes(int which) {
8045 int val = mNumCrashes;
8046 if (which == STATS_CURRENT) {
8047 val -= mLoadedNumCrashes;
8048 } else if (which == STATS_SINCE_UNPLUGGED) {
8049 val -= mUnpluggedNumCrashes;
8050 }
8051 return val;
8052 }
8053
8054 @Override
8055 public int getNumAnrs(int which) {
8056 int val = mNumAnrs;
8057 if (which == STATS_CURRENT) {
8058 val -= mLoadedNumAnrs;
8059 } else if (which == STATS_SINCE_UNPLUGGED) {
8060 val -= mUnpluggedNumAnrs;
8061 }
8062 return val;
8063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 }
8065
8066 /**
8067 * The statistics associated with a particular package.
8068 */
Joe Onoratoabded112016-02-08 16:49:39 -08008069 public static class Pkg extends BatteryStats.Uid.Pkg implements TimeBaseObs {
8070 /**
8071 * BatteryStatsImpl that we are associated with.
8072 */
8073 protected BatteryStatsImpl mBsi;
8074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 /**
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008076 * Number of times wakeup alarms have occurred for this app.
Bookatz98d4d5c2017-08-01 19:07:54 -07008077 * On screen-off timebase starting in report v25.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008078 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008079 ArrayMap<String, Counter> mWakeupAlarms = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008080
8081 /**
8082 * The statics we have collected for this package's services.
8083 */
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008084 final ArrayMap<String, Serv> mServiceStats = new ArrayMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085
Joe Onoratoabded112016-02-08 16:49:39 -08008086 public Pkg(BatteryStatsImpl bsi) {
8087 mBsi = bsi;
8088 mBsi.mOnBatteryScreenOffTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008090
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008091 public void onTimeStarted(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 }
8093
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008094 public void onTimeStopped(long elapsedRealtime, long baseUptime, long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008096
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008097 void detach() {
Joe Onoratoabded112016-02-08 16:49:39 -08008098 mBsi.mOnBatteryScreenOffTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008099 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008101 void readFromParcelLocked(Parcel in) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008102 int numWA = in.readInt();
8103 mWakeupAlarms.clear();
8104 for (int i=0; i<numWA; i++) {
8105 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -07008106 mWakeupAlarms.put(tag, new Counter(mBsi.mOnBatteryScreenOffTimeBase, in));
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108
8109 int numServs = in.readInt();
8110 mServiceStats.clear();
8111 for (int m = 0; m < numServs; m++) {
8112 String serviceName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -08008113 Uid.Pkg.Serv serv = new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008114 mServiceStats.put(serviceName, serv);
8115
8116 serv.readFromParcelLocked(in);
8117 }
8118 }
8119
8120 void writeToParcelLocked(Parcel out) {
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008121 int numWA = mWakeupAlarms.size();
8122 out.writeInt(numWA);
8123 for (int i=0; i<numWA; i++) {
8124 out.writeString(mWakeupAlarms.keyAt(i));
8125 mWakeupAlarms.valueAt(i).writeToParcel(out);
8126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008127
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008128 final int NS = mServiceStats.size();
8129 out.writeInt(NS);
8130 for (int i=0; i<NS; i++) {
8131 out.writeString(mServiceStats.keyAt(i));
8132 Uid.Pkg.Serv serv = mServiceStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 serv.writeToParcelLocked(out);
8134 }
8135 }
8136
8137 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008138 public ArrayMap<String, ? extends BatteryStats.Counter> getWakeupAlarmStats() {
8139 return mWakeupAlarms;
8140 }
8141
8142 public void noteWakeupAlarmLocked(String tag) {
8143 Counter c = mWakeupAlarms.get(tag);
8144 if (c == null) {
Bookatz98d4d5c2017-08-01 19:07:54 -07008145 c = new Counter(mBsi.mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008146 mWakeupAlarms.put(tag, c);
8147 }
8148 c.stepAtomic();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 }
8150
8151 @Override
Dianne Hackborn1e725a72015-03-24 18:23:19 -07008152 public ArrayMap<String, ? extends BatteryStats.Uid.Pkg.Serv> getServiceStats() {
8153 return mServiceStats;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008154 }
8155
8156 /**
8157 * The statistics associated with a particular service.
8158 */
Joe Onoratoabded112016-02-08 16:49:39 -08008159 public static class Serv extends BatteryStats.Uid.Pkg.Serv implements TimeBaseObs {
8160 /**
8161 * BatteryStatsImpl that we are associated with.
8162 */
8163 protected BatteryStatsImpl mBsi;
8164
8165 /**
8166 * The android package in which this service resides.
8167 */
8168 protected Pkg mPkg;
8169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 /**
8171 * Total time (ms in battery uptime) the service has been left started.
8172 */
Joe Onoratoabded112016-02-08 16:49:39 -08008173 protected long mStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008174
8175 /**
8176 * If service has been started and not yet stopped, this is
8177 * when it was started.
8178 */
Joe Onoratoabded112016-02-08 16:49:39 -08008179 protected long mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008180
8181 /**
8182 * True if we are currently running.
8183 */
Joe Onoratoabded112016-02-08 16:49:39 -08008184 protected boolean mRunning;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185
8186 /**
8187 * Total number of times startService() has been called.
8188 */
Joe Onoratoabded112016-02-08 16:49:39 -08008189 protected int mStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190
8191 /**
8192 * Total time (ms in battery uptime) the service has been left launched.
8193 */
Joe Onoratoabded112016-02-08 16:49:39 -08008194 protected long mLaunchedTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008195
8196 /**
8197 * If service has been launched and not yet exited, this is
8198 * when it was launched (ms in battery uptime).
8199 */
Joe Onoratoabded112016-02-08 16:49:39 -08008200 protected long mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008201
8202 /**
8203 * True if we are currently launched.
8204 */
Joe Onoratoabded112016-02-08 16:49:39 -08008205 protected boolean mLaunched;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008206
8207 /**
8208 * Total number times the service has been launched.
8209 */
Joe Onoratoabded112016-02-08 16:49:39 -08008210 protected int mLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008211
8212 /**
8213 * The amount of time spent started loaded from a previous save
8214 * (ms in battery uptime).
8215 */
Joe Onoratoabded112016-02-08 16:49:39 -08008216 protected long mLoadedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008217
8218 /**
8219 * The number of starts loaded from a previous save.
8220 */
Joe Onoratoabded112016-02-08 16:49:39 -08008221 protected int mLoadedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222
8223 /**
8224 * The number of launches loaded from a previous save.
8225 */
Joe Onoratoabded112016-02-08 16:49:39 -08008226 protected int mLoadedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008227
8228 /**
8229 * The amount of time spent started as of the last run (ms
8230 * in battery uptime).
8231 */
Joe Onoratoabded112016-02-08 16:49:39 -08008232 protected long mLastStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008233
8234 /**
8235 * The number of starts as of the last run.
8236 */
Joe Onoratoabded112016-02-08 16:49:39 -08008237 protected int mLastStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008238
8239 /**
8240 * The number of launches as of the last run.
8241 */
Joe Onoratoabded112016-02-08 16:49:39 -08008242 protected int mLastLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008243
8244 /**
8245 * The amount of time spent started when last unplugged (ms
8246 * in battery uptime).
8247 */
Joe Onoratoabded112016-02-08 16:49:39 -08008248 protected long mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008249
8250 /**
8251 * The number of starts when last unplugged.
8252 */
Joe Onoratoabded112016-02-08 16:49:39 -08008253 protected int mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008254
8255 /**
8256 * The number of launches when last unplugged.
8257 */
Joe Onoratoabded112016-02-08 16:49:39 -08008258 protected int mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259
Joe Onoratoabded112016-02-08 16:49:39 -08008260 /**
8261 * Construct a Serv. Also adds it to the on-battery time base as a listener.
8262 */
8263 public Serv(BatteryStatsImpl bsi) {
8264 mBsi = bsi;
8265 mBsi.mOnBatteryTimeBase.add(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008266 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008267
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008268 public void onTimeStarted(long elapsedRealtime, long baseUptime,
8269 long baseRealtime) {
8270 mUnpluggedStartTime = getStartTimeToNowLocked(baseUptime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008271 mUnpluggedStarts = mStarts;
8272 mUnpluggedLaunches = mLaunches;
8273 }
8274
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008275 public void onTimeStopped(long elapsedRealtime, long baseUptime,
8276 long baseRealtime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008277 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008278
Joe Onoratoabded112016-02-08 16:49:39 -08008279 /**
8280 * Remove this Serv as a listener from the time base.
8281 */
8282 public void detach() {
8283 mBsi.mOnBatteryTimeBase.remove(this);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008284 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008285
Joe Onoratoabded112016-02-08 16:49:39 -08008286 public void readFromParcelLocked(Parcel in) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008287 mStartTime = in.readLong();
8288 mRunningSince = in.readLong();
8289 mRunning = in.readInt() != 0;
8290 mStarts = in.readInt();
8291 mLaunchedTime = in.readLong();
8292 mLaunchedSince = in.readLong();
8293 mLaunched = in.readInt() != 0;
8294 mLaunches = in.readInt();
8295 mLoadedStartTime = in.readLong();
8296 mLoadedStarts = in.readInt();
8297 mLoadedLaunches = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -07008298 mLastStartTime = 0;
8299 mLastStarts = 0;
8300 mLastLaunches = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008301 mUnpluggedStartTime = in.readLong();
8302 mUnpluggedStarts = in.readInt();
8303 mUnpluggedLaunches = in.readInt();
8304 }
8305
Joe Onoratoabded112016-02-08 16:49:39 -08008306 public void writeToParcelLocked(Parcel out) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008307 out.writeLong(mStartTime);
8308 out.writeLong(mRunningSince);
8309 out.writeInt(mRunning ? 1 : 0);
8310 out.writeInt(mStarts);
8311 out.writeLong(mLaunchedTime);
8312 out.writeLong(mLaunchedSince);
8313 out.writeInt(mLaunched ? 1 : 0);
8314 out.writeInt(mLaunches);
8315 out.writeLong(mLoadedStartTime);
8316 out.writeInt(mLoadedStarts);
8317 out.writeInt(mLoadedLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008318 out.writeLong(mUnpluggedStartTime);
8319 out.writeInt(mUnpluggedStarts);
8320 out.writeInt(mUnpluggedLaunches);
8321 }
8322
Joe Onoratoabded112016-02-08 16:49:39 -08008323 public long getLaunchTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008324 if (!mLaunched) return mLaunchedTime;
8325 return mLaunchedTime + batteryUptime - mLaunchedSince;
8326 }
8327
Joe Onoratoabded112016-02-08 16:49:39 -08008328 public long getStartTimeToNowLocked(long batteryUptime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008329 if (!mRunning) return mStartTime;
8330 return mStartTime + batteryUptime - mRunningSince;
8331 }
8332
8333 public void startLaunchedLocked() {
8334 if (!mLaunched) {
8335 mLaunches++;
Joe Onoratoabded112016-02-08 16:49:39 -08008336 mLaunchedSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008337 mLaunched = true;
8338 }
8339 }
8340
8341 public void stopLaunchedLocked() {
8342 if (mLaunched) {
Joe Onoratoabded112016-02-08 16:49:39 -08008343 long time = mBsi.getBatteryUptimeLocked() - mLaunchedSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008344 if (time > 0) {
8345 mLaunchedTime += time;
8346 } else {
8347 mLaunches--;
8348 }
8349 mLaunched = false;
8350 }
8351 }
8352
8353 public void startRunningLocked() {
8354 if (!mRunning) {
8355 mStarts++;
Joe Onoratoabded112016-02-08 16:49:39 -08008356 mRunningSince = mBsi.getBatteryUptimeLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008357 mRunning = true;
8358 }
8359 }
8360
8361 public void stopRunningLocked() {
8362 if (mRunning) {
Joe Onoratoabded112016-02-08 16:49:39 -08008363 long time = mBsi.getBatteryUptimeLocked() - mRunningSince;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008364 if (time > 0) {
8365 mStartTime += time;
8366 } else {
8367 mStarts--;
8368 }
8369 mRunning = false;
8370 }
8371 }
8372
8373 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08008374 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008375 }
8376
8377 @Override
8378 public int getLaunches(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008379 int val = mLaunches;
8380 if (which == STATS_CURRENT) {
8381 val -= mLoadedLaunches;
8382 } else if (which == STATS_SINCE_UNPLUGGED) {
8383 val -= mUnpluggedLaunches;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008385 return val;
8386 }
8387
8388 @Override
8389 public long getStartTime(long now, int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008390 long val = getStartTimeToNowLocked(now);
8391 if (which == STATS_CURRENT) {
8392 val -= mLoadedStartTime;
8393 } else if (which == STATS_SINCE_UNPLUGGED) {
8394 val -= mUnpluggedStartTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008396 return val;
8397 }
8398
8399 @Override
8400 public int getStarts(int which) {
Dianne Hackborn4590e522014-03-24 13:36:46 -07008401 int val = mStarts;
8402 if (which == STATS_CURRENT) {
8403 val -= mLoadedStarts;
8404 } else if (which == STATS_SINCE_UNPLUGGED) {
8405 val -= mUnpluggedStarts;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008406 }
8407
8408 return val;
8409 }
8410 }
8411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008412 final Serv newServiceStatsLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -08008413 return new Serv(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008414 }
8415 }
8416
8417 /**
8418 * Retrieve the statistics object for a particular process, creating
8419 * if needed.
8420 */
8421 public Proc getProcessStatsLocked(String name) {
8422 Proc ps = mProcessStats.get(name);
8423 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08008424 ps = new Proc(mBsi, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008425 mProcessStats.put(name, ps);
8426 }
8427
8428 return ps;
8429 }
8430
Dianne Hackborna8d10942015-11-19 17:55:19 -08008431 public void updateUidProcessStateLocked(int procState) {
8432 int uidRunningState;
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008433 // Make special note of Foreground Services
8434 final boolean userAwareService =
8435 (procState == ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE);
Dianne Hackborna8d10942015-11-19 17:55:19 -08008436 if (procState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
8437 uidRunningState = ActivityManager.PROCESS_STATE_NONEXISTENT;
8438 } else if (procState == ActivityManager.PROCESS_STATE_TOP) {
8439 uidRunningState = PROCESS_STATE_TOP;
8440 } else if (procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
8441 // Persistent and other foreground states go here.
8442 uidRunningState = PROCESS_STATE_FOREGROUND_SERVICE;
8443 } else if (procState <= ActivityManager.PROCESS_STATE_TOP_SLEEPING) {
8444 uidRunningState = PROCESS_STATE_TOP_SLEEPING;
8445 } else if (procState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
8446 // Persistent and other foreground states go here.
8447 uidRunningState = PROCESS_STATE_FOREGROUND;
8448 } else if (procState <= ActivityManager.PROCESS_STATE_RECEIVER) {
8449 uidRunningState = PROCESS_STATE_BACKGROUND;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008450 } else {
Dianne Hackborna8d10942015-11-19 17:55:19 -08008451 uidRunningState = PROCESS_STATE_CACHED;
Dianne Hackborn61659e52014-07-09 16:13:01 -07008452 }
Dianne Hackborn61659e52014-07-09 16:13:01 -07008453
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008454 if (mProcessState == uidRunningState && userAwareService == mInForegroundService) {
8455 return;
8456 }
Dianne Hackborna8d10942015-11-19 17:55:19 -08008457
Bookatz867c0d72017-03-07 18:23:42 -08008458 final long elapsedRealtimeMs = mBsi.mClocks.elapsedRealtime();
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008459 if (mProcessState != uidRunningState) {
8460 final long uptimeMs = mBsi.mClocks.uptimeMillis();
Dianne Hackborna8d10942015-11-19 17:55:19 -08008461
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008462 if (mProcessState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
8463 mProcessStateTimer[mProcessState].stopRunningLocked(elapsedRealtimeMs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008464 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008465 mProcessState = uidRunningState;
8466 if (uidRunningState != ActivityManager.PROCESS_STATE_NONEXISTENT) {
8467 if (mProcessStateTimer[uidRunningState] == null) {
8468 makeProcessState(uidRunningState, null);
8469 }
8470 mProcessStateTimer[uidRunningState].startRunningLocked(elapsedRealtimeMs);
8471 }
8472
8473 updateOnBatteryBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
8474 updateOnBatteryScreenOffBgTimeBase(uptimeMs * 1000, elapsedRealtimeMs * 1000);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008475 }
Bookatz867c0d72017-03-07 18:23:42 -08008476
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -07008477 if (userAwareService != mInForegroundService) {
8478 if (userAwareService) {
8479 noteForegroundServiceResumedLocked(elapsedRealtimeMs);
8480 } else {
8481 noteForegroundServicePausedLocked(elapsedRealtimeMs);
8482 }
8483 mInForegroundService = userAwareService;
8484 }
Bookatz867c0d72017-03-07 18:23:42 -08008485 }
8486
Bookatzc8c44962017-05-11 12:12:54 -07008487 /** Whether to consider Uid to be in the background for background timebase purposes. */
8488 public boolean isInBackground() {
Bookatz867c0d72017-03-07 18:23:42 -08008489 // Note that PROCESS_STATE_CACHED and ActivityManager.PROCESS_STATE_NONEXISTENT is
8490 // also considered to be 'background' for our purposes, because it's not foreground.
Bookatzc8c44962017-05-11 12:12:54 -07008491 return mProcessState >= PROCESS_STATE_BACKGROUND;
8492 }
8493
8494 public boolean updateOnBatteryBgTimeBase(long uptimeUs, long realtimeUs) {
8495 boolean on = mBsi.mOnBatteryTimeBase.isRunning() && isInBackground();
8496 return mOnBatteryBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
8497 }
8498
8499 public boolean updateOnBatteryScreenOffBgTimeBase(long uptimeUs, long realtimeUs) {
8500 boolean on = mBsi.mOnBatteryScreenOffTimeBase.isRunning() && isInBackground();
8501 return mOnBatteryScreenOffBackgroundTimeBase.setRunning(on, uptimeUs, realtimeUs);
Dianne Hackborn61659e52014-07-09 16:13:01 -07008502 }
8503
Dianne Hackbornb5e31652010-09-07 12:13:55 -07008504 public SparseArray<? extends Pid> getPidStats() {
8505 return mPids;
8506 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008507
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008508 public Pid getPidStatsLocked(int pid) {
8509 Pid p = mPids.get(pid);
8510 if (p == null) {
8511 p = new Pid();
8512 mPids.put(pid, p);
8513 }
8514 return p;
8515 }
8516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 /**
8518 * Retrieve the statistics object for a particular service, creating
8519 * if needed.
8520 */
8521 public Pkg getPackageStatsLocked(String name) {
8522 Pkg ps = mPackageStats.get(name);
8523 if (ps == null) {
Joe Onoratoabded112016-02-08 16:49:39 -08008524 ps = new Pkg(mBsi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525 mPackageStats.put(name, ps);
8526 }
8527
8528 return ps;
8529 }
8530
8531 /**
8532 * Retrieve the statistics object for a particular service, creating
8533 * if needed.
8534 */
8535 public Pkg.Serv getServiceStatsLocked(String pkg, String serv) {
8536 Pkg ps = getPackageStatsLocked(pkg);
8537 Pkg.Serv ss = ps.mServiceStats.get(serv);
8538 if (ss == null) {
8539 ss = ps.newServiceStatsLocked();
8540 ps.mServiceStats.put(serv, ss);
8541 }
8542
8543 return ss;
8544 }
8545
Dianne Hackbornd953c532014-08-16 18:17:38 -07008546 public void readSyncSummaryFromParcelLocked(String name, Parcel in) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008547 DualTimer timer = mSyncStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008548 timer.readSummaryFromParcelLocked(in);
8549 mSyncStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008550 }
8551
Dianne Hackbornd953c532014-08-16 18:17:38 -07008552 public void readJobSummaryFromParcelLocked(String name, Parcel in) {
Bookatzaa4594a2017-03-24 12:39:56 -07008553 DualTimer timer = mJobStats.instantiateObject();
Dianne Hackbornd953c532014-08-16 18:17:38 -07008554 timer.readSummaryFromParcelLocked(in);
8555 mJobStats.add(name, timer);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008556 }
8557
Dianne Hackbornd953c532014-08-16 18:17:38 -07008558 public void readWakeSummaryFromParcelLocked(String wlName, Parcel in) {
Joe Onoratoabded112016-02-08 16:49:39 -08008559 Wakelock wl = new Wakelock(mBsi, this);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008560 mWakelockStats.add(wlName, wl);
8561 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07008562 getWakelockTimerLocked(wl, WAKE_TYPE_FULL).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07008564 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07008565 getWakelockTimerLocked(wl, WAKE_TYPE_PARTIAL).readSummaryFromParcelLocked(in);
Dianne Hackbornd953c532014-08-16 18:17:38 -07008566 }
8567 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07008568 getWakelockTimerLocked(wl, WAKE_TYPE_WINDOW).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008569 }
Adam Lesinski9425fe22015-06-19 12:02:13 -07008570 if (in.readInt() != 0) {
Bookatz5b5ec322017-05-26 09:40:38 -07008571 getWakelockTimerLocked(wl, WAKE_TYPE_DRAW).readSummaryFromParcelLocked(in);
Adam Lesinski9425fe22015-06-19 12:02:13 -07008572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008573 }
8574
Bookatz867c0d72017-03-07 18:23:42 -08008575 public DualTimer getSensorTimerLocked(int sensor, boolean create) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008576 Sensor se = mSensorStats.get(sensor);
8577 if (se == null) {
8578 if (!create) {
8579 return null;
8580 }
Joe Onoratoabded112016-02-08 16:49:39 -08008581 se = new Sensor(mBsi, this, sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 mSensorStats.put(sensor, se);
8583 }
Bookatz867c0d72017-03-07 18:23:42 -08008584 DualTimer t = se.mTimer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008585 if (t != null) {
8586 return t;
8587 }
Joe Onoratoabded112016-02-08 16:49:39 -08008588 ArrayList<StopwatchTimer> timers = mBsi.mSensorTimers.get(sensor);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008589 if (timers == null) {
Evan Millarc64edde2009-04-18 12:26:32 -07008590 timers = new ArrayList<StopwatchTimer>();
Joe Onoratoabded112016-02-08 16:49:39 -08008591 mBsi.mSensorTimers.put(sensor, timers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 }
Bookatz867c0d72017-03-07 18:23:42 -08008593 t = new DualTimer(mBsi.mClocks, this, BatteryStats.SENSOR, timers,
8594 mBsi.mOnBatteryTimeBase, mOnBatteryBackgroundTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595 se.mTimer = t;
8596 return t;
8597 }
8598
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008599 public void noteStartSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008600 DualTimer t = mSyncStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008601 if (t != null) {
8602 t.startRunningLocked(elapsedRealtimeMs);
8603 }
8604 }
8605
8606 public void noteStopSyncLocked(String name, long elapsedRealtimeMs) {
Bookatz2bffb5b2017-04-13 11:59:33 -07008607 DualTimer t = mSyncStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008608 if (t != null) {
8609 t.stopRunningLocked(elapsedRealtimeMs);
8610 }
8611 }
8612
8613 public void noteStartJobLocked(String name, long elapsedRealtimeMs) {
Bookatzaa4594a2017-03-24 12:39:56 -07008614 DualTimer t = mJobStats.startObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008615 if (t != null) {
8616 t.startRunningLocked(elapsedRealtimeMs);
8617 }
8618 }
8619
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008620 public void noteStopJobLocked(String name, long elapsedRealtimeMs, int stopReason) {
Bookatzaa4594a2017-03-24 12:39:56 -07008621 DualTimer t = mJobStats.stopObject(name);
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008622 if (t != null) {
8623 t.stopRunningLocked(elapsedRealtimeMs);
8624 }
Dianne Hackborn94326cb2017-06-28 16:17:20 -07008625 if (mBsi.mOnBatteryTimeBase.isRunning()) {
8626 SparseIntArray types = mJobCompletions.get(name);
8627 if (types == null) {
8628 types = new SparseIntArray();
8629 mJobCompletions.put(name, types);
8630 }
8631 int last = types.get(stopReason, 0);
8632 types.put(stopReason, last + 1);
8633 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -07008634 }
8635
Bookatz5b5ec322017-05-26 09:40:38 -07008636 public StopwatchTimer getWakelockTimerLocked(Wakelock wl, int type) {
8637 if (wl == null) {
8638 return null;
8639 }
8640 switch (type) {
8641 case WAKE_TYPE_PARTIAL: {
8642 DualTimer t = wl.mTimerPartial;
8643 if (t == null) {
8644 t = new DualTimer(mBsi.mClocks, this, WAKE_TYPE_PARTIAL,
8645 mBsi.mPartialTimers, mBsi.mOnBatteryScreenOffTimeBase,
8646 mOnBatteryScreenOffBackgroundTimeBase);
8647 wl.mTimerPartial = t;
8648 }
8649 return t;
8650 }
8651 case WAKE_TYPE_FULL: {
8652 StopwatchTimer t = wl.mTimerFull;
8653 if (t == null) {
8654 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_FULL,
8655 mBsi.mFullTimers, mBsi.mOnBatteryTimeBase);
8656 wl.mTimerFull = t;
8657 }
8658 return t;
8659 }
8660 case WAKE_TYPE_WINDOW: {
8661 StopwatchTimer t = wl.mTimerWindow;
8662 if (t == null) {
8663 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_WINDOW,
8664 mBsi.mWindowTimers, mBsi.mOnBatteryTimeBase);
8665 wl.mTimerWindow = t;
8666 }
8667 return t;
8668 }
8669 case WAKE_TYPE_DRAW: {
8670 StopwatchTimer t = wl.mTimerDraw;
8671 if (t == null) {
8672 t = new StopwatchTimer(mBsi.mClocks, this, WAKE_TYPE_DRAW,
8673 mBsi.mDrawTimers, mBsi.mOnBatteryTimeBase);
8674 wl.mTimerDraw = t;
8675 }
8676 return t;
8677 }
8678 default:
8679 throw new IllegalArgumentException("type=" + type);
8680 }
8681 }
8682
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008683 public void noteStartWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008684 Wakelock wl = mWakelockStats.startObject(name);
8685 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07008686 getWakelockTimerLocked(wl, type).startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008687 }
Bookatzc8c44962017-05-11 12:12:54 -07008688 if (type == WAKE_TYPE_PARTIAL) {
8689 createAggregatedPartialWakelockTimerLocked().startRunningLocked(elapsedRealtimeMs);
8690 if (pid >= 0) {
8691 Pid p = getPidStatsLocked(pid);
8692 if (p.mWakeNesting++ == 0) {
8693 p.mWakeStartMs = elapsedRealtimeMs;
8694 }
Dianne Hackbornb8071d792010-09-09 16:45:15 -07008695 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008697 }
8698
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008699 public void noteStopWakeLocked(int pid, String name, int type, long elapsedRealtimeMs) {
Dianne Hackbornd953c532014-08-16 18:17:38 -07008700 Wakelock wl = mWakelockStats.stopObject(name);
8701 if (wl != null) {
Bookatz5b5ec322017-05-26 09:40:38 -07008702 getWakelockTimerLocked(wl, type).stopRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008703 }
Bookatzc8c44962017-05-11 12:12:54 -07008704 if (type == WAKE_TYPE_PARTIAL) {
8705 if (mAggregatedPartialWakelockTimer != null) {
8706 mAggregatedPartialWakelockTimer.stopRunningLocked(elapsedRealtimeMs);
8707 }
8708 if (pid >= 0) {
8709 Pid p = mPids.get(pid);
8710 if (p != null && p.mWakeNesting > 0) {
8711 if (p.mWakeNesting-- == 1) {
8712 p.mWakeSumMs += elapsedRealtimeMs - p.mWakeStartMs;
8713 p.mWakeStartMs = 0;
8714 }
Dianne Hackborne5167ca2014-03-08 14:39:10 -08008715 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07008716 }
8717 }
8718 }
8719
Dianne Hackborn287952c2010-09-22 22:34:31 -07008720 public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
8721 Proc p = getProcessStatsLocked(proc);
8722 if (p != null) {
8723 p.addExcessiveCpu(overTime, usedTime);
8724 }
8725 }
8726
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008727 public void noteStartSensor(int sensor, long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08008728 DualTimer t = getSensorTimerLocked(sensor, /* create= */ true);
Amith Yamasani154d1242017-02-16 10:01:48 -08008729 t.startRunningLocked(elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008730 }
8731
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008732 public void noteStopSensor(int sensor, long elapsedRealtimeMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008733 // Don't create a timer if one doesn't already exist
Bookatz867c0d72017-03-07 18:23:42 -08008734 DualTimer t = getSensorTimerLocked(sensor, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008735 if (t != null) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008736 t.stopRunningLocked(elapsedRealtimeMs);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008738 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008739
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008740 public void noteStartGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08008741 noteStartSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008742 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07008743
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008744 public void noteStopGps(long elapsedRealtimeMs) {
Bookatz867c0d72017-03-07 18:23:42 -08008745 noteStopSensor(Sensor.GPS, elapsedRealtimeMs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008746 }
8747
8748 public BatteryStatsImpl getBatteryStats() {
Joe Onoratoabded112016-02-08 16:49:39 -08008749 return mBsi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008750 }
8751 }
8752
Sudheer Shanka9b735c52017-05-09 18:26:18 -07008753 public long[] getCpuFreqs() {
8754 return mCpuFreqs;
8755 }
8756
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07008757 public BatteryStatsImpl(File systemDir, Handler handler, PlatformIdleStateCallback cb,
8758 UserInfoProvider userInfoProvider) {
8759 this(new SystemClocks(), systemDir, handler, cb, userInfoProvider);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07008760 }
8761
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07008762 private BatteryStatsImpl(Clocks clocks, File systemDir, Handler handler,
8763 PlatformIdleStateCallback cb,
8764 UserInfoProvider userInfoProvider) {
Joe Onoratoabded112016-02-08 16:49:39 -08008765 init(clocks);
8766
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07008767 if (systemDir != null) {
8768 mFile = new JournaledFile(new File(systemDir, "batterystats.bin"),
8769 new File(systemDir, "batterystats.bin.tmp"));
8770 } else {
8771 mFile = null;
8772 }
8773 mCheckinFile = new AtomicFile(new File(systemDir, "batterystats-checkin.bin"));
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008774 mDailyFile = new AtomicFile(new File(systemDir, "batterystats-daily.xml"));
Jeff Brown6f357d32014-01-15 20:40:55 -08008775 mHandler = new MyHandler(handler.getLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 mStartCount++;
Joe Onoratoabded112016-02-08 16:49:39 -08008777 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase);
Dianne Hackborn617f8772009-03-31 15:04:46 -07008778 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008779 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008780 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07008781 }
Joe Onoratoabded112016-02-08 16:49:39 -08008782 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase);
8783 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
8784 mOnBatteryTimeBase);
8785 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -11, null,
8786 mOnBatteryTimeBase);
8787 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
8788 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null, mOnBatteryTimeBase);
8789 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase);
8790 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase);
8791 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
8792 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i, null,
8793 mOnBatteryTimeBase);
8794 }
8795 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
8796 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07008797 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008798 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i, null,
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008799 mOnBatteryTimeBase);
Dianne Hackborn627bba72009-03-24 22:32:56 -07008800 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008801 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008802 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
8803 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07008804 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08008805 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase, NUM_WIFI_TX_LEVELS);
8806 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
8807 NUM_BT_TX_LEVELS);
8808 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
8809 ModemActivityInfo.TX_POWER_LEVELS);
Joe Onoratoabded112016-02-08 16:49:39 -08008810 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null, mOnBatteryTimeBase);
8811 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
8812 mOnBatteryTimeBase);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07008813 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008814 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase);
8815 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase);
Joe Onoratoabded112016-02-08 16:49:39 -08008816 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase);
8817 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null, mOnBatteryTimeBase);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08008818 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -08008819 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i, null,
Dianne Hackborn3251b902014-06-20 14:40:53 -07008820 mOnBatteryTimeBase);
8821 }
Joe Onoratoabded112016-02-08 16:49:39 -08008822 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
8823 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i, null,
8824 mOnBatteryTimeBase);
8825 }
8826 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
8827 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i, null,
8828 mOnBatteryTimeBase);
8829 }
8830 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
8831 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
8832 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase);
8833 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase);
8834 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase);
Adam Lesinski3ee3f632016-06-08 13:55:55 -07008835 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryScreenOffTimeBase);
8836 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008837 mOnBattery = mOnBatteryInternal = false;
Joe Onoratoabded112016-02-08 16:49:39 -08008838 long uptime = mClocks.uptimeMillis() * 1000;
8839 long realtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08008840 initTimes(uptime, realtime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -07008841 mStartPlatformVersion = mEndPlatformVersion = Build.ID;
Evan Millar633a1742009-04-02 16:36:33 -07008842 mDischargeStartLevel = 0;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07008843 mDischargeUnplugLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07008844 mDischargePlugLevel = -1;
Evan Millar633a1742009-04-02 16:36:33 -07008845 mDischargeCurrentLevel = 0;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07008846 mCurrentBatteryLevel = 0;
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08008847 initDischarge();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008848 clearHistoryLocked();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008849 updateDailyDeadlineLocked();
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07008850 mPlatformIdleStateCallback = cb;
Suprabh Shuklae6e723d2017-06-14 16:14:43 -07008851 mUserInfoProvider = userInfoProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008852 }
8853
8854 public BatteryStatsImpl(Parcel p) {
Joe Onoratoabded112016-02-08 16:49:39 -08008855 this(new SystemClocks(), p);
8856 }
8857
8858 public BatteryStatsImpl(Clocks clocks, Parcel p) {
8859 init(clocks);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008860 mFile = null;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07008861 mCheckinFile = null;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008862 mDailyFile = null;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07008863 mHandler = null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07008864 mExternalSync = null;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07008865 clearHistoryLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 readFromParcel(p);
Badhri Jagan Sridharan68cdf192016-04-03 21:57:15 -07008867 mPlatformIdleStateCallback = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008868 }
8869
Adam Lesinski14ae39a2017-05-26 11:50:40 -07008870 public void setPowerProfileLocked(PowerProfile profile) {
8871 mPowerProfile = profile;
Adam Lesinski6832f392015-09-05 18:05:40 -07008872
Adam Lesinski14ae39a2017-05-26 11:50:40 -07008873 // We need to initialize the KernelCpuSpeedReaders to read from
8874 // the first cpu of each core. Once we have the PowerProfile, we have access to this
8875 // information.
8876 final int numClusters = mPowerProfile.getNumCpuClusters();
8877 mKernelCpuSpeedReaders = new KernelCpuSpeedReader[numClusters];
8878 int firstCpuOfCluster = 0;
8879 for (int i = 0; i < numClusters; i++) {
8880 final int numSpeedSteps = mPowerProfile.getNumSpeedStepsInCpuCluster(i);
8881 mKernelCpuSpeedReaders[i] = new KernelCpuSpeedReader(firstCpuOfCluster,
8882 numSpeedSteps);
8883 firstCpuOfCluster += mPowerProfile.getNumCoresInCpuCluster(i);
8884 }
Adam Lesinskif9b20a92016-06-17 17:30:01 -07008885
Adam Lesinski14ae39a2017-05-26 11:50:40 -07008886 if (mEstimatedBatteryCapacity == -1) {
8887 // Initialize the estimated battery capacity to a known preset one.
8888 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
Adam Lesinskie08af192015-03-25 16:42:59 -07008889 }
8890 }
8891
Dianne Hackborn0d903a82010-09-07 23:51:03 -07008892 public void setCallback(BatteryCallback cb) {
8893 mCallback = cb;
8894 }
8895
Adam Lesinski14ae39a2017-05-26 11:50:40 -07008896 public void setRadioScanningTimeoutLocked(long timeout) {
Amith Yamasanif37447b2009-10-08 18:28:01 -07008897 if (mPhoneSignalScanningTimer != null) {
8898 mPhoneSignalScanningTimer.setTimeout(timeout);
8899 }
8900 }
8901
Adam Lesinskib3a1bad2017-05-26 11:50:40 -07008902 public void setExternalStatsSyncLocked(ExternalStatsSync sync) {
8903 mExternalSync = sync;
8904 }
8905
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008906 public void updateDailyDeadlineLocked() {
8907 // Get the current time.
8908 long currentTime = mDailyStartTime = System.currentTimeMillis();
8909 Calendar calDeadline = Calendar.getInstance();
8910 calDeadline.setTimeInMillis(currentTime);
8911
8912 // Move time up to the next day, ranging from 1am to 3pm.
8913 calDeadline.set(Calendar.DAY_OF_YEAR, calDeadline.get(Calendar.DAY_OF_YEAR) + 1);
8914 calDeadline.set(Calendar.MILLISECOND, 0);
8915 calDeadline.set(Calendar.SECOND, 0);
8916 calDeadline.set(Calendar.MINUTE, 0);
8917 calDeadline.set(Calendar.HOUR_OF_DAY, 1);
8918 mNextMinDailyDeadline = calDeadline.getTimeInMillis();
8919 calDeadline.set(Calendar.HOUR_OF_DAY, 3);
8920 mNextMaxDailyDeadline = calDeadline.getTimeInMillis();
8921 }
8922
8923 public void recordDailyStatsIfNeededLocked(boolean settled) {
8924 long currentTime = System.currentTimeMillis();
8925 if (currentTime >= mNextMaxDailyDeadline) {
8926 recordDailyStatsLocked();
8927 } else if (settled && currentTime >= mNextMinDailyDeadline) {
8928 recordDailyStatsLocked();
8929 } else if (currentTime < (mDailyStartTime-(1000*60*60*24))) {
8930 recordDailyStatsLocked();
8931 }
8932 }
8933
8934 public void recordDailyStatsLocked() {
8935 DailyItem item = new DailyItem();
8936 item.mStartTime = mDailyStartTime;
8937 item.mEndTime = System.currentTimeMillis();
8938 boolean hasData = false;
8939 if (mDailyDischargeStepTracker.mNumStepDurations > 0) {
8940 hasData = true;
8941 item.mDischargeSteps = new LevelStepTracker(
8942 mDailyDischargeStepTracker.mNumStepDurations,
8943 mDailyDischargeStepTracker.mStepDurations);
8944 }
8945 if (mDailyChargeStepTracker.mNumStepDurations > 0) {
8946 hasData = true;
8947 item.mChargeSteps = new LevelStepTracker(
8948 mDailyChargeStepTracker.mNumStepDurations,
8949 mDailyChargeStepTracker.mStepDurations);
8950 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07008951 if (mDailyPackageChanges != null) {
8952 hasData = true;
8953 item.mPackageChanges = mDailyPackageChanges;
8954 mDailyPackageChanges = null;
8955 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008956 mDailyDischargeStepTracker.init();
8957 mDailyChargeStepTracker.init();
8958 updateDailyDeadlineLocked();
8959
8960 if (hasData) {
8961 mDailyItems.add(item);
8962 while (mDailyItems.size() > MAX_DAILY_ITEMS) {
8963 mDailyItems.remove(0);
8964 }
8965 final ByteArrayOutputStream memStream = new ByteArrayOutputStream();
8966 try {
8967 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01008968 out.setOutput(memStream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08008969 writeDailyItemsLocked(out);
8970 BackgroundThread.getHandler().post(new Runnable() {
8971 @Override
8972 public void run() {
8973 synchronized (mCheckinFile) {
8974 FileOutputStream stream = null;
8975 try {
8976 stream = mDailyFile.startWrite();
8977 memStream.writeTo(stream);
8978 stream.flush();
8979 FileUtils.sync(stream);
8980 stream.close();
8981 mDailyFile.finishWrite(stream);
8982 } catch (IOException e) {
8983 Slog.w("BatteryStats",
8984 "Error writing battery daily items", e);
8985 mDailyFile.failWrite(stream);
8986 }
8987 }
8988 }
8989 });
8990 } catch (IOException e) {
8991 }
8992 }
8993 }
8994
8995 private void writeDailyItemsLocked(XmlSerializer out) throws IOException {
8996 StringBuilder sb = new StringBuilder(64);
8997 out.startDocument(null, true);
8998 out.startTag(null, "daily-items");
8999 for (int i=0; i<mDailyItems.size(); i++) {
9000 final DailyItem dit = mDailyItems.get(i);
9001 out.startTag(null, "item");
9002 out.attribute(null, "start", Long.toString(dit.mStartTime));
9003 out.attribute(null, "end", Long.toString(dit.mEndTime));
9004 writeDailyLevelSteps(out, "dis", dit.mDischargeSteps, sb);
9005 writeDailyLevelSteps(out, "chg", dit.mChargeSteps, sb);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07009006 if (dit.mPackageChanges != null) {
9007 for (int j=0; j<dit.mPackageChanges.size(); j++) {
9008 PackageChange pc = dit.mPackageChanges.get(j);
9009 if (pc.mUpdate) {
9010 out.startTag(null, "upd");
9011 out.attribute(null, "pkg", pc.mPackageName);
9012 out.attribute(null, "ver", Integer.toString(pc.mVersionCode));
9013 out.endTag(null, "upd");
9014 } else {
9015 out.startTag(null, "rem");
9016 out.attribute(null, "pkg", pc.mPackageName);
9017 out.endTag(null, "rem");
9018 }
9019 }
9020 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009021 out.endTag(null, "item");
9022 }
9023 out.endTag(null, "daily-items");
9024 out.endDocument();
9025 }
9026
9027 private void writeDailyLevelSteps(XmlSerializer out, String tag, LevelStepTracker steps,
9028 StringBuilder tmpBuilder) throws IOException {
9029 if (steps != null) {
9030 out.startTag(null, tag);
9031 out.attribute(null, "n", Integer.toString(steps.mNumStepDurations));
9032 for (int i=0; i<steps.mNumStepDurations; i++) {
9033 out.startTag(null, "s");
9034 tmpBuilder.setLength(0);
9035 steps.encodeEntryAt(i, tmpBuilder);
9036 out.attribute(null, "v", tmpBuilder.toString());
9037 out.endTag(null, "s");
9038 }
9039 out.endTag(null, tag);
9040 }
9041 }
9042
9043 public void readDailyStatsLocked() {
9044 Slog.d(TAG, "Reading daily items from " + mDailyFile.getBaseFile());
9045 mDailyItems.clear();
9046 FileInputStream stream;
9047 try {
9048 stream = mDailyFile.openRead();
9049 } catch (FileNotFoundException e) {
9050 return;
9051 }
9052 try {
9053 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01009054 parser.setInput(stream, StandardCharsets.UTF_8.name());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009055 readDailyItemsLocked(parser);
9056 } catch (XmlPullParserException e) {
9057 } finally {
9058 try {
9059 stream.close();
9060 } catch (IOException e) {
9061 }
9062 }
9063 }
9064
9065 private void readDailyItemsLocked(XmlPullParser parser) {
9066 try {
9067 int type;
9068 while ((type = parser.next()) != XmlPullParser.START_TAG
9069 && type != XmlPullParser.END_DOCUMENT) {
9070 ;
9071 }
9072
9073 if (type != XmlPullParser.START_TAG) {
9074 throw new IllegalStateException("no start tag found");
9075 }
9076
9077 int outerDepth = parser.getDepth();
9078 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
9079 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
9080 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
9081 continue;
9082 }
9083
9084 String tagName = parser.getName();
9085 if (tagName.equals("item")) {
9086 readDailyItemTagLocked(parser);
9087 } else {
9088 Slog.w(TAG, "Unknown element under <daily-items>: "
9089 + parser.getName());
9090 XmlUtils.skipCurrentTag(parser);
9091 }
9092 }
9093
9094 } catch (IllegalStateException e) {
9095 Slog.w(TAG, "Failed parsing daily " + e);
9096 } catch (NullPointerException e) {
9097 Slog.w(TAG, "Failed parsing daily " + e);
9098 } catch (NumberFormatException e) {
9099 Slog.w(TAG, "Failed parsing daily " + e);
9100 } catch (XmlPullParserException e) {
9101 Slog.w(TAG, "Failed parsing daily " + e);
9102 } catch (IOException e) {
9103 Slog.w(TAG, "Failed parsing daily " + e);
9104 } catch (IndexOutOfBoundsException e) {
9105 Slog.w(TAG, "Failed parsing daily " + e);
9106 }
9107 }
9108
9109 void readDailyItemTagLocked(XmlPullParser parser) throws NumberFormatException,
9110 XmlPullParserException, IOException {
9111 DailyItem dit = new DailyItem();
9112 String attr = parser.getAttributeValue(null, "start");
9113 if (attr != null) {
9114 dit.mStartTime = Long.parseLong(attr);
9115 }
9116 attr = parser.getAttributeValue(null, "end");
9117 if (attr != null) {
9118 dit.mEndTime = Long.parseLong(attr);
9119 }
9120 int outerDepth = parser.getDepth();
9121 int type;
9122 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
9123 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
9124 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
9125 continue;
9126 }
9127
9128 String tagName = parser.getName();
9129 if (tagName.equals("dis")) {
9130 readDailyItemTagDetailsLocked(parser, dit, false, "dis");
9131 } else if (tagName.equals("chg")) {
9132 readDailyItemTagDetailsLocked(parser, dit, true, "chg");
Dianne Hackborn88e98df2015-03-23 13:29:14 -07009133 } else if (tagName.equals("upd")) {
9134 if (dit.mPackageChanges == null) {
9135 dit.mPackageChanges = new ArrayList<>();
9136 }
9137 PackageChange pc = new PackageChange();
9138 pc.mUpdate = true;
9139 pc.mPackageName = parser.getAttributeValue(null, "pkg");
9140 String verStr = parser.getAttributeValue(null, "ver");
9141 pc.mVersionCode = verStr != null ? Integer.parseInt(verStr) : 0;
9142 dit.mPackageChanges.add(pc);
9143 XmlUtils.skipCurrentTag(parser);
9144 } else if (tagName.equals("rem")) {
9145 if (dit.mPackageChanges == null) {
9146 dit.mPackageChanges = new ArrayList<>();
9147 }
9148 PackageChange pc = new PackageChange();
9149 pc.mUpdate = false;
9150 pc.mPackageName = parser.getAttributeValue(null, "pkg");
9151 dit.mPackageChanges.add(pc);
9152 XmlUtils.skipCurrentTag(parser);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009153 } else {
9154 Slog.w(TAG, "Unknown element under <item>: "
9155 + parser.getName());
9156 XmlUtils.skipCurrentTag(parser);
9157 }
9158 }
9159 mDailyItems.add(dit);
9160 }
9161
9162 void readDailyItemTagDetailsLocked(XmlPullParser parser, DailyItem dit, boolean isCharge,
9163 String tag)
9164 throws NumberFormatException, XmlPullParserException, IOException {
9165 final String numAttr = parser.getAttributeValue(null, "n");
9166 if (numAttr == null) {
9167 Slog.w(TAG, "Missing 'n' attribute at " + parser.getPositionDescription());
9168 XmlUtils.skipCurrentTag(parser);
9169 return;
9170 }
9171 final int num = Integer.parseInt(numAttr);
9172 LevelStepTracker steps = new LevelStepTracker(num);
9173 if (isCharge) {
9174 dit.mChargeSteps = steps;
9175 } else {
9176 dit.mDischargeSteps = steps;
9177 }
9178 int i = 0;
9179 int outerDepth = parser.getDepth();
9180 int type;
9181 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
9182 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
9183 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
9184 continue;
9185 }
9186
9187 String tagName = parser.getName();
9188 if ("s".equals(tagName)) {
9189 if (i < num) {
9190 String valueAttr = parser.getAttributeValue(null, "v");
9191 if (valueAttr != null) {
9192 steps.decodeEntryAt(i, valueAttr);
9193 i++;
9194 }
9195 }
9196 } else {
9197 Slog.w(TAG, "Unknown element under <" + tag + ">: "
9198 + parser.getName());
9199 XmlUtils.skipCurrentTag(parser);
9200 }
9201 }
9202 steps.mNumStepDurations = i;
9203 }
9204
9205 @Override
9206 public DailyItem getDailyItemLocked(int daysAgo) {
9207 int index = mDailyItems.size()-1-daysAgo;
9208 return index >= 0 ? mDailyItems.get(index) : null;
9209 }
9210
9211 @Override
9212 public long getCurrentDailyStartTime() {
9213 return mDailyStartTime;
9214 }
9215
9216 @Override
9217 public long getNextMinDailyDeadline() {
9218 return mNextMinDailyDeadline;
9219 }
9220
9221 @Override
9222 public long getNextMaxDailyDeadline() {
9223 return mNextMaxDailyDeadline;
9224 }
9225
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009226 @Override
9227 public boolean startIteratingOldHistoryLocked() {
9228 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
9229 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009230 if ((mHistoryIterator = mHistory) == null) {
9231 return false;
9232 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009233 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn1fadab52011-04-14 17:57:33 -07009234 mHistoryReadTmp.clear();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009235 mReadOverflow = false;
9236 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009237 return true;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07009238 }
9239
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009240 @Override
9241 public boolean getNextOldHistoryLocked(HistoryItem out) {
9242 boolean end = mHistoryBuffer.dataPosition() >= mHistoryBuffer.dataSize();
9243 if (!end) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08009244 readHistoryDelta(mHistoryBuffer, mHistoryReadTmp);
Dianne Hackborn1fadab52011-04-14 17:57:33 -07009245 mReadOverflow |= mHistoryReadTmp.cmd == HistoryItem.CMD_OVERFLOW;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009246 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -07009247 HistoryItem cur = mHistoryIterator;
9248 if (cur == null) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009249 if (!mReadOverflow && !end) {
9250 Slog.w(TAG, "Old history ends before new history!");
9251 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -07009252 return false;
9253 }
9254 out.setTo(cur);
9255 mHistoryIterator = cur.next;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009256 if (!mReadOverflow) {
9257 if (end) {
9258 Slog.w(TAG, "New history ends before old history!");
Dianne Hackborn1fadab52011-04-14 17:57:33 -07009259 } else if (!out.same(mHistoryReadTmp)) {
Dianne Hackborn8c841092013-06-24 13:46:13 -07009260 PrintWriter pw = new FastPrintWriter(new LogWriter(android.util.Log.WARN, TAG));
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009261 pw.println("Histories differ!");
9262 pw.println("Old history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -07009263 (new HistoryPrinter()).printNextItem(pw, out, 0, false, true);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009264 pw.println("New history:");
Dianne Hackborn99009ea2014-04-18 16:23:42 -07009265 (new HistoryPrinter()).printNextItem(pw, mHistoryReadTmp, 0, false,
9266 true);
Dianne Hackborn8c841092013-06-24 13:46:13 -07009267 pw.flush();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009268 }
9269 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -07009270 return true;
9271 }
9272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009274 public void finishIteratingOldHistoryLocked() {
9275 mIteratingHistory = false;
9276 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009277 mHistoryIterator = null;
9278 }
9279
9280 public int getHistoryTotalSize() {
9281 return MAX_HISTORY_BUFFER;
9282 }
9283
9284 public int getHistoryUsedSize() {
9285 return mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009286 }
9287
9288 @Override
9289 public boolean startIteratingHistoryLocked() {
9290 if (DEBUG_HISTORY) Slog.i(TAG, "ITERATING: buff size=" + mHistoryBuffer.dataSize()
9291 + " pos=" + mHistoryBuffer.dataPosition());
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009292 if (mHistoryBuffer.dataSize() <= 0) {
9293 return false;
9294 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009295 mHistoryBuffer.setDataPosition(0);
9296 mReadOverflow = false;
9297 mIteratingHistory = true;
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009298 mReadHistoryStrings = new String[mHistoryTagPool.size()];
9299 mReadHistoryUids = new int[mHistoryTagPool.size()];
9300 mReadHistoryChars = 0;
9301 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
9302 final HistoryTag tag = ent.getKey();
9303 final int idx = ent.getValue();
9304 mReadHistoryStrings[idx] = tag.string;
9305 mReadHistoryUids[idx] = tag.uid;
9306 mReadHistoryChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -08009307 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009308 return true;
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009309 }
9310
9311 @Override
Dianne Hackborn099bc622014-01-22 13:39:16 -08009312 public int getHistoryStringPoolSize() {
9313 return mReadHistoryStrings.length;
9314 }
9315
9316 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009317 public int getHistoryStringPoolBytes() {
9318 // Each entry is a fixed 12 bytes: 4 for index, 4 for uid, 4 for string size
9319 // Each string character is 2 bytes.
9320 return (mReadHistoryStrings.length * 12) + (mReadHistoryChars * 2);
9321 }
9322
9323 @Override
9324 public String getHistoryTagPoolString(int index) {
Dianne Hackborn099bc622014-01-22 13:39:16 -08009325 return mReadHistoryStrings[index];
9326 }
9327
9328 @Override
Dianne Hackborn71fc13e2014-02-03 10:50:53 -08009329 public int getHistoryTagPoolUid(int index) {
9330 return mReadHistoryUids[index];
9331 }
9332
9333 @Override
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009334 public boolean getNextHistoryLocked(HistoryItem out) {
Dianne Hackborn1fadab52011-04-14 17:57:33 -07009335 final int pos = mHistoryBuffer.dataPosition();
9336 if (pos == 0) {
9337 out.clear();
9338 }
9339 boolean end = pos >= mHistoryBuffer.dataSize();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009340 if (end) {
9341 return false;
9342 }
9343
Dianne Hackborn99009ea2014-04-18 16:23:42 -07009344 final long lastRealtime = out.time;
9345 final long lastWalltime = out.currentTime;
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08009346 readHistoryDelta(mHistoryBuffer, out);
Dianne Hackborn37de0982014-05-09 09:32:18 -07009347 if (out.cmd != HistoryItem.CMD_CURRENT_TIME
9348 && out.cmd != HistoryItem.CMD_RESET && lastWalltime != 0) {
Dianne Hackborn99009ea2014-04-18 16:23:42 -07009349 out.currentTime = lastWalltime + (out.time - lastRealtime);
9350 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -07009351 return true;
9352 }
9353
9354 @Override
9355 public void finishIteratingHistoryLocked() {
9356 mIteratingHistory = false;
9357 mHistoryBuffer.setDataPosition(mHistoryBuffer.dataSize());
Dianne Hackborn099bc622014-01-22 13:39:16 -08009358 mReadHistoryStrings = null;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009359 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009360
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009361 @Override
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009362 public long getHistoryBaseTime() {
9363 return mHistoryBaseTime;
9364 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009365
Dianne Hackbornb5e31652010-09-07 12:13:55 -07009366 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009367 public int getStartCount() {
9368 return mStartCount;
9369 }
9370
9371 public boolean isOnBattery() {
9372 return mOnBattery;
9373 }
9374
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07009375 public boolean isCharging() {
9376 return mCharging;
9377 }
9378
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009379 public boolean isScreenOn() {
Jeff Browne95c3cd2014-05-02 16:59:26 -07009380 return mScreenState == Display.STATE_ON;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07009381 }
9382
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009383 void initTimes(long uptime, long realtime) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -08009384 mStartClockTime = System.currentTimeMillis();
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009385 mOnBatteryTimeBase.init(uptime, realtime);
9386 mOnBatteryScreenOffTimeBase.init(uptime, realtime);
Dianne Hackborn4590e522014-03-24 13:36:46 -07009387 mRealtime = 0;
9388 mUptime = 0;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009389 mRealtimeStart = realtime;
Dianne Hackborn4590e522014-03-24 13:36:46 -07009390 mUptimeStart = uptime;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009391 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009392
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009393 void initDischarge() {
9394 mLowDischargeAmountSinceCharge = 0;
9395 mHighDischargeAmountSinceCharge = 0;
9396 mDischargeAmountScreenOn = 0;
9397 mDischargeAmountScreenOnSinceCharge = 0;
9398 mDischargeAmountScreenOff = 0;
9399 mDischargeAmountScreenOffSinceCharge = 0;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -08009400 mDischargeStepTracker.init();
9401 mChargeStepTracker.init();
Adam Lesinski3ee3f632016-06-08 13:55:55 -07009402 mDischargeScreenOffCounter.reset(false);
9403 mDischargeCounter.reset(false);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009404 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009405
9406 public void resetAllStatsCmdLocked() {
9407 resetAllStatsLocked();
Joe Onoratoabded112016-02-08 16:49:39 -08009408 final long mSecUptime = mClocks.uptimeMillis();
Dianne Hackborn40c87252014-03-19 16:55:40 -07009409 long uptime = mSecUptime * 1000;
Joe Onoratoabded112016-02-08 16:49:39 -08009410 long mSecRealtime = mClocks.elapsedRealtime();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009411 long realtime = mSecRealtime * 1000;
9412 mDischargeStartLevel = mHistoryCur.batteryLevel;
9413 pullPendingStateUpdatesLocked();
Dianne Hackborn40c87252014-03-19 16:55:40 -07009414 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07009415 mDischargeCurrentLevel = mDischargeUnplugLevel = mDischargePlugLevel
9416 = mCurrentBatteryLevel = mHistoryCur.batteryLevel;
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009417 mOnBatteryTimeBase.reset(uptime, realtime);
9418 mOnBatteryScreenOffTimeBase.reset(uptime, realtime);
9419 if ((mHistoryCur.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) == 0) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07009420 if (mScreenState == Display.STATE_ON) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009421 mDischargeScreenOnUnplugLevel = mHistoryCur.batteryLevel;
9422 mDischargeScreenOffUnplugLevel = 0;
9423 } else {
9424 mDischargeScreenOnUnplugLevel = 0;
9425 mDischargeScreenOffUnplugLevel = mHistoryCur.batteryLevel;
9426 }
9427 mDischargeAmountScreenOn = 0;
9428 mDischargeAmountScreenOff = 0;
9429 }
Dianne Hackborn40c87252014-03-19 16:55:40 -07009430 initActiveHistoryEventsLocked(mSecRealtime, mSecUptime);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08009431 }
9432
9433 private void resetAllStatsLocked() {
Adam Lesinski8ce36942016-05-26 16:05:35 -07009434 final long uptimeMillis = mClocks.uptimeMillis();
9435 final long elapsedRealtimeMillis = mClocks.elapsedRealtime();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009436 mStartCount = 0;
Adam Lesinski8ce36942016-05-26 16:05:35 -07009437 initTimes(uptimeMillis * 1000, elapsedRealtimeMillis * 1000);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009438 mScreenOnTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009439 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009440 mScreenBrightnessTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009441 }
Adam Lesinski1a76a622016-06-22 10:28:47 -07009442
9443 if (mPowerProfile != null) {
9444 mEstimatedBatteryCapacity = (int) mPowerProfile.getBatteryCapacity();
9445 } else {
9446 mEstimatedBatteryCapacity = -1;
9447 }
Jocelyn Dangc627d102017-04-14 13:15:14 -07009448 mMinLearnedBatteryCapacity = -1;
9449 mMaxLearnedBatteryCapacity = -1;
Jeff Browne95c3cd2014-05-02 16:59:26 -07009450 mInteractiveTimer.reset(false);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07009451 mPowerSaveModeEnabledTimer.reset(false);
Adam Lesinski8ce36942016-05-26 16:05:35 -07009452 mLastIdleTimeStart = elapsedRealtimeMillis;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07009453 mLongestLightIdleTime = 0;
9454 mLongestFullIdleTime = 0;
9455 mDeviceIdleModeLightTimer.reset(false);
9456 mDeviceIdleModeFullTimer.reset(false);
9457 mDeviceLightIdlingTimer.reset(false);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07009458 mDeviceIdlingTimer.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009459 mPhoneOnTimer.reset(false);
9460 mAudioOnTimer.reset(false);
9461 mVideoOnTimer.reset(false);
Dianne Hackbornabc7c492014-06-30 16:57:46 -07009462 mFlashlightOnTimer.reset(false);
Ruben Brunk6d2c3632015-05-26 17:32:16 -07009463 mCameraOnTimer.reset(false);
Adam Lesinski9f55cc72016-01-27 20:42:14 -08009464 mBluetoothScanTimer.reset(false);
Wink Saville52840902011-02-18 12:40:47 -08009465 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009466 mPhoneSignalStrengthsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009467 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009468 mPhoneSignalScanningTimer.reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009469 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009470 mPhoneDataConnectionsTimer[i].reset(false);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009471 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009472 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -08009473 mNetworkByteActivityCounters[i].reset(false);
9474 mNetworkPacketActivityCounters[i].reset(false);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -07009475 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009476 mMobileRadioActiveTimer.reset(false);
9477 mMobileRadioActivePerAppTimer.reset(false);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009478 mMobileRadioActiveAdjustedTime.reset(false);
Dianne Hackbornd45665b2014-02-26 12:35:32 -08009479 mMobileRadioActiveUnknownTime.reset(false);
9480 mMobileRadioActiveUnknownCount.reset(false);
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009481 mWifiOnTimer.reset(false);
9482 mGlobalWifiRunningTimer.reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08009483 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009484 mWifiStateTimer[i].reset(false);
Dianne Hackbornca1bf212014-02-14 14:18:36 -08009485 }
Dianne Hackborn3251b902014-06-20 14:40:53 -07009486 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
9487 mWifiSupplStateTimer[i].reset(false);
9488 }
9489 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
9490 mWifiSignalStrengthsTimer[i].reset(false);
9491 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009492 mWifiActivity.reset(false);
9493 mBluetoothActivity.reset(false);
9494 mModemActivity.reset(false);
Dianne Hackborn1e01d162014-12-04 17:46:42 -08009495 mNumConnectivityChange = mLoadedNumConnectivityChange = mUnpluggedNumConnectivityChange = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009496
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009497 for (int i=0; i<mUidStats.size(); i++) {
Bookatz993a0be2017-07-21 09:03:23 -07009498 if (mUidStats.valueAt(i).reset(uptimeMillis * 1000, elapsedRealtimeMillis * 1000)) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009499 mUidStats.remove(mUidStats.keyAt(i));
9500 i--;
9501 }
9502 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009503
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009504 if (mKernelWakelockStats.size() > 0) {
9505 for (SamplingTimer timer : mKernelWakelockStats.values()) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -08009506 mOnBatteryScreenOffTimeBase.remove(timer);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009507 }
9508 mKernelWakelockStats.clear();
9509 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009510
James Carr3a226052016-07-01 14:49:52 -07009511 if (mKernelMemoryStats.size() > 0) {
9512 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
9513 mOnBatteryTimeBase.remove(mKernelMemoryStats.valueAt(i));
9514 }
9515 mKernelMemoryStats.clear();
9516 }
9517
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009518 if (mWakeupReasonStats.size() > 0) {
Dianne Hackbornc3940bc2014-09-05 15:50:25 -07009519 for (SamplingTimer timer : mWakeupReasonStats.values()) {
9520 mOnBatteryTimeBase.remove(timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -07009521 }
9522 mWakeupReasonStats.clear();
9523 }
9524
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -08009525 mLastHistoryStepDetails = null;
9526 mLastStepCpuUserTime = mLastStepCpuSystemTime = 0;
9527 mCurStepCpuUserTime = mCurStepCpuSystemTime = 0;
9528 mLastStepCpuUserTime = mCurStepCpuUserTime = 0;
9529 mLastStepCpuSystemTime = mCurStepCpuSystemTime = 0;
9530 mLastStepStatUserTime = mCurStepStatUserTime = 0;
9531 mLastStepStatSystemTime = mCurStepStatSystemTime = 0;
9532 mLastStepStatIOWaitTime = mCurStepStatIOWaitTime = 0;
9533 mLastStepStatIrqTime = mCurStepStatIrqTime = 0;
9534 mLastStepStatSoftIrqTime = mCurStepStatSoftIrqTime = 0;
9535 mLastStepStatIdleTime = mCurStepStatIdleTime = 0;
9536
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009537 initDischarge();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009538
Dianne Hackborn6b7b4842010-06-14 17:17:44 -07009539 clearHistoryLocked();
9540 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -07009541
Dianne Hackborn40c87252014-03-19 16:55:40 -07009542 private void initActiveHistoryEventsLocked(long elapsedRealtimeMs, long uptimeMs) {
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009543 for (int i=0; i<HistoryItem.EVENT_COUNT; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -07009544 if (!mRecordAllHistory && i == HistoryItem.EVENT_PROC) {
9545 // Not recording process starts/stops.
9546 continue;
9547 }
Dianne Hackborn37de0982014-05-09 09:32:18 -07009548 HashMap<String, SparseIntArray> active = mActiveEvents.getStateForEvent(i);
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009549 if (active == null) {
9550 continue;
9551 }
Dianne Hackborn37de0982014-05-09 09:32:18 -07009552 for (HashMap.Entry<String, SparseIntArray> ent : active.entrySet()) {
9553 SparseIntArray uids = ent.getValue();
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009554 for (int j=0; j<uids.size(); j++) {
Dianne Hackborn37de0982014-05-09 09:32:18 -07009555 addHistoryEventLocked(elapsedRealtimeMs, uptimeMs, i, ent.getKey(),
9556 uids.keyAt(j));
Dianne Hackborneaf2ac42014-02-07 13:01:07 -08009557 }
9558 }
9559 }
9560 }
9561
Dianne Hackborn32de2f62011-03-09 14:03:35 -08009562 void updateDischargeScreenLevelsLocked(boolean oldScreenOn, boolean newScreenOn) {
Dianne Hackbornc1b40e32011-01-05 18:27:40 -08009563 if (oldScreenOn) {
9564 int diff = mDischargeScreenOnUnplugLevel - mDischargeCurrentLevel;
9565 if (diff > 0) {
9566 mDischargeAmountScreenOn += diff;
9567 mDischargeAmountScreenOnSinceCharge += diff;
9568 }
9569 } else {
9570 int diff = mDischargeScreenOffUnplugLevel - mDischargeCurrentLevel;
9571 if (diff > 0) {
9572 mDischargeAmountScreenOff += diff;
9573 mDischargeAmountScreenOffSinceCharge += diff;
9574 }
9575 }
9576 if (newScreenOn) {
9577 mDischargeScreenOnUnplugLevel = mDischargeCurrentLevel;
9578 mDischargeScreenOffUnplugLevel = 0;
9579 } else {
9580 mDischargeScreenOnUnplugLevel = 0;
9581 mDischargeScreenOffUnplugLevel = mDischargeCurrentLevel;
9582 }
9583 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009584
Dianne Hackborna7c837f2014-01-15 16:20:44 -08009585 public void pullPendingStateUpdatesLocked() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08009586 if (mOnBatteryInternal) {
Jeff Browne95c3cd2014-05-02 16:59:26 -07009587 final boolean screenOn = mScreenState == Display.STATE_ON;
9588 updateDischargeScreenLevelsLocked(screenOn, screenOn);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08009589 }
Dianne Hackborna7c837f2014-01-15 16:20:44 -08009590 }
9591
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009592 private final NetworkStatsFactory mNetworkStatsFactory = new NetworkStatsFactory();
9593 private final Pools.Pool<NetworkStats> mNetworkStatsPool = new Pools.SynchronizedPool<>(6);
9594
9595 private final Object mWifiNetworkLock = new Object();
9596
9597 @GuardedBy("mWifiNetworkLock")
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009598 private String[] mWifiIfaces = EmptyArray.STRING;
9599
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009600 @GuardedBy("mWifiNetworkLock")
9601 private NetworkStats mLastWifiNetworkStats = new NetworkStats(0, -1);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009602
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009603 private final Object mModemNetworkLock = new Object();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009604
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009605 @GuardedBy("mModemNetworkLock")
9606 private String[] mModemIfaces = EmptyArray.STRING;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009607
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009608 @GuardedBy("mModemNetworkLock")
9609 private NetworkStats mLastModemNetworkStats = new NetworkStats(0, -1);
9610
9611 private NetworkStats readNetworkStatsLocked(String[] ifaces) {
9612 try {
9613 if (!ArrayUtils.isEmpty(ifaces)) {
9614 return mNetworkStatsFactory.readNetworkStatsDetail(NetworkStats.UID_ALL, ifaces,
9615 NetworkStats.TAG_NONE, mNetworkStatsPool.acquire());
9616 }
9617 } catch (IOException e) {
9618 Slog.e(TAG, "failed to read network stats for ifaces: " + Arrays.toString(ifaces));
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009619 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009620 return null;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009621 }
9622
9623 /**
9624 * Distribute WiFi energy info and network traffic to apps.
9625 * @param info The energy information from the WiFi controller.
9626 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009627 public void updateWifiState(@Nullable final WifiActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009628 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009629 Slog.d(TAG, "Updating wifi stats: " + Arrays.toString(mWifiIfaces));
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009630 }
9631
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009632 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -07009633 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009634 synchronized (mWifiNetworkLock) {
9635 final NetworkStats latestStats = readNetworkStatsLocked(mWifiIfaces);
9636 if (latestStats != null) {
9637 delta = NetworkStats.subtract(latestStats, mLastWifiNetworkStats, null, null,
9638 mNetworkStatsPool.acquire());
9639 mNetworkStatsPool.release(mLastWifiNetworkStats);
9640 mLastWifiNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -07009641 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009642 }
9643
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009644 synchronized (this) {
9645 if (!mOnBatteryInternal) {
9646 if (delta != null) {
9647 mNetworkStatsPool.release(delta);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009648 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009649 return;
9650 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009651
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009652 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
9653 SparseLongArray rxPackets = new SparseLongArray();
9654 SparseLongArray txPackets = new SparseLongArray();
9655 long totalTxPackets = 0;
9656 long totalRxPackets = 0;
9657 if (delta != null) {
9658 NetworkStats.Entry entry = new NetworkStats.Entry();
9659 final int size = delta.size();
9660 for (int i = 0; i < size; i++) {
9661 entry = delta.getValues(i, entry);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009662
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009663 if (DEBUG_ENERGY) {
9664 Slog.d(TAG, "Wifi uid " + entry.uid + ": delta rx=" + entry.rxBytes
9665 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
9666 + " txPackets=" + entry.txPackets);
9667 }
9668
9669 if (entry.rxBytes == 0 && entry.txBytes == 0) {
9670 // Skip the lookup below since there is no work to do.
9671 continue;
9672 }
9673
9674 final Uid u = getUidStatsLocked(mapUid(entry.uid));
9675 if (entry.rxBytes != 0) {
9676 u.noteNetworkActivityLocked(NETWORK_WIFI_RX_DATA, entry.rxBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -08009677 entry.rxPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009678 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
9679 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_RX_DATA, entry.rxBytes,
9680 entry.rxPackets);
9681 }
9682 mNetworkByteActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
9683 entry.rxBytes);
9684 mNetworkPacketActivityCounters[NETWORK_WIFI_RX_DATA].addCountLocked(
9685 entry.rxPackets);
9686
9687 rxPackets.put(u.getUid(), entry.rxPackets);
9688
9689 // Sum the total number of packets so that the Rx Power can
9690 // be evenly distributed amongst the apps.
9691 totalRxPackets += entry.rxPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -08009692 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009693
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009694 if (entry.txBytes != 0) {
9695 u.noteNetworkActivityLocked(NETWORK_WIFI_TX_DATA, entry.txBytes,
Amith Yamasani59fe8412017-03-03 16:28:52 -08009696 entry.txPackets);
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009697 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
9698 u.noteNetworkActivityLocked(NETWORK_WIFI_BG_TX_DATA, entry.txBytes,
9699 entry.txPackets);
9700 }
9701 mNetworkByteActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
9702 entry.txBytes);
9703 mNetworkPacketActivityCounters[NETWORK_WIFI_TX_DATA].addCountLocked(
9704 entry.txPackets);
9705
9706 txPackets.put(u.getUid(), entry.txPackets);
9707
9708 // Sum the total number of packets so that the Tx Power can
9709 // be evenly distributed amongst the apps.
9710 totalTxPackets += entry.txPackets;
Amith Yamasani59fe8412017-03-03 16:28:52 -08009711 }
Adam Lesinskiba88e682015-12-08 12:06:55 -08009712 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009713 mNetworkStatsPool.release(delta);
9714 delta = null;
Adam Lesinskie08af192015-03-25 16:42:59 -07009715 }
9716
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009717 if (info != null) {
9718 mHasWifiReporting = true;
Adam Lesinskie08af192015-03-25 16:42:59 -07009719
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009720 // Measured in mAms
9721 final long txTimeMs = info.getControllerTxTimeMillis();
9722 final long rxTimeMs = info.getControllerRxTimeMillis();
9723 final long idleTimeMs = info.getControllerIdleTimeMillis();
9724 final long totalTimeMs = txTimeMs + rxTimeMs + idleTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -07009725
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009726 long leftOverRxTimeMs = rxTimeMs;
9727 long leftOverTxTimeMs = txTimeMs;
Adam Lesinskie08af192015-03-25 16:42:59 -07009728
Adam Lesinskie08af192015-03-25 16:42:59 -07009729 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009730 Slog.d(TAG, "------ BEGIN WiFi power blaming ------");
9731 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
9732 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
9733 Slog.d(TAG, " Idle Time: " + idleTimeMs + " ms");
9734 Slog.d(TAG, " Total Time: " + totalTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -07009735 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009736
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009737 long totalWifiLockTimeMs = 0;
9738 long totalScanTimeMs = 0;
9739
9740 // On the first pass, collect some totals so that we can normalize power
9741 // calculations if we need to.
9742 final int uidStatsSize = mUidStats.size();
9743 for (int i = 0; i < uidStatsSize; i++) {
9744 final Uid uid = mUidStats.valueAt(i);
9745
9746 // Sum the total scan power for all apps.
9747 totalScanTimeMs += uid.mWifiScanTimer.getTimeSinceMarkLocked(
9748 elapsedRealtimeMs * 1000) / 1000;
9749
9750 // Sum the total time holding wifi lock for all apps.
9751 totalWifiLockTimeMs += uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
9752 elapsedRealtimeMs * 1000) / 1000;
9753 }
9754
9755 if (DEBUG_ENERGY && totalScanTimeMs > rxTimeMs) {
9756 Slog.d(TAG,
9757 " !Estimated scan time > Actual rx time (" + totalScanTimeMs + " ms > "
9758 + rxTimeMs + " ms). Normalizing scan time.");
9759 }
9760 if (DEBUG_ENERGY && totalScanTimeMs > txTimeMs) {
9761 Slog.d(TAG,
9762 " !Estimated scan time > Actual tx time (" + totalScanTimeMs + " ms > "
9763 + txTimeMs + " ms). Normalizing scan time.");
9764 }
9765
9766 // Actually assign and distribute power usage to apps.
9767 for (int i = 0; i < uidStatsSize; i++) {
9768 final Uid uid = mUidStats.valueAt(i);
9769
9770 long scanTimeSinceMarkMs = uid.mWifiScanTimer.getTimeSinceMarkLocked(
9771 elapsedRealtimeMs * 1000) / 1000;
9772 if (scanTimeSinceMarkMs > 0) {
9773 // Set the new mark so that next time we get new data since this point.
9774 uid.mWifiScanTimer.setMark(elapsedRealtimeMs);
9775
9776 long scanRxTimeSinceMarkMs = scanTimeSinceMarkMs;
9777 long scanTxTimeSinceMarkMs = scanTimeSinceMarkMs;
9778
9779 // Our total scan time is more than the reported Tx/Rx time.
9780 // This is possible because the cost of a scan is approximate.
9781 // Let's normalize the result so that we evenly blame each app
9782 // scanning.
9783 //
9784 // This means that we may have apps that transmitted/received packets not be
9785 // blamed for this, but this is fine as scans are relatively more expensive.
9786 if (totalScanTimeMs > rxTimeMs) {
9787 scanRxTimeSinceMarkMs = (rxTimeMs * scanRxTimeSinceMarkMs) /
9788 totalScanTimeMs;
9789 }
9790 if (totalScanTimeMs > txTimeMs) {
9791 scanTxTimeSinceMarkMs = (txTimeMs * scanTxTimeSinceMarkMs) /
9792 totalScanTimeMs;
9793 }
9794
9795 if (DEBUG_ENERGY) {
9796 Slog.d(TAG, " ScanTime for UID " + uid.getUid() + ": Rx:"
9797 + scanRxTimeSinceMarkMs + " ms Tx:"
9798 + scanTxTimeSinceMarkMs + " ms)");
9799 }
9800
9801 ControllerActivityCounterImpl activityCounter =
9802 uid.getOrCreateWifiControllerActivityLocked();
9803 activityCounter.getRxTimeCounter().addCountLocked(scanRxTimeSinceMarkMs);
9804 activityCounter.getTxTimeCounters()[0].addCountLocked(
9805 scanTxTimeSinceMarkMs);
9806 leftOverRxTimeMs -= scanRxTimeSinceMarkMs;
9807 leftOverTxTimeMs -= scanTxTimeSinceMarkMs;
9808 }
9809
9810 // Distribute evenly the power consumed while Idle to each app holding a WiFi
9811 // lock.
9812 final long wifiLockTimeSinceMarkMs =
9813 uid.mFullWifiLockTimer.getTimeSinceMarkLocked(
9814 elapsedRealtimeMs * 1000) / 1000;
9815 if (wifiLockTimeSinceMarkMs > 0) {
9816 // Set the new mark so that next time we get new data since this point.
9817 uid.mFullWifiLockTimer.setMark(elapsedRealtimeMs);
9818
9819 final long myIdleTimeMs = (wifiLockTimeSinceMarkMs * idleTimeMs)
9820 / totalWifiLockTimeMs;
9821 if (DEBUG_ENERGY) {
9822 Slog.d(TAG, " IdleTime for UID " + uid.getUid() + ": "
9823 + myIdleTimeMs + " ms");
9824 }
9825 uid.getOrCreateWifiControllerActivityLocked().getIdleTimeCounter()
9826 .addCountLocked(myIdleTimeMs);
9827 }
9828 }
9829
Adam Lesinskie08af192015-03-25 16:42:59 -07009830 if (DEBUG_ENERGY) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009831 Slog.d(TAG, " New RxPower: " + leftOverRxTimeMs + " ms");
9832 Slog.d(TAG, " New TxPower: " + leftOverTxTimeMs + " ms");
Adam Lesinskie08af192015-03-25 16:42:59 -07009833 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009834
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009835 // Distribute the remaining Tx power appropriately between all apps that transmitted
9836 // packets.
9837 for (int i = 0; i < txPackets.size(); i++) {
9838 final Uid uid = getUidStatsLocked(txPackets.keyAt(i));
9839 final long myTxTimeMs = (txPackets.valueAt(i) * leftOverTxTimeMs)
9840 / totalTxPackets;
9841 if (DEBUG_ENERGY) {
9842 Slog.d(TAG, " TxTime for UID " + uid.getUid() + ": " + myTxTimeMs + " ms");
9843 }
9844 uid.getOrCreateWifiControllerActivityLocked().getTxTimeCounters()[0]
9845 .addCountLocked(myTxTimeMs);
9846 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009847
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009848 // Distribute the remaining Rx power appropriately between all apps that received
9849 // packets.
9850 for (int i = 0; i < rxPackets.size(); i++) {
9851 final Uid uid = getUidStatsLocked(rxPackets.keyAt(i));
9852 final long myRxTimeMs = (rxPackets.valueAt(i) * leftOverRxTimeMs)
9853 / totalRxPackets;
9854 if (DEBUG_ENERGY) {
9855 Slog.d(TAG, " RxTime for UID " + uid.getUid() + ": " + myRxTimeMs + " ms");
9856 }
9857 uid.getOrCreateWifiControllerActivityLocked().getRxTimeCounter()
9858 .addCountLocked(myRxTimeMs);
9859 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009860
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009861 // Any left over power use will be picked up by the WiFi category in BatteryStatsHelper.
9862
9863
9864 // Update WiFi controller stats.
9865 mWifiActivity.getRxTimeCounter().addCountLocked(info.getControllerRxTimeMillis());
9866 mWifiActivity.getTxTimeCounters()[0].addCountLocked(
9867 info.getControllerTxTimeMillis());
9868 mWifiActivity.getIdleTimeCounter().addCountLocked(
9869 info.getControllerIdleTimeMillis());
9870
9871 // POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
9872 final double opVolt = mPowerProfile.getAveragePower(
9873 PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
9874 if (opVolt != 0) {
9875 // We store the power drain as mAms.
9876 mWifiActivity.getPowerCounter().addCountLocked(
9877 (long) (info.getControllerEnergyUsed() / opVolt));
9878 }
Adam Lesinskie08af192015-03-25 16:42:59 -07009879 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009880 }
9881 }
9882
9883 /**
9884 * Distribute Cell radio energy info and network traffic to apps.
9885 */
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009886 public void updateMobileRadioState(@Nullable final ModemActivityInfo activityInfo) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009887 if (DEBUG_ENERGY) {
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009888 Slog.d(TAG, "Updating mobile radio stats with " + activityInfo);
Adam Lesinskia7c90c82015-06-18 14:52:24 -07009889 }
9890
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009891 // Grab a separate lock to acquire the network stats, which may do I/O.
Adam Lesinskie08af192015-03-25 16:42:59 -07009892 NetworkStats delta = null;
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009893 synchronized (mModemNetworkLock) {
9894 final NetworkStats latestStats = readNetworkStatsLocked(mModemIfaces);
9895 if (latestStats != null) {
9896 delta = NetworkStats.subtract(latestStats, mLastModemNetworkStats, null, null,
9897 mNetworkStatsPool.acquire());
9898 mNetworkStatsPool.release(mLastModemNetworkStats);
9899 mLastModemNetworkStats = latestStats;
Adam Lesinskie08af192015-03-25 16:42:59 -07009900 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009901 }
9902
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009903 synchronized (this) {
9904 if (!mOnBatteryInternal) {
9905 if (delta != null) {
9906 mNetworkStatsPool.release(delta);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009907 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009908 return;
Adam Lesinskie08af192015-03-25 16:42:59 -07009909 }
9910
Adam Lesinskib3a1bad2017-05-26 11:50:40 -07009911 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009912 long radioTime = mMobileRadioActivePerAppTimer.getTimeSinceMarkLocked(
9913 elapsedRealtimeMs * 1000);
9914 mMobileRadioActivePerAppTimer.setMark(elapsedRealtimeMs);
9915
9916 long totalRxPackets = 0;
9917 long totalTxPackets = 0;
9918 if (delta != null) {
9919 NetworkStats.Entry entry = new NetworkStats.Entry();
9920 final int size = delta.size();
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009921 for (int i = 0; i < size; i++) {
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009922 entry = delta.getValues(i, entry);
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009923 if (entry.rxPackets == 0 && entry.txPackets == 0) {
9924 continue;
9925 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -07009926
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009927 if (DEBUG_ENERGY) {
9928 Slog.d(TAG, "Mobile uid " + entry.uid + ": delta rx=" + entry.rxBytes
9929 + " tx=" + entry.txBytes + " rxPackets=" + entry.rxPackets
9930 + " txPackets=" + entry.txPackets);
9931 }
9932
9933 totalRxPackets += entry.rxPackets;
9934 totalTxPackets += entry.txPackets;
9935
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009936 final Uid u = getUidStatsLocked(mapUid(entry.uid));
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009937 u.noteNetworkActivityLocked(NETWORK_MOBILE_RX_DATA, entry.rxBytes,
9938 entry.rxPackets);
9939 u.noteNetworkActivityLocked(NETWORK_MOBILE_TX_DATA, entry.txBytes,
9940 entry.txPackets);
9941 if (entry.set == NetworkStats.SET_DEFAULT) { // Background transfers
9942 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_RX_DATA,
9943 entry.rxBytes, entry.rxPackets);
9944 u.noteNetworkActivityLocked(NETWORK_MOBILE_BG_TX_DATA,
9945 entry.txBytes, entry.txPackets);
9946 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009947
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009948 mNetworkByteActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
9949 entry.rxBytes);
9950 mNetworkByteActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
9951 entry.txBytes);
9952 mNetworkPacketActivityCounters[NETWORK_MOBILE_RX_DATA].addCountLocked(
9953 entry.rxPackets);
9954 mNetworkPacketActivityCounters[NETWORK_MOBILE_TX_DATA].addCountLocked(
9955 entry.txPackets);
9956 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009957
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009958 // Now distribute proportional blame to the apps that did networking.
9959 long totalPackets = totalRxPackets + totalTxPackets;
9960 if (totalPackets > 0) {
9961 for (int i = 0; i < size; i++) {
9962 entry = delta.getValues(i, entry);
9963 if (entry.rxPackets == 0 && entry.txPackets == 0) {
9964 continue;
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009965 }
9966
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009967 final Uid u = getUidStatsLocked(mapUid(entry.uid));
9968
9969 // Distribute total radio active time in to this app.
9970 final long appPackets = entry.rxPackets + entry.txPackets;
9971 final long appRadioTime = (radioTime * appPackets) / totalPackets;
9972 u.noteMobileRadioActiveTimeLocked(appRadioTime);
9973
9974 // Remove this app from the totals, so that we don't lose any time
9975 // due to rounding.
9976 radioTime -= appRadioTime;
9977 totalPackets -= appPackets;
9978
9979 if (activityInfo != null) {
9980 ControllerActivityCounterImpl activityCounter =
9981 u.getOrCreateModemControllerActivityLocked();
9982 if (totalRxPackets > 0 && entry.rxPackets > 0) {
9983 final long rxMs = (entry.rxPackets * activityInfo.getRxTimeMillis())
9984 / totalRxPackets;
9985 activityCounter.getRxTimeCounter().addCountLocked(rxMs);
9986 }
9987
9988 if (totalTxPackets > 0 && entry.txPackets > 0) {
9989 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
9990 long txMs =
9991 entry.txPackets * activityInfo.getTxTimeMillis()[lvl];
9992 txMs /= totalTxPackets;
9993 activityCounter.getTxTimeCounters()[lvl].addCountLocked(txMs);
9994 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -08009995 }
9996 }
9997 }
9998 }
Adam Lesinski14ae39a2017-05-26 11:50:40 -07009999
10000 if (radioTime > 0) {
10001 // Whoops, there is some radio time we can't blame on an app!
10002 mMobileRadioActiveUnknownTime.addCountLocked(radioTime);
10003 mMobileRadioActiveUnknownCount.addCountLocked(1);
10004 }
10005
10006 mNetworkStatsPool.release(delta);
10007 delta = null;
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010008 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010009
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010010 if (activityInfo != null) {
10011 mHasModemReporting = true;
10012 mModemActivity.getIdleTimeCounter().addCountLocked(
10013 activityInfo.getIdleTimeMillis());
10014 mModemActivity.getRxTimeCounter().addCountLocked(activityInfo.getRxTimeMillis());
10015 for (int lvl = 0; lvl < ModemActivityInfo.TX_POWER_LEVELS; lvl++) {
10016 mModemActivity.getTxTimeCounters()[lvl]
10017 .addCountLocked(activityInfo.getTxTimeMillis()[lvl]);
10018 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010019
Adam Lesinski14ae39a2017-05-26 11:50:40 -070010020 // POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
10021 final double opVolt = mPowerProfile.getAveragePower(
10022 PowerProfile.POWER_MODEM_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
10023 if (opVolt != 0) {
10024 // We store the power drain as mAms.
10025 mModemActivity.getPowerCounter().addCountLocked(
10026 (long) (activityInfo.getEnergyUsed() / opVolt));
10027 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080010028 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010029 }
10030 }
10031
10032 /**
10033 * Distribute Bluetooth energy info and network traffic to apps.
10034 * @param info The energy information from the bluetooth controller.
10035 */
10036 public void updateBluetoothStateLocked(@Nullable final BluetoothActivityEnergyInfo info) {
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010037 if (DEBUG_ENERGY) {
Adam Lesinski50e47602015-12-04 17:04:54 -080010038 Slog.d(TAG, "Updating bluetooth stats: " + info);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010039 }
10040
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010041 if (info == null || !mOnBatteryInternal) {
10042 return;
10043 }
Adam Lesinskie283d332015-04-16 12:29:25 -070010044
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010045 mHasBluetoothReporting = true;
10046
Bookatz867c0d72017-03-07 18:23:42 -080010047 final long elapsedRealtimeMs = mClocks.elapsedRealtime();
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010048 final long rxTimeMs = info.getControllerRxTimeMillis();
10049 final long txTimeMs = info.getControllerTxTimeMillis();
10050
10051 if (DEBUG_ENERGY) {
10052 Slog.d(TAG, "------ BEGIN BLE power blaming ------");
10053 Slog.d(TAG, " Tx Time: " + txTimeMs + " ms");
10054 Slog.d(TAG, " Rx Time: " + rxTimeMs + " ms");
10055 Slog.d(TAG, " Idle Time: " + info.getControllerIdleTimeMillis() + " ms");
10056 }
10057
10058 long totalScanTimeMs = 0;
10059
10060 final int uidCount = mUidStats.size();
10061 for (int i = 0; i < uidCount; i++) {
10062 final Uid u = mUidStats.valueAt(i);
10063 if (u.mBluetoothScanTimer == null) {
10064 continue;
Adam Lesinskie283d332015-04-16 12:29:25 -070010065 }
Adam Lesinski50e47602015-12-04 17:04:54 -080010066
Bookatzaa4594a2017-03-24 12:39:56 -070010067 totalScanTimeMs += u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010068 elapsedRealtimeMs * 1000) / 1000;
10069 }
10070
10071 final boolean normalizeScanRxTime = (totalScanTimeMs > rxTimeMs);
10072 final boolean normalizeScanTxTime = (totalScanTimeMs > txTimeMs);
10073
10074 if (DEBUG_ENERGY) {
10075 Slog.d(TAG, "Normalizing scan power for RX=" + normalizeScanRxTime
10076 + " TX=" + normalizeScanTxTime);
10077 }
10078
10079 long leftOverRxTimeMs = rxTimeMs;
10080 long leftOverTxTimeMs = txTimeMs;
10081
10082 for (int i = 0; i < uidCount; i++) {
10083 final Uid u = mUidStats.valueAt(i);
10084 if (u.mBluetoothScanTimer == null) {
10085 continue;
10086 }
10087
Bookatzaa4594a2017-03-24 12:39:56 -070010088 long scanTimeSinceMarkMs = u.mBluetoothScanTimer.getTimeSinceMarkLocked(
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010089 elapsedRealtimeMs * 1000) / 1000;
10090 if (scanTimeSinceMarkMs > 0) {
10091 // Set the new mark so that next time we get new data since this point.
10092 u.mBluetoothScanTimer.setMark(elapsedRealtimeMs);
10093
10094 long scanTimeRxSinceMarkMs = scanTimeSinceMarkMs;
10095 long scanTimeTxSinceMarkMs = scanTimeSinceMarkMs;
10096
10097 if (normalizeScanRxTime) {
10098 // Scan time is longer than the total rx time in the controller,
10099 // so distribute the scan time proportionately. This means regular traffic
10100 // will not blamed, but scans are more expensive anyways.
10101 scanTimeRxSinceMarkMs = (rxTimeMs * scanTimeRxSinceMarkMs) / totalScanTimeMs;
10102 }
10103
10104 if (normalizeScanTxTime) {
10105 // Scan time is longer than the total tx time in the controller,
10106 // so distribute the scan time proportionately. This means regular traffic
10107 // will not blamed, but scans are more expensive anyways.
10108 scanTimeTxSinceMarkMs = (txTimeMs * scanTimeTxSinceMarkMs) / totalScanTimeMs;
10109 }
10110
10111 final ControllerActivityCounterImpl counter =
10112 u.getOrCreateBluetoothControllerActivityLocked();
10113 counter.getRxTimeCounter().addCountLocked(scanTimeRxSinceMarkMs);
10114 counter.getTxTimeCounters()[0].addCountLocked(scanTimeTxSinceMarkMs);
10115
10116 leftOverRxTimeMs -= scanTimeRxSinceMarkMs;
10117 leftOverTxTimeMs -= scanTimeTxSinceMarkMs;
10118 }
10119 }
10120
10121 if (DEBUG_ENERGY) {
10122 Slog.d(TAG, "Left over time for traffic RX=" + leftOverRxTimeMs
10123 + " TX=" + leftOverTxTimeMs);
10124 }
10125
10126 //
10127 // Now distribute blame to apps that did bluetooth traffic.
10128 //
10129
10130 long totalTxBytes = 0;
10131 long totalRxBytes = 0;
10132
10133 final UidTraffic[] uidTraffic = info.getUidTraffic();
10134 final int numUids = uidTraffic != null ? uidTraffic.length : 0;
10135 for (int i = 0; i < numUids; i++) {
10136 final UidTraffic traffic = uidTraffic[i];
10137
10138 // Add to the global counters.
10139 mNetworkByteActivityCounters[NETWORK_BT_RX_DATA].addCountLocked(
10140 traffic.getRxBytes());
10141 mNetworkByteActivityCounters[NETWORK_BT_TX_DATA].addCountLocked(
10142 traffic.getTxBytes());
10143
10144 // Add to the UID counters.
10145 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
10146 u.noteNetworkActivityLocked(NETWORK_BT_RX_DATA, traffic.getRxBytes(), 0);
10147 u.noteNetworkActivityLocked(NETWORK_BT_TX_DATA, traffic.getTxBytes(), 0);
10148
10149 // Calculate the total traffic.
10150 totalTxBytes += traffic.getTxBytes();
10151 totalRxBytes += traffic.getRxBytes();
10152 }
10153
10154 if ((totalTxBytes != 0 || totalRxBytes != 0) &&
10155 (leftOverRxTimeMs != 0 || leftOverTxTimeMs != 0)) {
Adam Lesinski50e47602015-12-04 17:04:54 -080010156 for (int i = 0; i < numUids; i++) {
10157 final UidTraffic traffic = uidTraffic[i];
10158
Adam Lesinski50e47602015-12-04 17:04:54 -080010159 final Uid u = getUidStatsLocked(mapUid(traffic.getUid()));
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010160 final ControllerActivityCounterImpl counter =
10161 u.getOrCreateBluetoothControllerActivityLocked();
10162
10163 if (totalRxBytes > 0 && traffic.getRxBytes() > 0) {
10164 final long timeRxMs = (leftOverRxTimeMs * traffic.getRxBytes()) / totalRxBytes;
10165
10166 if (DEBUG_ENERGY) {
10167 Slog.d(TAG, "UID=" + traffic.getUid() + " rx_bytes=" + traffic.getRxBytes()
10168 + " rx_time=" + timeRxMs);
10169 }
10170 counter.getRxTimeCounter().addCountLocked(timeRxMs);
10171 leftOverRxTimeMs -= timeRxMs;
10172 }
10173
10174 if (totalTxBytes > 0 && traffic.getTxBytes() > 0) {
10175 final long timeTxMs = (leftOverTxTimeMs * traffic.getTxBytes()) / totalTxBytes;
10176
10177 if (DEBUG_ENERGY) {
10178 Slog.d(TAG, "UID=" + traffic.getUid() + " tx_bytes=" + traffic.getTxBytes()
10179 + " tx_time=" + timeTxMs);
10180 }
10181
10182 counter.getTxTimeCounters()[0].addCountLocked(timeTxMs);
10183 leftOverTxTimeMs -= timeTxMs;
10184 }
Adam Lesinski50e47602015-12-04 17:04:54 -080010185 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010186 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010187
10188 mBluetoothActivity.getRxTimeCounter().addCountLocked(
10189 info.getControllerRxTimeMillis());
10190 mBluetoothActivity.getTxTimeCounters()[0].addCountLocked(
10191 info.getControllerTxTimeMillis());
10192 mBluetoothActivity.getIdleTimeCounter().addCountLocked(
10193 info.getControllerIdleTimeMillis());
10194
10195 // POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE is measured in mV, so convert to V.
10196 final double opVolt = mPowerProfile.getAveragePower(
10197 PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE) / 1000.0;
10198 if (opVolt != 0) {
10199 // We store the power drain as mAms.
10200 mBluetoothActivity.getPowerCounter().addCountLocked(
10201 (long) (info.getControllerEnergyUsed() / opVolt));
10202 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010203 }
10204
10205 /**
10206 * Read and distribute kernel wake lock use across apps.
10207 */
10208 public void updateKernelWakelocksLocked() {
10209 final KernelWakelockStats wakelockStats = mKernelWakelockReader.readKernelWakelockStats(
10210 mTmpWakelockStats);
10211 if (wakelockStats == null) {
10212 // Not crashing might make board bringup easier.
10213 Slog.w(TAG, "Couldn't get kernel wake lock stats");
10214 return;
10215 }
10216
10217 for (Map.Entry<String, KernelWakelockStats.Entry> ent : wakelockStats.entrySet()) {
10218 String name = ent.getKey();
10219 KernelWakelockStats.Entry kws = ent.getValue();
10220
10221 SamplingTimer kwlt = mKernelWakelockStats.get(name);
10222 if (kwlt == null) {
Adam Lesinski757c6ea2016-04-21 09:55:41 -070010223 kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010224 mKernelWakelockStats.put(name, kwlt);
10225 }
Adam Lesinskid84ad302016-05-17 18:31:02 -070010226
Adam Lesinski757c6ea2016-04-21 09:55:41 -070010227 kwlt.update(kws.mTotalTime, kws.mCount);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010228 kwlt.setUpdateVersion(kws.mVersion);
10229 }
10230
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070010231 int numWakelocksSetStale = 0;
Adam Lesinskid84ad302016-05-17 18:31:02 -070010232 // Set timers to stale if they didn't appear in /d/wakeup_sources (or /proc/wakelocks)
10233 // this time.
10234 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
10235 SamplingTimer st = ent.getValue();
10236 if (st.getUpdateVersion() != wakelockStats.kernelWakelockVersion) {
10237 st.endSample();
10238 numWakelocksSetStale++;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010239 }
10240 }
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070010241
Adam Lesinskid84ad302016-05-17 18:31:02 -070010242 // Record whether we've seen a non-zero time (for debugging b/22716723).
10243 if (wakelockStats.isEmpty()) {
Adam Lesinskifbabe7d2015-08-03 14:37:38 -070010244 Slog.wtf(TAG, "All kernel wakelocks had time of zero");
10245 }
10246
10247 if (numWakelocksSetStale == mKernelWakelockStats.size()) {
10248 Slog.wtf(TAG, "All kernel wakelocks were set stale. new version=" +
10249 wakelockStats.kernelWakelockVersion);
10250 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010251 }
10252
Adam Lesinski72478f02015-06-17 15:39:43 -070010253 // We use an anonymous class to access these variables,
10254 // so they can't live on the stack or they'd have to be
10255 // final MutableLong objects (more allocations).
10256 // Used in updateCpuTimeLocked().
10257 long mTempTotalCpuUserTimeUs;
10258 long mTempTotalCpuSystemTimeUs;
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010259 long[][] mWakeLockAllocationsUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070010260
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010261 /**
James Carr3a226052016-07-01 14:49:52 -070010262 * Reads the newest memory stats from the kernel.
10263 */
10264 public void updateKernelMemoryBandwidthLocked() {
10265 mKernelMemoryBandwidthStats.updateStats();
10266 LongSparseLongArray bandwidthEntries = mKernelMemoryBandwidthStats.getBandwidthEntries();
10267 final int bandwidthEntryCount = bandwidthEntries.size();
10268 int index;
10269 for (int i = 0; i < bandwidthEntryCount; i++) {
10270 SamplingTimer timer;
10271 if ((index = mKernelMemoryStats.indexOfKey(bandwidthEntries.keyAt(i))) >= 0) {
10272 timer = mKernelMemoryStats.valueAt(index);
10273 } else {
10274 timer = new SamplingTimer(mClocks, mOnBatteryTimeBase);
10275 mKernelMemoryStats.put(bandwidthEntries.keyAt(i), timer);
10276 }
10277 timer.update(bandwidthEntries.valueAt(i), 1);
10278 if (DEBUG_MEMORY) {
10279 Slog.d(TAG, String.format("Added entry %d and updated timer to: "
10280 + "mUnpluggedReportedTotalTime %d size %d", bandwidthEntries.keyAt(i),
10281 mKernelMemoryStats.get(
10282 bandwidthEntries.keyAt(i)).mUnpluggedReportedTotalTime,
10283 mKernelMemoryStats.size()));
10284 }
10285 }
10286 }
10287
10288 /**
Adam Lesinski72478f02015-06-17 15:39:43 -070010289 * Read and distribute CPU usage across apps. If their are partial wakelocks being held
10290 * and we are on battery with screen off, we give more of the cpu time to those apps holding
10291 * wakelocks. If the screen is on, we just assign the actual cpu time an app used.
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010292 */
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010293 public void updateCpuTimeLocked() {
Adam Lesinski52290c9c2015-09-21 16:54:52 -070010294 if (mPowerProfile == null) {
10295 return;
10296 }
10297
Adam Lesinski72478f02015-06-17 15:39:43 -070010298 if (DEBUG_ENERGY_CPU) {
10299 Slog.d(TAG, "!Cpu updating!");
10300 }
10301
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010302 if (mCpuFreqs == null) {
10303 mCpuFreqs = mKernelUidCpuFreqTimeReader.readFreqs(mPowerProfile);
10304 }
10305
Sudheer Shanka38383232017-07-25 09:55:03 -070010306 // Calculate the wakelocks we have to distribute amongst. The system is excluded as it is
10307 // usually holding the wakelock on behalf of an app.
10308 // And Only distribute cpu power to wakelocks if the screen is off and we're on battery.
10309 ArrayList<StopwatchTimer> partialTimersToConsider = null;
Adam Lesinski72478f02015-06-17 15:39:43 -070010310 if (mOnBatteryScreenOffTimeBase.isRunning()) {
Sudheer Shanka38383232017-07-25 09:55:03 -070010311 partialTimersToConsider = new ArrayList<>();
10312 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070010313 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070010314 // Since the collection and blaming of wakelocks can be scheduled to run after
10315 // some delay, the mPartialTimers list may have new entries. We can't blame
10316 // the newly added timer for past cpu time, so we only consider timers that
10317 // were present for one round of collection. Once a timer has gone through
10318 // a round of collection, its mInList field is set to true.
Adam Lesinski72478f02015-06-17 15:39:43 -070010319 if (timer.mInList && timer.mUid != null && timer.mUid.mUid != Process.SYSTEM_UID) {
Sudheer Shanka38383232017-07-25 09:55:03 -070010320 partialTimersToConsider.add(timer);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010321 }
Adam Lesinski72478f02015-06-17 15:39:43 -070010322 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010323 }
Sudheer Shanka38383232017-07-25 09:55:03 -070010324 markPartialTimersAsEligible();
Adam Lesinski72478f02015-06-17 15:39:43 -070010325
Sudheer Shanka38383232017-07-25 09:55:03 -070010326 // When the battery is not on, we don't attribute the cpu times to any timers but we still
10327 // need to take the snapshots.
10328 if (!mOnBatteryInternal) {
10329 mKernelUidCpuTimeReader.readDelta(null);
10330 mKernelUidCpuFreqTimeReader.readDelta(null);
10331 for (int cluster = mKernelCpuSpeedReaders.length - 1; cluster >= 0; --cluster) {
10332 mKernelCpuSpeedReaders[cluster].readDelta();
10333 }
10334 return;
10335 }
Adam Lesinski72478f02015-06-17 15:39:43 -070010336
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070010337 mUserInfoProvider.refreshUserIds();
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010338 final SparseLongArray updatedUids = mKernelUidCpuFreqTimeReader.perClusterTimesAvailable()
10339 ? null : new SparseLongArray();
Sudheer Shanka38383232017-07-25 09:55:03 -070010340 readKernelUidCpuTimesLocked(partialTimersToConsider, updatedUids);
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010341 // updatedUids=null means /proc/uid_time_in_state provides snapshots of per-cluster cpu
10342 // freqs, so no need to approximate these values.
10343 if (updatedUids != null) {
10344 updateClusterSpeedTimes(updatedUids);
Sudheer Shanka671985f2017-05-19 11:33:42 -070010345 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010346 readKernelUidCpuFreqTimesLocked(partialTimersToConsider);
Sudheer Shanka38383232017-07-25 09:55:03 -070010347 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010348
Sudheer Shanka38383232017-07-25 09:55:03 -070010349 /**
10350 * Mark the current partial timers as gone through a collection so that they will be
10351 * considered in the next cpu times distribution to wakelock holders.
10352 */
10353 @VisibleForTesting
10354 public void markPartialTimersAsEligible() {
10355 if (ArrayUtils.referenceEquals(mPartialTimers, mLastPartialTimers)) {
10356 // No difference, so each timer is now considered for the next collection.
10357 for (int i = mPartialTimers.size() - 1; i >= 0; --i) {
10358 mPartialTimers.get(i).mInList = true;
10359 }
10360 } else {
10361 // The lists are different, meaning we added (or removed a timer) since the last
10362 // collection.
10363 for (int i = mLastPartialTimers.size() - 1; i >= 0; --i) {
10364 mLastPartialTimers.get(i).mInList = false;
10365 }
10366 mLastPartialTimers.clear();
Adam Lesinski72478f02015-06-17 15:39:43 -070010367
Sudheer Shanka38383232017-07-25 09:55:03 -070010368 // Mark the current timers as gone through a collection.
10369 final int numPartialTimers = mPartialTimers.size();
10370 for (int i = 0; i < numPartialTimers; ++i) {
Adam Lesinski72478f02015-06-17 15:39:43 -070010371 final StopwatchTimer timer = mPartialTimers.get(i);
Sudheer Shanka38383232017-07-25 09:55:03 -070010372 timer.mInList = true;
10373 mLastPartialTimers.add(timer);
Adam Lesinski72478f02015-06-17 15:39:43 -070010374 }
10375 }
Sudheer Shanka38383232017-07-25 09:55:03 -070010376 }
Adam Lesinski72478f02015-06-17 15:39:43 -070010377
Sudheer Shanka38383232017-07-25 09:55:03 -070010378 /**
10379 * Take snapshot of cpu times (aggregated over all uids) at different frequencies and
10380 * calculate cpu times spent by each uid at different frequencies.
10381 *
10382 * @param updatedUids The uids for which times spent at different frequencies are calculated.
10383 */
10384 @VisibleForTesting
10385 public void updateClusterSpeedTimes(@NonNull SparseLongArray updatedUids) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070010386 long totalCpuClustersTimeMs = 0;
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010387 // Read the time spent for each cluster at various cpu frequencies.
Sudheer Shankaaf857412017-07-21 00:14:24 -070010388 final long[][] clusterSpeedTimesMs = new long[mKernelCpuSpeedReaders.length][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010389 for (int cluster = 0; cluster < mKernelCpuSpeedReaders.length; cluster++) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070010390 clusterSpeedTimesMs[cluster] = mKernelCpuSpeedReaders[cluster].readDelta();
10391 if (clusterSpeedTimesMs[cluster] != null) {
10392 for (int speed = clusterSpeedTimesMs[cluster].length - 1; speed >= 0; --speed) {
10393 totalCpuClustersTimeMs += clusterSpeedTimesMs[cluster][speed];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010394 }
10395 }
10396 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070010397 if (totalCpuClustersTimeMs != 0) {
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010398 // We have cpu times per freq aggregated over all uids but we need the times per uid.
10399 // So, we distribute total time spent by an uid to different cpu freqs based on the
10400 // amount of time cpu was running at that freq.
10401 final int updatedUidsCount = updatedUids.size();
10402 for (int i = 0; i < updatedUidsCount; ++i) {
10403 final Uid u = getUidStatsLocked(updatedUids.keyAt(i));
Sudheer Shankaaf857412017-07-21 00:14:24 -070010404 final long appCpuTimeUs = updatedUids.valueAt(i);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010405 // Add the cpu speeds to this UID.
10406 final int numClusters = mPowerProfile.getNumCpuClusters();
Sudheer Shanka38383232017-07-25 09:55:03 -070010407 if (u.mCpuClusterSpeedTimesUs == null ||
10408 u.mCpuClusterSpeedTimesUs.length != numClusters) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070010409 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010410 }
10411
Sudheer Shankaaf857412017-07-21 00:14:24 -070010412 for (int cluster = 0; cluster < clusterSpeedTimesMs.length; cluster++) {
10413 final int speedsInCluster = clusterSpeedTimesMs[cluster].length;
10414 if (u.mCpuClusterSpeedTimesUs[cluster] == null || speedsInCluster !=
10415 u.mCpuClusterSpeedTimesUs[cluster].length) {
10416 u.mCpuClusterSpeedTimesUs[cluster]
10417 = new LongSamplingCounter[speedsInCluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010418 }
10419
Sudheer Shankaaf857412017-07-21 00:14:24 -070010420 final LongSamplingCounter[] cpuSpeeds = u.mCpuClusterSpeedTimesUs[cluster];
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010421 for (int speed = 0; speed < speedsInCluster; speed++) {
10422 if (cpuSpeeds[speed] == null) {
10423 cpuSpeeds[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
10424 }
Sudheer Shankaaf857412017-07-21 00:14:24 -070010425 cpuSpeeds[speed].addCountLocked(appCpuTimeUs
10426 * clusterSpeedTimesMs[cluster][speed]
10427 / totalCpuClustersTimeMs);
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010428 }
10429 }
10430 }
10431 }
Sudheer Shanka38383232017-07-25 09:55:03 -070010432 }
Sudheer Shanka2fc52d42017-06-16 17:29:19 -070010433
Sudheer Shanka38383232017-07-25 09:55:03 -070010434 /**
10435 * Take a snapshot of the cpu times spent by each uid and update the corresponding counters.
10436 * If {@param partialTimers} is not null and empty, then we assign a portion of cpu times to
10437 * wakelock holders.
10438 *
10439 * @param partialTimers The wakelock holders among which the cpu times will be distributed.
10440 * @param updatedUids If not null, then the uids found in the snapshot will be added to this.
10441 */
10442 @VisibleForTesting
10443 public void readKernelUidCpuTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers,
10444 @Nullable SparseLongArray updatedUids) {
10445 mTempTotalCpuUserTimeUs = mTempTotalCpuSystemTimeUs = 0;
10446 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
10447 final long startTimeMs = mClocks.uptimeMillis();
Adam Lesinski72478f02015-06-17 15:39:43 -070010448
Sudheer Shanka38383232017-07-25 09:55:03 -070010449 mKernelUidCpuTimeReader.readDelta((uid, userTimeUs, systemTimeUs) -> {
10450 uid = mapUid(uid);
10451 if (Process.isIsolated(uid)) {
10452 // This could happen if the isolated uid mapping was removed before that process
10453 // was actually killed.
10454 mKernelUidCpuTimeReader.removeUid(uid);
10455 Slog.d(TAG, "Got readings for an isolated uid with no mapping: " + uid);
10456 return;
10457 }
10458 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
10459 Slog.d(TAG, "Got readings for an invalid user's uid " + uid);
10460 mKernelUidCpuTimeReader.removeUid(uid);
10461 return;
10462 }
10463 final Uid u = getUidStatsLocked(uid);
10464
10465 // Accumulate the total system and user time.
10466 mTempTotalCpuUserTimeUs += userTimeUs;
10467 mTempTotalCpuSystemTimeUs += systemTimeUs;
10468
10469 StringBuilder sb = null;
10470 if (DEBUG_ENERGY_CPU) {
10471 sb = new StringBuilder();
10472 sb.append(" got time for uid=").append(u.mUid).append(": u=");
10473 TimeUtils.formatDuration(userTimeUs / 1000, sb);
10474 sb.append(" s=");
10475 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
10476 sb.append("\n");
10477 }
10478
10479 if (numWakelocks > 0) {
10480 // We have wakelocks being held, so only give a portion of the
10481 // time to the process. The rest will be distributed among wakelock
10482 // holders.
10483 userTimeUs = (userTimeUs * WAKE_LOCK_WEIGHT) / 100;
10484 systemTimeUs = (systemTimeUs * WAKE_LOCK_WEIGHT) / 100;
10485 }
10486
10487 if (sb != null) {
10488 sb.append(" adding to uid=").append(u.mUid).append(": u=");
10489 TimeUtils.formatDuration(userTimeUs / 1000, sb);
10490 sb.append(" s=");
10491 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
10492 Slog.d(TAG, sb.toString());
10493 }
10494
10495 u.mUserCpuTime.addCountLocked(userTimeUs);
10496 u.mSystemCpuTime.addCountLocked(systemTimeUs);
10497 if (updatedUids != null) {
10498 updatedUids.put(u.getUid(), userTimeUs + systemTimeUs);
10499 }
10500 });
10501
10502 final long elapsedTimeMs = mClocks.uptimeMillis() - startTimeMs;
10503 if (DEBUG_ENERGY_CPU || elapsedTimeMs >= 100) {
10504 Slog.d(TAG, "Reading cpu stats took " + elapsedTimeMs + "ms");
10505 }
10506
10507 if (numWakelocks > 0) {
10508 // Distribute a portion of the total cpu time to wakelock holders.
10509 mTempTotalCpuUserTimeUs = (mTempTotalCpuUserTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
10510 mTempTotalCpuSystemTimeUs =
10511 (mTempTotalCpuSystemTimeUs * (100 - WAKE_LOCK_WEIGHT)) / 100;
10512
10513 for (int i = 0; i < numWakelocks; ++i) {
10514 final StopwatchTimer timer = partialTimers.get(i);
10515 final int userTimeUs = (int) (mTempTotalCpuUserTimeUs / (numWakelocks - i));
10516 final int systemTimeUs = (int) (mTempTotalCpuSystemTimeUs / (numWakelocks - i));
10517
10518 if (DEBUG_ENERGY_CPU) {
10519 final StringBuilder sb = new StringBuilder();
10520 sb.append(" Distributing wakelock uid=").append(timer.mUid.mUid)
10521 .append(": u=");
10522 TimeUtils.formatDuration(userTimeUs / 1000, sb);
10523 sb.append(" s=");
10524 TimeUtils.formatDuration(systemTimeUs / 1000, sb);
10525 Slog.d(TAG, sb.toString());
10526 }
10527
10528 timer.mUid.mUserCpuTime.addCountLocked(userTimeUs);
10529 timer.mUid.mSystemCpuTime.addCountLocked(systemTimeUs);
10530 if (updatedUids != null) {
10531 final int uid = timer.mUid.getUid();
10532 updatedUids.put(uid, updatedUids.get(uid, 0) + userTimeUs + systemTimeUs);
10533 }
10534
10535 final Uid.Proc proc = timer.mUid.getProcessStatsLocked("*wakelock*");
10536 proc.addCpuTimeLocked(userTimeUs / 1000, systemTimeUs / 1000);
10537
10538 mTempTotalCpuUserTimeUs -= userTimeUs;
10539 mTempTotalCpuSystemTimeUs -= systemTimeUs;
Adam Lesinski72478f02015-06-17 15:39:43 -070010540 }
10541 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070010542 }
10543
Sudheer Shanka38383232017-07-25 09:55:03 -070010544 /**
10545 * Take a snapshot of the cpu times spent by each uid in each freq and update the
10546 * corresponding counters.
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010547 *
10548 * @param partialTimers The wakelock holders among which the cpu freq times will be distributed.
Sudheer Shanka38383232017-07-25 09:55:03 -070010549 */
10550 @VisibleForTesting
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010551 public void readKernelUidCpuFreqTimesLocked(@Nullable ArrayList<StopwatchTimer> partialTimers) {
10552 final boolean perClusterTimesAvailable =
10553 mKernelUidCpuFreqTimeReader.perClusterTimesAvailable();
10554 final int numWakelocks = partialTimers == null ? 0 : partialTimers.size();
10555 final int numClusters = mPowerProfile.getNumCpuClusters();
10556 mWakeLockAllocationsUs = null;
10557 mKernelUidCpuFreqTimeReader.readDelta((uid, cpuFreqTimeMs) -> {
10558 uid = mapUid(uid);
10559 if (Process.isIsolated(uid)) {
10560 mKernelUidCpuFreqTimeReader.removeUid(uid);
10561 Slog.d(TAG, "Got freq readings for an isolated uid with no mapping: " + uid);
10562 return;
Sudheer Shanka38383232017-07-25 09:55:03 -070010563 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010564 if (!mUserInfoProvider.exists(UserHandle.getUserId(uid))) {
10565 Slog.d(TAG, "Got freq readings for an invalid user's uid " + uid);
10566 mKernelUidCpuFreqTimeReader.removeUid(uid);
10567 return;
10568 }
10569 final Uid u = getUidStatsLocked(uid);
10570 if (u.mCpuFreqTimeMs == null || u.mCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
10571 u.mCpuFreqTimeMs = new LongSamplingCounterArray(mOnBatteryTimeBase);
10572 }
10573 u.mCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
10574 if (u.mScreenOffCpuFreqTimeMs == null ||
10575 u.mScreenOffCpuFreqTimeMs.getSize() != cpuFreqTimeMs.length) {
10576 u.mScreenOffCpuFreqTimeMs = new LongSamplingCounterArray(
10577 mOnBatteryScreenOffTimeBase);
10578 }
10579 u.mScreenOffCpuFreqTimeMs.addCountLocked(cpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010580
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010581 if (perClusterTimesAvailable) {
10582 if (u.mCpuClusterSpeedTimesUs == null ||
10583 u.mCpuClusterSpeedTimesUs.length != numClusters) {
10584 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070010585 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010586 if (numWakelocks > 0 && mWakeLockAllocationsUs == null) {
10587 mWakeLockAllocationsUs = new long[numClusters][];
Sudheer Shanka38383232017-07-25 09:55:03 -070010588 }
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010589
10590 int freqIndex = 0;
10591 for (int cluster = 0; cluster < numClusters; ++cluster) {
10592 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
10593 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
10594 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
10595 u.mCpuClusterSpeedTimesUs[cluster]
10596 = new LongSamplingCounter[speedsInCluster];
10597 }
10598 if (numWakelocks > 0 && mWakeLockAllocationsUs[cluster] == null) {
10599 mWakeLockAllocationsUs[cluster] = new long[speedsInCluster];
10600 }
10601 final LongSamplingCounter[] cpuTimesUs = u.mCpuClusterSpeedTimesUs[cluster];
10602 for (int speed = 0; speed < speedsInCluster; ++speed) {
10603 if (cpuTimesUs[speed] == null) {
10604 cpuTimesUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
10605 }
10606 final long appAllocationUs;
10607 if (mWakeLockAllocationsUs != null) {
10608 appAllocationUs =
10609 (cpuFreqTimeMs[freqIndex] * 1000 * WAKE_LOCK_WEIGHT) / 100;
10610 mWakeLockAllocationsUs[cluster][speed] +=
10611 (cpuFreqTimeMs[freqIndex] * 1000 - appAllocationUs);
10612 } else {
10613 appAllocationUs = cpuFreqTimeMs[freqIndex] * 1000;
10614 }
10615 cpuTimesUs[speed].addCountLocked(appAllocationUs);
10616 freqIndex++;
10617 }
Sudheer Shanka38383232017-07-25 09:55:03 -070010618 }
Sudheer Shanka38383232017-07-25 09:55:03 -070010619 }
10620 });
Sudheer Shankab8ad5942017-08-08 12:16:09 -070010621
10622 if (mWakeLockAllocationsUs != null) {
10623 for (int i = 0; i < numWakelocks; ++i) {
10624 final Uid u = partialTimers.get(i).mUid;
10625 if (u.mCpuClusterSpeedTimesUs == null ||
10626 u.mCpuClusterSpeedTimesUs.length != numClusters) {
10627 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
10628 }
10629
10630 for (int cluster = 0; cluster < numClusters; ++cluster) {
10631 final int speedsInCluster = mPowerProfile.getNumSpeedStepsInCpuCluster(cluster);
10632 if (u.mCpuClusterSpeedTimesUs[cluster] == null ||
10633 u.mCpuClusterSpeedTimesUs[cluster].length != speedsInCluster) {
10634 u.mCpuClusterSpeedTimesUs[cluster]
10635 = new LongSamplingCounter[speedsInCluster];
10636 }
10637 final LongSamplingCounter[] cpuTimeUs = u.mCpuClusterSpeedTimesUs[cluster];
10638 for (int speed = 0; speed < speedsInCluster; ++speed) {
10639 if (cpuTimeUs[speed] == null) {
10640 cpuTimeUs[speed] = new LongSamplingCounter(mOnBatteryTimeBase);
10641 }
10642 final long allocationUs =
10643 mWakeLockAllocationsUs[cluster][speed] / (numWakelocks - i);
10644 cpuTimeUs[speed].addCountLocked(allocationUs);
10645 mWakeLockAllocationsUs[cluster][speed] -= allocationUs;
10646 }
10647 }
10648 }
10649 }
Sudheer Shanka9b735c52017-05-09 18:26:18 -070010650 }
10651
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010652 boolean setChargingLocked(boolean charging) {
10653 if (mCharging != charging) {
10654 mCharging = charging;
10655 if (charging) {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070010656 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010657 } else {
Dianne Hackborn0c820db2015-04-14 17:47:34 -070010658 mHistoryCur.states2 &= ~HistoryItem.STATE2_CHARGING_FLAG;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010659 }
10660 mHandler.sendEmptyMessage(MSG_REPORT_CHARGING);
10661 return true;
10662 }
10663 return false;
10664 }
10665
Dianne Hackborn40c87252014-03-19 16:55:40 -070010666 void setOnBatteryLocked(final long mSecRealtime, final long mSecUptime, final boolean onBattery,
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010667 final int oldStatus, final int level, final int chargeUAh) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010668 boolean doWrite = false;
10669 Message m = mHandler.obtainMessage(MSG_REPORT_POWER_CHANGE);
10670 m.arg1 = onBattery ? 1 : 0;
10671 mHandler.sendMessage(m);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010672
Dianne Hackborn40c87252014-03-19 16:55:40 -070010673 final long uptime = mSecUptime * 1000;
10674 final long realtime = mSecRealtime * 1000;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010675 final boolean screenOn = mScreenState == Display.STATE_ON;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010676 if (onBattery) {
10677 // We will reset our status if we are unplugging after the
10678 // battery was last full, or the level is at 100, or
10679 // we have gone through a significant charge (from a very low
10680 // level to a now very high level).
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010681 boolean reset = false;
Dianne Hackborn9a755432014-05-15 17:05:22 -070010682 if (!mNoAutoReset && (oldStatus == BatteryManager.BATTERY_STATUS_FULL
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010683 || level >= 90
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070010684 || (mDischargeCurrentLevel < 20 && level >= 80)
10685 || (getHighDischargeAmountSinceCharge() >= 200
10686 && mHistoryBuffer.dataSize() >= MAX_HISTORY_BUFFER))) {
Dianne Hackborn73d6a822014-09-29 10:52:47 -070010687 Slog.i(TAG, "Resetting battery stats: level=" + level + " status=" + oldStatus
Dianne Hackbornfb3809c2014-09-29 18:31:22 -070010688 + " dischargeLevel=" + mDischargeCurrentLevel
Dianne Hackborn73d6a822014-09-29 10:52:47 -070010689 + " lowAmount=" + getLowDischargeAmountSinceCharge()
10690 + " highAmount=" + getHighDischargeAmountSinceCharge());
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010691 // Before we write, collect a snapshot of the final aggregated
10692 // stats to be reported in the next checkin. Only do this if we have
10693 // a sufficient amount of data to make it interesting.
10694 if (getLowDischargeAmountSinceCharge() >= 20) {
10695 final Parcel parcel = Parcel.obtain();
10696 writeSummaryToParcel(parcel, true);
10697 BackgroundThread.getHandler().post(new Runnable() {
10698 @Override public void run() {
10699 synchronized (mCheckinFile) {
10700 FileOutputStream stream = null;
10701 try {
10702 stream = mCheckinFile.startWrite();
10703 stream.write(parcel.marshall());
10704 stream.flush();
10705 FileUtils.sync(stream);
10706 stream.close();
10707 mCheckinFile.finishWrite(stream);
10708 } catch (IOException e) {
10709 Slog.w("BatteryStats",
10710 "Error writing checkin battery statistics", e);
10711 mCheckinFile.failWrite(stream);
10712 } finally {
10713 parcel.recycle();
10714 }
10715 }
10716 }
10717 });
10718 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010719 doWrite = true;
10720 resetAllStatsLocked();
Ying Wai (Daniel) Fan442ab762017-01-31 22:00:10 -080010721 if (chargeUAh > 0 && level > 0) {
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010722 // Only use the reported coulomb charge value if it is supported and reported.
Ying Wai (Daniel) Fan9238b612017-01-18 15:50:19 -080010723 mEstimatedBatteryCapacity = (int) ((chargeUAh / 1000) / (level / 100.0));
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010724 }
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010725 mDischargeStartLevel = level;
Dianne Hackborneaf2ac42014-02-07 13:01:07 -080010726 reset = true;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010727 mDischargeStepTracker.init();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010728 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010729 if (mCharging) {
10730 setChargingLocked(false);
10731 }
10732 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010733 mOnBattery = mOnBatteryInternal = true;
Dianne Hackborn260c5022014-04-29 11:23:16 -070010734 mLastDischargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070010735 mMinDischargeStepLevel = level;
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010736 mDischargeStepTracker.clearTime();
10737 mDailyDischargeStepTracker.clearTime();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010738 mInitStepMode = mCurStepMode;
10739 mModStepMode = 0;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010740 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010741 mHistoryCur.batteryLevel = (byte)level;
10742 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
10743 if (DEBUG_HISTORY) Slog.v(TAG, "Battery unplugged to: "
10744 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010745 if (reset) {
10746 mRecordingHistory = true;
10747 startRecordingHistory(mSecRealtime, mSecUptime, reset);
10748 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070010749 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010750 mDischargeCurrentLevel = mDischargeUnplugLevel = level;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010751 if (screenOn) {
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010752 mDischargeScreenOnUnplugLevel = level;
10753 mDischargeScreenOffUnplugLevel = 0;
10754 } else {
10755 mDischargeScreenOnUnplugLevel = 0;
10756 mDischargeScreenOffUnplugLevel = level;
10757 }
10758 mDischargeAmountScreenOn = 0;
10759 mDischargeAmountScreenOff = 0;
Jeff Browne95c3cd2014-05-02 16:59:26 -070010760 updateTimeBasesLocked(true, !screenOn, uptime, realtime);
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010761 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010762 mLastChargingStateLevel = level;
Dianne Hackbornd1eccbe2015-02-18 14:02:14 -080010763 mOnBattery = mOnBatteryInternal = false;
Dianne Hackborna7c837f2014-01-15 16:20:44 -080010764 pullPendingStateUpdatesLocked();
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010765 mHistoryCur.batteryLevel = (byte)level;
10766 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
10767 if (DEBUG_HISTORY) Slog.v(TAG, "Battery plugged to: "
10768 + Integer.toHexString(mHistoryCur.states));
Dianne Hackborn40c87252014-03-19 16:55:40 -070010769 addHistoryRecordLocked(mSecRealtime, mSecUptime);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070010770 mDischargeCurrentLevel = mDischargePlugLevel = level;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010771 if (level < mDischargeUnplugLevel) {
10772 mLowDischargeAmountSinceCharge += mDischargeUnplugLevel-level-1;
10773 mHighDischargeAmountSinceCharge += mDischargeUnplugLevel-level;
10774 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070010775 updateDischargeScreenLevelsLocked(screenOn, screenOn);
10776 updateTimeBasesLocked(false, !screenOn, uptime, realtime);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080010777 mChargeStepTracker.init();
Dianne Hackborn260c5022014-04-29 11:23:16 -070010778 mLastChargeStepLevel = level;
Dianne Hackborn29325132014-05-21 15:01:03 -070010779 mMaxChargeStepLevel = level;
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070010780 mInitStepMode = mCurStepMode;
10781 mModStepMode = 0;
Dianne Hackborn32de2f62011-03-09 14:03:35 -080010782 }
10783 if (doWrite || (mLastWriteTime + (60 * 1000)) < mSecRealtime) {
10784 if (mFile != null) {
10785 writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010786 }
10787 }
10788 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010789
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010790 private void startRecordingHistory(final long elapsedRealtimeMs, final long uptimeMs,
10791 boolean reset) {
10792 mRecordingHistory = true;
10793 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn37de0982014-05-09 09:32:18 -070010794 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs,
10795 reset ? HistoryItem.CMD_RESET : HistoryItem.CMD_CURRENT_TIME,
Dianne Hackborna1bd7922014-03-21 11:07:11 -070010796 mHistoryCur);
10797 mHistoryCur.currentTime = 0;
10798 if (reset) {
10799 initActiveHistoryEventsLocked(elapsedRealtimeMs, uptimeMs);
10800 }
10801 }
10802
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070010803 private void recordCurrentTimeChangeLocked(final long currentTime, final long elapsedRealtimeMs,
10804 final long uptimeMs) {
10805 if (mRecordingHistory) {
10806 mHistoryCur.currentTime = currentTime;
10807 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_CURRENT_TIME,
10808 mHistoryCur);
10809 mHistoryCur.currentTime = 0;
10810 }
10811 }
10812
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080010813 private void recordShutdownLocked(final long elapsedRealtimeMs, final long uptimeMs) {
10814 if (mRecordingHistory) {
10815 mHistoryCur.currentTime = System.currentTimeMillis();
Dianne Hackborn29cd7f12015-01-08 10:37:05 -080010816 addHistoryBufferLocked(elapsedRealtimeMs, uptimeMs, HistoryItem.CMD_SHUTDOWN,
10817 mHistoryCur);
10818 mHistoryCur.currentTime = 0;
10819 }
10820 }
10821
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010822 private void scheduleSyncExternalStatsLocked(String reason, int updateFlags) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010823 if (mExternalSync != null) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010824 mExternalSync.scheduleSync(reason, updateFlags);
Adam Lesinskia7c90c82015-06-18 14:52:24 -070010825 }
10826 }
10827
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010828 // This should probably be exposed in the API, though it's not critical
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010829 public static final int BATTERY_PLUGGED_NONE = 0;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070010830
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010831 public void setBatteryStateLocked(int status, int health, int plugType, int level,
Adam Lesinski041d9172016-12-12 12:03:56 -080010832 int temp, int volt, int chargeUAh, int chargeFullUAh) {
Adam Lesinski29ddfe52017-03-29 19:29:00 -070010833 // Temperature is encoded without the signed bit, so clamp any negative temperatures to 0.
10834 temp = Math.max(0, temp);
10835
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010836 final boolean onBattery = plugType == BATTERY_PLUGGED_NONE;
Joe Onoratoabded112016-02-08 16:49:39 -080010837 final long uptime = mClocks.uptimeMillis();
10838 final long elapsedRealtime = mClocks.elapsedRealtime();
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010839 if (!mHaveBatteryLevel) {
10840 mHaveBatteryLevel = true;
10841 // We start out assuming that the device is plugged in (not
10842 // on battery). If our first report is now that we are indeed
10843 // plugged in, then twiddle our state to correctly reflect that
10844 // since we won't be going through the full setOnBattery().
10845 if (onBattery == mOnBattery) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070010846 if (onBattery) {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010847 mHistoryCur.states &= ~HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070010848 } else {
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010849 mHistoryCur.states |= HistoryItem.STATE_BATTERY_PLUGGED_FLAG;
Dianne Hackborn260c5022014-04-29 11:23:16 -070010850 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010851 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010852 // Always start out assuming charging, that will be updated later.
Dianne Hackborn0c820db2015-04-14 17:47:34 -070010853 mHistoryCur.states2 |= HistoryItem.STATE2_CHARGING_FLAG;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010854 mHistoryCur.batteryStatus = (byte)status;
10855 mHistoryCur.batteryLevel = (byte)level;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010856 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010857 mMaxChargeStepLevel = mMinDischargeStepLevel =
10858 mLastChargeStepLevel = mLastDischargeStepLevel = level;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010859 mLastChargingStateLevel = level;
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010860 } else if (mCurrentBatteryLevel != level || mOnBattery != onBattery) {
10861 recordDailyStatsIfNeededLocked(level >= 100 && onBattery);
10862 }
10863 int oldStatus = mHistoryCur.batteryStatus;
10864 if (onBattery) {
10865 mDischargeCurrentLevel = level;
10866 if (!mRecordingHistory) {
10867 mRecordingHistory = true;
10868 startRecordingHistory(elapsedRealtime, uptime, true);
10869 }
10870 } else if (level < 96) {
10871 if (!mRecordingHistory) {
10872 mRecordingHistory = true;
10873 startRecordingHistory(elapsedRealtime, uptime, true);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070010874 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010875 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010876 mCurrentBatteryLevel = level;
10877 if (mDischargePlugLevel < 0) {
10878 mDischargePlugLevel = level;
Marco Nelissend8593312009-04-30 14:45:06 -070010879 }
Adam Lesinski926969b2016-04-28 17:31:12 -070010880
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010881 if (onBattery != mOnBattery) {
10882 mHistoryCur.batteryLevel = (byte)level;
10883 mHistoryCur.batteryStatus = (byte)status;
10884 mHistoryCur.batteryHealth = (byte)health;
10885 mHistoryCur.batteryPlugType = (byte)plugType;
10886 mHistoryCur.batteryTemperature = (short)temp;
10887 mHistoryCur.batteryVoltage = (char)volt;
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010888 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
10889 // Only record discharges
10890 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
10891 mDischargeCounter.addCountLocked(chargeDiff);
10892 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
10893 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070010894 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070010895 setOnBatteryLocked(elapsedRealtime, uptime, onBattery, oldStatus, level, chargeUAh);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010896 } else {
10897 boolean changed = false;
10898 if (mHistoryCur.batteryLevel != level) {
10899 mHistoryCur.batteryLevel = (byte)level;
10900 changed = true;
Marco Nelissend8593312009-04-30 14:45:06 -070010901
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010902 // TODO(adamlesinski): Schedule the creation of a HistoryStepDetails record
10903 // which will pull external stats.
Adam Lesinski9f55cc72016-01-27 20:42:14 -080010904 scheduleSyncExternalStatsLocked("battery-level", ExternalStatsSync.UPDATE_ALL);
Evan Millarc64edde2009-04-18 12:26:32 -070010905 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010906 if (mHistoryCur.batteryStatus != status) {
10907 mHistoryCur.batteryStatus = (byte)status;
10908 changed = true;
10909 }
10910 if (mHistoryCur.batteryHealth != health) {
10911 mHistoryCur.batteryHealth = (byte)health;
10912 changed = true;
10913 }
10914 if (mHistoryCur.batteryPlugType != plugType) {
10915 mHistoryCur.batteryPlugType = (byte)plugType;
10916 changed = true;
10917 }
10918 if (temp >= (mHistoryCur.batteryTemperature+10)
10919 || temp <= (mHistoryCur.batteryTemperature-10)) {
10920 mHistoryCur.batteryTemperature = (short)temp;
10921 changed = true;
10922 }
10923 if (volt > (mHistoryCur.batteryVoltage+20)
10924 || volt < (mHistoryCur.batteryVoltage-20)) {
10925 mHistoryCur.batteryVoltage = (char)volt;
10926 changed = true;
10927 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070010928 if (chargeUAh >= (mHistoryCur.batteryChargeUAh+10)
10929 || chargeUAh <= (mHistoryCur.batteryChargeUAh-10)) {
Adam Lesinski3ee3f632016-06-08 13:55:55 -070010930 if (chargeUAh < mHistoryCur.batteryChargeUAh) {
10931 // Only record discharges
10932 final long chargeDiff = mHistoryCur.batteryChargeUAh - chargeUAh;
10933 mDischargeCounter.addCountLocked(chargeDiff);
10934 mDischargeScreenOffCounter.addCountLocked(chargeDiff);
10935 }
Adam Lesinskia8018ac2016-05-03 10:18:10 -070010936 mHistoryCur.batteryChargeUAh = chargeUAh;
Adam Lesinski926969b2016-04-28 17:31:12 -070010937 changed = true;
10938 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010939 long modeBits = (((long)mInitStepMode) << STEP_LEVEL_INITIAL_MODE_SHIFT)
10940 | (((long)mModStepMode) << STEP_LEVEL_MODIFIED_MODE_SHIFT)
10941 | (((long)(level&0xff)) << STEP_LEVEL_LEVEL_SHIFT);
10942 if (onBattery) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010943 changed |= setChargingLocked(false);
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010944 if (mLastDischargeStepLevel != level && mMinDischargeStepLevel > level) {
10945 mDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
10946 modeBits, elapsedRealtime);
10947 mDailyDischargeStepTracker.addLevelSteps(mLastDischargeStepLevel - level,
10948 modeBits, elapsedRealtime);
10949 mLastDischargeStepLevel = level;
10950 mMinDischargeStepLevel = level;
10951 mInitStepMode = mCurStepMode;
10952 mModStepMode = 0;
10953 }
10954 } else {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010955 if (level >= 90) {
10956 // If the battery level is at least 90%, always consider the device to be
10957 // charging even if it happens to go down a level.
10958 changed |= setChargingLocked(true);
10959 mLastChargeStepLevel = level;
10960 } if (!mCharging) {
10961 if (mLastChargeStepLevel < level) {
10962 // We have not reporting that we are charging, but the level has now
10963 // gone up, so consider the state to be charging.
10964 changed |= setChargingLocked(true);
10965 mLastChargeStepLevel = level;
10966 }
10967 } else {
10968 if (mLastChargeStepLevel > level) {
10969 // We had reported that the device was charging, but here we are with
10970 // power connected and the level going down. Looks like the current
10971 // power supplied isn't enough, so consider the device to now be
10972 // discharging.
10973 changed |= setChargingLocked(false);
10974 mLastChargeStepLevel = level;
10975 }
10976 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010977 if (mLastChargeStepLevel != level && mMaxChargeStepLevel < level) {
10978 mChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
10979 modeBits, elapsedRealtime);
10980 mDailyChargeStepTracker.addLevelSteps(level - mLastChargeStepLevel,
10981 modeBits, elapsedRealtime);
10982 mLastChargeStepLevel = level;
10983 mMaxChargeStepLevel = level;
10984 mInitStepMode = mCurStepMode;
10985 mModStepMode = 0;
Evan Millarc64edde2009-04-18 12:26:32 -070010986 }
10987 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070010988 if (changed) {
10989 addHistoryRecordLocked(elapsedRealtime, uptime);
10990 }
Evan Millarc64edde2009-04-18 12:26:32 -070010991 }
Adam Lesinski4b6bd8d2015-03-19 14:35:45 -070010992 if (!onBattery && status == BatteryManager.BATTERY_STATUS_FULL) {
10993 // We don't record history while we are plugged in and fully charged.
10994 // The next time we are unplugged, history will be cleared.
10995 mRecordingHistory = DEBUG;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080010996 }
Adam Lesinski041d9172016-12-12 12:03:56 -080010997
Jocelyn Dangc627d102017-04-14 13:15:14 -070010998 if (mMinLearnedBatteryCapacity == -1) {
10999 mMinLearnedBatteryCapacity = chargeFullUAh;
11000 } else {
11001 Math.min(mMinLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski041d9172016-12-12 12:03:56 -080011002 }
Jocelyn Dangc627d102017-04-14 13:15:14 -070011003 mMaxLearnedBatteryCapacity = Math.max(mMaxLearnedBatteryCapacity, chargeFullUAh);
Adam Lesinski33dac552015-03-09 15:24:48 -070011004 }
11005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011006 public long getAwakeTimeBattery() {
11007 return computeBatteryUptime(getBatteryUptimeLocked(), STATS_CURRENT);
11008 }
11009
11010 public long getAwakeTimePlugged() {
Joe Onoratoabded112016-02-08 16:49:39 -080011011 return (mClocks.uptimeMillis() * 1000) - getAwakeTimeBattery();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011012 }
11013
11014 @Override
11015 public long computeUptime(long curTime, int which) {
11016 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011017 case STATS_SINCE_CHARGED: return mUptime + (curTime-mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011018 case STATS_CURRENT: return (curTime-mUptimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070011019 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getUptimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011020 }
11021 return 0;
11022 }
11023
11024 @Override
11025 public long computeRealtime(long curTime, int which) {
11026 switch (which) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011027 case STATS_SINCE_CHARGED: return mRealtime + (curTime-mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011028 case STATS_CURRENT: return (curTime-mRealtimeStart);
Dianne Hackborn4590e522014-03-24 13:36:46 -070011029 case STATS_SINCE_UNPLUGGED: return (curTime-mOnBatteryTimeBase.getRealtimeStart());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011030 }
11031 return 0;
11032 }
11033
11034 @Override
11035 public long computeBatteryUptime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011036 return mOnBatteryTimeBase.computeUptime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011037 }
11038
11039 @Override
11040 public long computeBatteryRealtime(long curTime, int which) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011041 return mOnBatteryTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011042 }
11043
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011044 @Override
11045 public long computeBatteryScreenOffUptime(long curTime, int which) {
11046 return mOnBatteryScreenOffTimeBase.computeUptime(curTime, which);
11047 }
11048
11049 @Override
11050 public long computeBatteryScreenOffRealtime(long curTime, int which) {
11051 return mOnBatteryScreenOffTimeBase.computeRealtime(curTime, which);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011052 }
11053
Dianne Hackborn260c5022014-04-29 11:23:16 -070011054 private long computeTimePerLevel(long[] steps, int numSteps) {
11055 // For now we'll do a simple average across all steps.
11056 if (numSteps <= 0) {
11057 return -1;
11058 }
11059 long total = 0;
11060 for (int i=0; i<numSteps; i++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011061 total += steps[i] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011062 }
11063 return total / numSteps;
11064 /*
11065 long[] buckets = new long[numSteps];
11066 int numBuckets = 0;
11067 int numToAverage = 4;
11068 int i = 0;
11069 while (i < numSteps) {
11070 long totalTime = 0;
11071 int num = 0;
11072 for (int j=0; j<numToAverage && (i+j)<numSteps; j++) {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011073 totalTime += steps[i+j] & STEP_LEVEL_TIME_MASK;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011074 num++;
11075 }
11076 buckets[numBuckets] = totalTime / num;
11077 numBuckets++;
11078 numToAverage *= 2;
11079 i += num;
11080 }
11081 if (numBuckets < 1) {
11082 return -1;
11083 }
11084 long averageTime = buckets[numBuckets-1];
11085 for (i=numBuckets-2; i>=0; i--) {
11086 averageTime = (averageTime + buckets[i]) / 2;
11087 }
11088 return averageTime;
11089 */
11090 }
11091
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011092 @Override
11093 public long computeBatteryTimeRemaining(long curTime) {
11094 if (!mOnBattery) {
11095 return -1;
11096 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070011097 /* Simple implementation just looks at the average discharge per level across the
11098 entire sample period.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011099 int discharge = (getLowDischargeAmountSinceCharge()+getHighDischargeAmountSinceCharge())/2;
11100 if (discharge < 2) {
11101 return -1;
11102 }
11103 long duration = computeBatteryRealtime(curTime, STATS_SINCE_CHARGED);
11104 if (duration < 1000*1000) {
11105 return -1;
11106 }
11107 long usPerLevel = duration/discharge;
11108 return usPerLevel * mCurrentBatteryLevel;
Dianne Hackborn260c5022014-04-29 11:23:16 -070011109 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011110 if (mDischargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070011111 return -1;
11112 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011113 long msPerLevel = mDischargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070011114 if (msPerLevel <= 0) {
11115 return -1;
11116 }
11117 return (msPerLevel * mCurrentBatteryLevel) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011118 }
11119
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011120 @Override
11121 public LevelStepTracker getDischargeLevelStepTracker() {
11122 return mDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070011123 }
11124
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011125 @Override
11126 public LevelStepTracker getDailyDischargeLevelStepTracker() {
11127 return mDailyDischargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070011128 }
11129
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011130 @Override
11131 public long computeChargeTimeRemaining(long curTime) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070011132 if (mOnBattery) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011133 // Not yet working.
11134 return -1;
11135 }
Dianne Hackborn260c5022014-04-29 11:23:16 -070011136 /* Broken
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011137 int curLevel = mCurrentBatteryLevel;
11138 int plugLevel = mDischargePlugLevel;
11139 if (plugLevel < 0 || curLevel < (plugLevel+1)) {
11140 return -1;
11141 }
11142 long duration = computeBatteryRealtime(curTime, STATS_SINCE_UNPLUGGED);
11143 if (duration < 1000*1000) {
11144 return -1;
11145 }
11146 long usPerLevel = duration/(curLevel-plugLevel);
11147 return usPerLevel * (100-curLevel);
Dianne Hackborn260c5022014-04-29 11:23:16 -070011148 */
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011149 if (mChargeStepTracker.mNumStepDurations < 1) {
Dianne Hackborn260c5022014-04-29 11:23:16 -070011150 return -1;
11151 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011152 long msPerLevel = mChargeStepTracker.computeTimePerLevel();
Dianne Hackborn260c5022014-04-29 11:23:16 -070011153 if (msPerLevel <= 0) {
11154 return -1;
11155 }
11156 return (msPerLevel * (100-mCurrentBatteryLevel)) * 1000;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011157 }
11158
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011159 @Override
11160 public LevelStepTracker getChargeLevelStepTracker() {
11161 return mChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070011162 }
11163
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011164 @Override
11165 public LevelStepTracker getDailyChargeLevelStepTracker() {
11166 return mDailyChargeStepTracker;
Dianne Hackbornab5c0ea2014-04-29 14:53:32 -070011167 }
11168
Dianne Hackborn88e98df2015-03-23 13:29:14 -070011169 @Override
11170 public ArrayList<PackageChange> getDailyPackageChanges() {
11171 return mDailyPackageChanges;
11172 }
11173
Joe Onoratoe1acd632016-02-23 13:25:10 -080011174 protected long getBatteryUptimeLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080011175 return mOnBatteryTimeBase.getUptime(mClocks.uptimeMillis() * 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011176 }
11177
11178 @Override
11179 public long getBatteryUptime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011180 return mOnBatteryTimeBase.getUptime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011181 }
11182
11183 @Override
11184 public long getBatteryRealtime(long curTime) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011185 return mOnBatteryTimeBase.getRealtime(curTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011186 }
Amith Yamasani3718aaa2009-06-09 06:32:35 -070011187
The Android Open Source Project10592532009-03-18 17:39:46 -070011188 @Override
Evan Millar633a1742009-04-02 16:36:33 -070011189 public int getDischargeStartLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011190 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070011191 return getDischargeStartLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070011192 }
11193 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011194
Evan Millar633a1742009-04-02 16:36:33 -070011195 public int getDischargeStartLevelLocked() {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011196 return mDischargeUnplugLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070011197 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011198
The Android Open Source Project10592532009-03-18 17:39:46 -070011199 @Override
Evan Millar633a1742009-04-02 16:36:33 -070011200 public int getDischargeCurrentLevel() {
The Android Open Source Project10592532009-03-18 17:39:46 -070011201 synchronized(this) {
Evan Millar633a1742009-04-02 16:36:33 -070011202 return getDischargeCurrentLevelLocked();
The Android Open Source Project10592532009-03-18 17:39:46 -070011203 }
11204 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011205
Evan Millar633a1742009-04-02 16:36:33 -070011206 public int getDischargeCurrentLevelLocked() {
Dianne Hackborne4a59512010-12-07 11:08:07 -080011207 return mDischargeCurrentLevel;
The Android Open Source Project10592532009-03-18 17:39:46 -070011208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011209
Amith Yamasanie43530a2009-08-21 13:11:37 -070011210 @Override
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011211 public int getLowDischargeAmountSinceCharge() {
11212 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080011213 int val = mLowDischargeAmountSinceCharge;
11214 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
11215 val += mDischargeUnplugLevel-mDischargeCurrentLevel-1;
11216 }
11217 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011218 }
11219 }
11220
11221 @Override
11222 public int getHighDischargeAmountSinceCharge() {
11223 synchronized(this) {
Dianne Hackborne4a59512010-12-07 11:08:07 -080011224 int val = mHighDischargeAmountSinceCharge;
11225 if (mOnBattery && mDischargeCurrentLevel < mDischargeUnplugLevel) {
11226 val += mDischargeUnplugLevel-mDischargeCurrentLevel;
11227 }
11228 return val;
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011229 }
11230 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070011231
11232 @Override
11233 public int getDischargeAmount(int which) {
11234 int dischargeAmount = which == STATS_SINCE_CHARGED
11235 ? getHighDischargeAmountSinceCharge()
11236 : (getDischargeStartLevel() - getDischargeCurrentLevel());
11237 if (dischargeAmount < 0) {
11238 dischargeAmount = 0;
11239 }
11240 return dischargeAmount;
11241 }
11242
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011243 public int getDischargeAmountScreenOn() {
11244 synchronized(this) {
11245 int val = mDischargeAmountScreenOn;
Jeff Browne95c3cd2014-05-02 16:59:26 -070011246 if (mOnBattery && mScreenState == Display.STATE_ON
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011247 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
11248 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
11249 }
11250 return val;
11251 }
11252 }
11253
11254 public int getDischargeAmountScreenOnSinceCharge() {
11255 synchronized(this) {
11256 int val = mDischargeAmountScreenOnSinceCharge;
Jeff Browne95c3cd2014-05-02 16:59:26 -070011257 if (mOnBattery && mScreenState == Display.STATE_ON
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011258 && mDischargeCurrentLevel < mDischargeScreenOnUnplugLevel) {
11259 val += mDischargeScreenOnUnplugLevel-mDischargeCurrentLevel;
11260 }
11261 return val;
11262 }
11263 }
11264
11265 public int getDischargeAmountScreenOff() {
11266 synchronized(this) {
11267 int val = mDischargeAmountScreenOff;
Jeff Browne95c3cd2014-05-02 16:59:26 -070011268 if (mOnBattery && mScreenState != Display.STATE_ON
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011269 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
11270 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
11271 }
11272 return val;
11273 }
11274 }
11275
11276 public int getDischargeAmountScreenOffSinceCharge() {
11277 synchronized(this) {
11278 int val = mDischargeAmountScreenOffSinceCharge;
Jeff Browne95c3cd2014-05-02 16:59:26 -070011279 if (mOnBattery && mScreenState != Display.STATE_ON
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011280 && mDischargeCurrentLevel < mDischargeScreenOffUnplugLevel) {
11281 val += mDischargeScreenOffUnplugLevel-mDischargeCurrentLevel;
11282 }
11283 return val;
11284 }
11285 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 /**
11288 * Retrieve the statistics object for a particular uid, creating if needed.
11289 */
11290 public Uid getUidStatsLocked(int uid) {
11291 Uid u = mUidStats.get(uid);
11292 if (u == null) {
Joe Onoratoabded112016-02-08 16:49:39 -080011293 u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011294 mUidStats.put(uid, u);
11295 }
11296 return u;
11297 }
11298
Suprabh Shuklae6e723d2017-06-14 16:14:43 -070011299 public void onCleanupUserLocked(int userId) {
11300 final int firstUidForUser = UserHandle.getUid(userId, 0);
11301 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
11302 mKernelUidCpuFreqTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
11303 mKernelUidCpuTimeReader.removeUidsInRange(firstUidForUser, lastUidForUser);
11304 }
11305
11306 public void onUserRemovedLocked(int userId) {
11307 final int firstUidForUser = UserHandle.getUid(userId, 0);
11308 final int lastUidForUser = UserHandle.getUid(userId, UserHandle.PER_USER_RANGE - 1);
11309 mUidStats.put(firstUidForUser, null);
11310 mUidStats.put(lastUidForUser, null);
11311 final int firstIndex = mUidStats.indexOfKey(firstUidForUser);
11312 final int lastIndex = mUidStats.indexOfKey(lastUidForUser);
11313 mUidStats.removeAtRange(firstIndex, lastIndex - firstIndex + 1);
11314 }
11315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011316 /**
11317 * Remove the statistics object for a particular uid.
11318 */
11319 public void removeUidStatsLocked(int uid) {
Adam Lesinskib83ffee2015-05-12 14:43:47 -070011320 mKernelUidCpuTimeReader.removeUid(uid);
Sudheer Shanka6d8dcec2017-06-01 12:09:03 -070011321 mKernelUidCpuFreqTimeReader.removeUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011322 mUidStats.remove(uid);
11323 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -070011324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011325 /**
11326 * Retrieve the statistics object for a particular process, creating
11327 * if needed.
11328 */
11329 public Uid.Proc getProcessStatsLocked(int uid, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070011330 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 Uid u = getUidStatsLocked(uid);
11332 return u.getProcessStatsLocked(name);
11333 }
11334
11335 /**
11336 * Retrieve the statistics object for a particular process, creating
11337 * if needed.
11338 */
11339 public Uid.Pkg getPackageStatsLocked(int uid, String pkg) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070011340 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011341 Uid u = getUidStatsLocked(uid);
11342 return u.getPackageStatsLocked(pkg);
11343 }
11344
11345 /**
11346 * Retrieve the statistics object for a particular service, creating
11347 * if needed.
11348 */
11349 public Uid.Pkg.Serv getServiceStatsLocked(int uid, String pkg, String name) {
Dianne Hackbornbbb74722014-03-13 09:50:24 -070011350 uid = mapUid(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011351 Uid u = getUidStatsLocked(uid);
11352 return u.getServiceStatsLocked(pkg, name);
11353 }
11354
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011355 public void shutdownLocked() {
Joe Onoratoabded112016-02-08 16:49:39 -080011356 recordShutdownLocked(mClocks.elapsedRealtime(), mClocks.uptimeMillis());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011357 writeSyncLocked();
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011358 mShuttingDown = true;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011359 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011360
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011361 Parcel mPendingWrite = null;
11362 final ReentrantLock mWriteLock = new ReentrantLock();
11363
11364 public void writeAsyncLocked() {
11365 writeLocked(false);
11366 }
11367
11368 public void writeSyncLocked() {
11369 writeLocked(true);
11370 }
11371
11372 void writeLocked(boolean sync) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011373 if (mFile == null) {
11374 Slog.w("BatteryStats", "writeLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011375 return;
11376 }
11377
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011378 if (mShuttingDown) {
11379 return;
11380 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011381
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011382 Parcel out = Parcel.obtain();
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011383 writeSummaryToParcel(out, true);
Joe Onoratoabded112016-02-08 16:49:39 -080011384 mLastWriteTime = mClocks.elapsedRealtime();
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011385
11386 if (mPendingWrite != null) {
11387 mPendingWrite.recycle();
11388 }
11389 mPendingWrite = out;
11390
11391 if (sync) {
11392 commitPendingDataToDisk();
11393 } else {
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011394 BackgroundThread.getHandler().post(new Runnable() {
11395 @Override public void run() {
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011396 commitPendingDataToDisk();
11397 }
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011398 });
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011399 }
11400 }
11401
11402 public void commitPendingDataToDisk() {
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070011403 final Parcel next;
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011404 synchronized (this) {
11405 next = mPendingWrite;
11406 mPendingWrite = null;
Dianne Hackbornf47d8f22010-10-08 10:46:55 -070011407 if (next == null) {
11408 return;
11409 }
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011410 }
11411
Amith Yamasanid2450862017-02-07 15:58:24 -080011412 mWriteLock.lock();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011413 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011414 FileOutputStream stream = new FileOutputStream(mFile.chooseForWrite());
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011415 stream.write(next.marshall());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011416 stream.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070011417 FileUtils.sync(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 stream.close();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011419 mFile.commit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011420 } catch (IOException e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011421 Slog.w("BatteryStats", "Error writing battery statistics", e);
Dianne Hackbornce2ef762010-09-20 11:39:14 -070011422 mFile.rollback();
11423 } finally {
11424 next.recycle();
11425 mWriteLock.unlock();
Suchi Amalapurapu8550f252009-09-29 15:20:32 -070011426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011427 }
11428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011429 public void readLocked() {
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011430 if (mDailyFile != null) {
11431 readDailyStatsLocked();
11432 }
11433
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011434 if (mFile == null) {
11435 Slog.w("BatteryStats", "readLocked: no file associated with this instance");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011436 return;
11437 }
11438
11439 mUidStats.clear();
11440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011441 try {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011442 File file = mFile.chooseForRead();
11443 if (!file.exists()) {
11444 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011445 }
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011446 FileInputStream stream = new FileInputStream(file);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011447
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011448 byte[] raw = BatteryStatsHelper.readFully(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 Parcel in = Parcel.obtain();
11450 in.unmarshall(raw, 0, raw.length);
11451 in.setDataPosition(0);
11452 stream.close();
11453
11454 readSummaryFromParcel(in);
Dianne Hackborn00e25212014-02-19 10:49:24 -080011455 } catch(Exception e) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011456 Slog.e("BatteryStats", "Error reading battery statistics", e);
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011457 resetAllStatsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011458 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011459
Dianne Hackborncd0e3352014-08-07 17:08:09 -070011460 mEndPlatformVersion = Build.ID;
11461
Dianne Hackborne5167ca2014-03-08 14:39:10 -080011462 if (mHistoryBuffer.dataPosition() > 0) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011463 mRecordingHistory = true;
Joe Onoratoabded112016-02-08 16:49:39 -080011464 final long elapsedRealtime = mClocks.elapsedRealtime();
11465 final long uptime = mClocks.uptimeMillis();
Dianne Hackborne5167ca2014-03-08 14:39:10 -080011466 if (USE_OLD_HISTORY) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011467 addHistoryRecordLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
Dianne Hackborne5167ca2014-03-08 14:39:10 -080011468 }
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011469 addHistoryBufferLocked(elapsedRealtime, uptime, HistoryItem.CMD_START, mHistoryCur);
11470 startRecordingHistory(elapsedRealtime, uptime, false);
Dianne Hackborne8c88e62011-08-17 19:09:09 -070011471 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011472
11473 recordDailyStatsIfNeededLocked(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011474 }
11475
11476 public int describeContents() {
11477 return 0;
11478 }
11479
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011480 void readHistory(Parcel in, boolean andOldHistory) throws ParcelFormatException {
Dianne Hackbornae384452011-06-28 12:33:48 -070011481 final long historyBaseTime = in.readLong();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011482
11483 mHistoryBuffer.setDataSize(0);
11484 mHistoryBuffer.setDataPosition(0);
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011485 mHistoryTagPool.clear();
11486 mNextHistoryTagIdx = 0;
11487 mNumHistoryTagChars = 0;
Dianne Hackborn099bc622014-01-22 13:39:16 -080011488
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011489 int numTags = in.readInt();
11490 for (int i=0; i<numTags; i++) {
Dianne Hackborn099bc622014-01-22 13:39:16 -080011491 int idx = in.readInt();
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011492 String str = in.readString();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011493 if (str == null) {
11494 throw new ParcelFormatException("null history tag string");
11495 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011496 int uid = in.readInt();
11497 HistoryTag tag = new HistoryTag();
11498 tag.string = str;
11499 tag.uid = uid;
11500 tag.poolIdx = idx;
11501 mHistoryTagPool.put(tag, idx);
11502 if (idx >= mNextHistoryTagIdx) {
11503 mNextHistoryTagIdx = idx+1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080011504 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011505 mNumHistoryTagChars += tag.string.length() + 1;
Dianne Hackborn099bc622014-01-22 13:39:16 -080011506 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011507
11508 int bufSize = in.readInt();
11509 int curPos = in.dataPosition();
11510 if (bufSize >= (MAX_MAX_HISTORY_BUFFER*3)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011511 throw new ParcelFormatException("File corrupt: history data buffer too large " +
11512 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011513 } else if ((bufSize&~3) != bufSize) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011514 throw new ParcelFormatException("File corrupt: history data buffer not aligned " +
11515 bufSize);
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011516 } else {
11517 if (DEBUG_HISTORY) Slog.i(TAG, "***************** READING NEW HISTORY: " + bufSize
11518 + " bytes at " + curPos);
11519 mHistoryBuffer.appendFrom(in, curPos, bufSize);
11520 in.setDataPosition(curPos + bufSize);
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011521 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011522
Dianne Hackbornae384452011-06-28 12:33:48 -070011523 if (andOldHistory) {
11524 readOldHistory(in);
11525 }
11526
11527 if (DEBUG_HISTORY) {
11528 StringBuilder sb = new StringBuilder(128);
11529 sb.append("****************** OLD mHistoryBaseTime: ");
11530 TimeUtils.formatDuration(mHistoryBaseTime, sb);
11531 Slog.i(TAG, sb.toString());
11532 }
11533 mHistoryBaseTime = historyBaseTime;
11534 if (DEBUG_HISTORY) {
11535 StringBuilder sb = new StringBuilder(128);
11536 sb.append("****************** NEW mHistoryBaseTime: ");
11537 TimeUtils.formatDuration(mHistoryBaseTime, sb);
11538 Slog.i(TAG, sb.toString());
11539 }
11540
11541 // We are just arbitrarily going to insert 1 minute from the sample of
11542 // the last run until samples in this run.
11543 if (mHistoryBaseTime > 0) {
Joe Onoratoabded112016-02-08 16:49:39 -080011544 long oldnow = mClocks.elapsedRealtime();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011545 mHistoryBaseTime = mHistoryBaseTime - oldnow + 1;
Dianne Hackbornae384452011-06-28 12:33:48 -070011546 if (DEBUG_HISTORY) {
11547 StringBuilder sb = new StringBuilder(128);
11548 sb.append("****************** ADJUSTED mHistoryBaseTime: ");
11549 TimeUtils.formatDuration(mHistoryBaseTime, sb);
11550 Slog.i(TAG, sb.toString());
11551 }
Dianne Hackborn1e4b9f32010-06-23 14:10:57 -070011552 }
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011553 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011554
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011555 void readOldHistory(Parcel in) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070011556 if (!USE_OLD_HISTORY) {
11557 return;
11558 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011559 mHistory = mHistoryEnd = mHistoryCache = null;
11560 long time;
Conley Owens5e3357f2011-05-02 09:59:30 -070011561 while (in.dataAvail() > 0 && (time=in.readLong()) >= 0) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011562 HistoryItem rec = new HistoryItem(time, in);
11563 addHistoryRecordLocked(rec);
11564 }
11565 }
11566
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011567 void writeHistory(Parcel out, boolean inclData, boolean andOldHistory) {
Dianne Hackbornae384452011-06-28 12:33:48 -070011568 if (DEBUG_HISTORY) {
11569 StringBuilder sb = new StringBuilder(128);
11570 sb.append("****************** WRITING mHistoryBaseTime: ");
11571 TimeUtils.formatDuration(mHistoryBaseTime, sb);
Dianne Hackborn40c87252014-03-19 16:55:40 -070011572 sb.append(" mLastHistoryElapsedRealtime: ");
11573 TimeUtils.formatDuration(mLastHistoryElapsedRealtime, sb);
Dianne Hackbornae384452011-06-28 12:33:48 -070011574 Slog.i(TAG, sb.toString());
11575 }
Dianne Hackborn40c87252014-03-19 16:55:40 -070011576 out.writeLong(mHistoryBaseTime + mLastHistoryElapsedRealtime);
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070011577 if (!inclData) {
11578 out.writeInt(0);
11579 out.writeInt(0);
11580 return;
11581 }
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011582 out.writeInt(mHistoryTagPool.size());
11583 for (HashMap.Entry<HistoryTag, Integer> ent : mHistoryTagPool.entrySet()) {
11584 HistoryTag tag = ent.getKey();
Dianne Hackborn099bc622014-01-22 13:39:16 -080011585 out.writeInt(ent.getValue());
Dianne Hackborn71fc13e2014-02-03 10:50:53 -080011586 out.writeString(tag.string);
11587 out.writeInt(tag.uid);
Dianne Hackborn099bc622014-01-22 13:39:16 -080011588 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011589 out.writeInt(mHistoryBuffer.dataSize());
11590 if (DEBUG_HISTORY) Slog.i(TAG, "***************** WRITING HISTORY: "
11591 + mHistoryBuffer.dataSize() + " bytes at " + out.dataPosition());
11592 out.appendFrom(mHistoryBuffer, 0, mHistoryBuffer.dataSize());
Dianne Hackbornae384452011-06-28 12:33:48 -070011593
11594 if (andOldHistory) {
11595 writeOldHistory(out);
11596 }
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070011597 }
11598
11599 void writeOldHistory(Parcel out) {
Dianne Hackborne8c88e62011-08-17 19:09:09 -070011600 if (!USE_OLD_HISTORY) {
11601 return;
11602 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011603 HistoryItem rec = mHistory;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070011604 while (rec != null) {
11605 if (rec.time >= 0) rec.writeToParcel(out, 0);
11606 rec = rec.next;
11607 }
11608 out.writeLong(-1);
11609 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011610
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011611 public void readSummaryFromParcel(Parcel in) throws ParcelFormatException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011612 final int version = in.readInt();
11613 if (version != VERSION) {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011614 Slog.w("BatteryStats", "readFromParcel: version got " + version
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011615 + ", expected " + VERSION + "; erasing old stats");
11616 return;
11617 }
11618
Dianne Hackbornae384452011-06-28 12:33:48 -070011619 readHistory(in, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011621 mStartCount = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011622 mUptime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011623 mRealtime = in.readLong();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080011624 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070011625 mStartPlatformVersion = in.readString();
11626 mEndPlatformVersion = in.readString();
Dianne Hackborn97ae5382014-03-05 16:43:25 -080011627 mOnBatteryTimeBase.readSummaryFromParcel(in);
11628 mOnBatteryScreenOffTimeBase.readSummaryFromParcel(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011629 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011630 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070011631 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011632 mCurrentBatteryLevel = in.readInt();
Adam Lesinskif9b20a92016-06-17 17:30:01 -070011633 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070011634 mMinLearnedBatteryCapacity = in.readInt();
11635 mMaxLearnedBatteryCapacity = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070011636 mLowDischargeAmountSinceCharge = in.readInt();
11637 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080011638 mDischargeAmountScreenOnSinceCharge = in.readInt();
11639 mDischargeAmountScreenOffSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011640 mDischargeStepTracker.readFromParcel(in);
11641 mChargeStepTracker.readFromParcel(in);
11642 mDailyDischargeStepTracker.readFromParcel(in);
11643 mDailyChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070011644 mDischargeCounter.readSummaryFromParcelLocked(in);
11645 mDischargeScreenOffCounter.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070011646 int NPKG = in.readInt();
11647 if (NPKG > 0) {
11648 mDailyPackageChanges = new ArrayList<>(NPKG);
11649 while (NPKG > 0) {
11650 NPKG--;
11651 PackageChange pc = new PackageChange();
11652 pc.mPackageName = in.readString();
11653 pc.mUpdate = in.readInt() != 0;
11654 pc.mVersionCode = in.readInt();
11655 mDailyPackageChanges.add(pc);
11656 }
11657 } else {
11658 mDailyPackageChanges = null;
11659 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080011660 mDailyStartTime = in.readLong();
11661 mNextMinDailyDeadline = in.readLong();
11662 mNextMaxDailyDeadline = in.readLong();
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011664 mStartCount++;
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011665
Jeff Browne95c3cd2014-05-02 16:59:26 -070011666 mScreenState = Display.STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011667 mScreenOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn617f8772009-03-31 15:04:46 -070011668 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
11669 mScreenBrightnessTimer[i].readSummaryFromParcelLocked(in);
11670 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070011671 mInteractive = false;
11672 mInteractiveTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011673 mPhoneOn = false;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070011674 mPowerSaveModeEnabledTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070011675 mLongestLightIdleTime = in.readLong();
11676 mLongestFullIdleTime = in.readLong();
11677 mDeviceIdleModeLightTimer.readSummaryFromParcelLocked(in);
11678 mDeviceIdleModeFullTimer.readSummaryFromParcelLocked(in);
11679 mDeviceLightIdlingTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070011680 mDeviceIdlingTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011681 mPhoneOnTimer.readSummaryFromParcelLocked(in);
Wink Saville52840902011-02-18 12:40:47 -080011682 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn627bba72009-03-24 22:32:56 -070011683 mPhoneSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
11684 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070011685 mPhoneSignalScanningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn627bba72009-03-24 22:32:56 -070011686 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
11687 mPhoneDataConnectionsTimer[i].readSummaryFromParcelLocked(in);
11688 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011689 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080011690 mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
11691 mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011692 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070011693 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborne13c4c02014-02-11 17:18:35 -080011694 mMobileRadioActiveTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn77b987f2014-02-26 16:20:52 -080011695 mMobileRadioActivePerAppTimer.readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011696 mMobileRadioActiveAdjustedTime.readSummaryFromParcelLocked(in);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080011697 mMobileRadioActiveUnknownTime.readSummaryFromParcelLocked(in);
11698 mMobileRadioActiveUnknownCount.readSummaryFromParcelLocked(in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070011699 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
The Android Open Source Project10592532009-03-18 17:39:46 -070011700 mWifiOn = false;
11701 mWifiOnTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070011702 mGlobalWifiRunning = false;
11703 mGlobalWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080011704 for (int i=0; i<NUM_WIFI_STATES; i++) {
11705 mWifiStateTimer[i].readSummaryFromParcelLocked(in);
11706 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070011707 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
11708 mWifiSupplStateTimer[i].readSummaryFromParcelLocked(in);
11709 }
11710 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
11711 mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
11712 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080011713 mWifiActivity.readSummaryFromParcel(in);
11714 mBluetoothActivity.readSummaryFromParcel(in);
11715 mModemActivity.readSummaryFromParcel(in);
11716 mHasWifiReporting = in.readInt() != 0;
11717 mHasBluetoothReporting = in.readInt() != 0;
11718 mHasModemReporting = in.readInt() != 0;
Adam Lesinski33dac552015-03-09 15:24:48 -070011719
Dianne Hackborn1e01d162014-12-04 17:46:42 -080011720 mNumConnectivityChange = mLoadedNumConnectivityChange = in.readInt();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011721 mFlashlightOnNesting = 0;
Dianne Hackbornabc7c492014-06-30 16:57:46 -070011722 mFlashlightOnTimer.readSummaryFromParcelLocked(in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011723 mCameraOnNesting = 0;
11724 mCameraOnTimer.readSummaryFromParcelLocked(in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011725 mBluetoothScanNesting = 0;
11726 mBluetoothScanTimer.readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011727
Evan Millarc64edde2009-04-18 12:26:32 -070011728 int NKW = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011729 if (NKW > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011730 throw new ParcelFormatException("File corrupt: too many kernel wake locks " + NKW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011731 }
Evan Millarc64edde2009-04-18 12:26:32 -070011732 for (int ikw = 0; ikw < NKW; ikw++) {
11733 if (in.readInt() != 0) {
11734 String kwltName = in.readString();
11735 getKernelWakelockTimerLocked(kwltName).readSummaryFromParcelLocked(in);
11736 }
11737 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070011738
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011739 int NWR = in.readInt();
11740 if (NWR > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011741 throw new ParcelFormatException("File corrupt: too many wakeup reasons " + NWR);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011742 }
11743 for (int iwr = 0; iwr < NWR; iwr++) {
11744 if (in.readInt() != 0) {
11745 String reasonName = in.readString();
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070011746 getWakeupReasonTimerLocked(reasonName).readSummaryFromParcelLocked(in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070011747 }
11748 }
11749
James Carr3a226052016-07-01 14:49:52 -070011750 int NMS = in.readInt();
11751 for (int ims = 0; ims < NMS; ims++) {
11752 if (in.readInt() != 0) {
11753 long kmstName = in.readLong();
11754 getKernelMemoryTimerLocked(kmstName).readSummaryFromParcelLocked(in);
11755 }
11756 }
11757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011758 final int NU = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011759 if (NU > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011760 throw new ParcelFormatException("File corrupt: too many uids " + NU);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011762 for (int iu = 0; iu < NU; iu++) {
11763 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080011764 Uid u = new Uid(this, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011765 mUidStats.put(uid, u);
11766
Bookatz867c0d72017-03-07 18:23:42 -080011767 u.mOnBatteryBackgroundTimeBase.readSummaryFromParcel(in);
Bookatzc8c44962017-05-11 12:12:54 -070011768 u.mOnBatteryScreenOffBackgroundTimeBase.readSummaryFromParcel(in);
Bookatz867c0d72017-03-07 18:23:42 -080011769
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070011770 u.mWifiRunning = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011771 if (in.readInt() != 0) {
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070011772 u.mWifiRunningTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011773 }
The Android Open Source Project10592532009-03-18 17:39:46 -070011774 u.mFullWifiLockOut = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011775 if (in.readInt() != 0) {
11776 u.mFullWifiLockTimer.readSummaryFromParcelLocked(in);
11777 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070011778 u.mWifiScanStarted = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011779 if (in.readInt() != 0) {
Nick Pelly6ccaa542012-06-15 15:22:47 -070011780 u.mWifiScanTimer.readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011781 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070011782 u.mWifiBatchedScanBinStarted = Uid.NO_BATCHED_SCAN_STARTED;
11783 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
11784 if (in.readInt() != 0) {
11785 u.makeWifiBatchedScanBin(i, null);
11786 u.mWifiBatchedScanTimer[i].readSummaryFromParcelLocked(in);
11787 }
11788 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070011789 u.mWifiMulticastEnabled = false;
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011790 if (in.readInt() != 0) {
11791 u.mWifiMulticastTimer.readSummaryFromParcelLocked(in);
11792 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011793 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080011794 u.createAudioTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011795 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011796 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080011797 u.createVideoTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
11798 }
11799 if (in.readInt() != 0) {
Ruben Brunk6d2c3632015-05-26 17:32:16 -070011800 u.createFlashlightTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
11801 }
11802 if (in.readInt() != 0) {
11803 u.createCameraTurnedOnTimerLocked().readSummaryFromParcelLocked(in);
11804 }
11805 if (in.readInt() != 0) {
Jeff Sharkey3e013e82013-04-25 14:48:19 -070011806 u.createForegroundActivityTimerLocked().readSummaryFromParcelLocked(in);
11807 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011808 if (in.readInt() != 0) {
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070011809 u.createForegroundServiceTimerLocked().readSummaryFromParcelLocked(in);
11810 }
11811 if (in.readInt() != 0) {
Bookatzc8c44962017-05-11 12:12:54 -070011812 u.createAggregatedPartialWakelockTimerLocked().readSummaryFromParcelLocked(in);
11813 }
11814 if (in.readInt() != 0) {
Adam Lesinski9f55cc72016-01-27 20:42:14 -080011815 u.createBluetoothScanTimerLocked().readSummaryFromParcelLocked(in);
11816 }
Bookatz956f36bf2017-04-28 09:48:17 -070011817 if (in.readInt() != 0) {
Bookatzb1f04f32017-05-19 13:57:32 -070011818 u.createBluetoothUnoptimizedScanTimerLocked().readSummaryFromParcelLocked(in);
11819 }
11820 if (in.readInt() != 0) {
Bookatz956f36bf2017-04-28 09:48:17 -070011821 u.createBluetoothScanResultCounterLocked().readSummaryFromParcelLocked(in);
11822 }
Bookatzb1f04f32017-05-19 13:57:32 -070011823 if (in.readInt() != 0) {
11824 u.createBluetoothScanResultBgCounterLocked().readSummaryFromParcelLocked(in);
11825 }
Dianne Hackborna8d10942015-11-19 17:55:19 -080011826 u.mProcessState = ActivityManager.PROCESS_STATE_NONEXISTENT;
Dianne Hackborn61659e52014-07-09 16:13:01 -070011827 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
11828 if (in.readInt() != 0) {
11829 u.makeProcessState(i, null);
11830 u.mProcessStateTimer[i].readSummaryFromParcelLocked(in);
11831 }
11832 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070011833 if (in.readInt() != 0) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -080011834 u.createVibratorOnTimerLocked().readSummaryFromParcelLocked(in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070011835 }
Robert Greenwalt5347bd42009-05-13 15:10:16 -070011836
Dianne Hackborn617f8772009-03-31 15:04:46 -070011837 if (in.readInt() != 0) {
11838 if (u.mUserActivityCounters == null) {
11839 u.initUserActivityLocked();
11840 }
11841 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
11842 u.mUserActivityCounters[i].readSummaryFromParcelLocked(in);
11843 }
11844 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070011845
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011846 if (in.readInt() != 0) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080011847 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011848 u.initNetworkActivityLocked();
11849 }
11850 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080011851 u.mNetworkByteActivityCounters[i].readSummaryFromParcelLocked(in);
11852 u.mNetworkPacketActivityCounters[i].readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011853 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080011854 u.mMobileRadioActiveTime.readSummaryFromParcelLocked(in);
11855 u.mMobileRadioActiveCount.readSummaryFromParcelLocked(in);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070011856 }
11857
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011858 u.mUserCpuTime.readSummaryFromParcelLocked(in);
11859 u.mSystemCpuTime.readSummaryFromParcelLocked(in);
11860
Adam Lesinski6832f392015-09-05 18:05:40 -070011861 if (in.readInt() != 0) {
11862 final int numClusters = in.readInt();
11863 if (mPowerProfile != null && mPowerProfile.getNumCpuClusters() != numClusters) {
11864 throw new ParcelFormatException("Incompatible cpu cluster arrangement");
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011865 }
Adam Lesinski6832f392015-09-05 18:05:40 -070011866
Sudheer Shankaaf857412017-07-21 00:14:24 -070011867 u.mCpuClusterSpeedTimesUs = new LongSamplingCounter[numClusters][];
Adam Lesinski6832f392015-09-05 18:05:40 -070011868 for (int cluster = 0; cluster < numClusters; cluster++) {
Adam Lesinski6832f392015-09-05 18:05:40 -070011869 if (in.readInt() != 0) {
Adam Lesinskia57a5402015-09-28 10:21:33 -070011870 final int NSB = in.readInt();
11871 if (mPowerProfile != null &&
11872 mPowerProfile.getNumSpeedStepsInCpuCluster(cluster) != NSB) {
11873 throw new ParcelFormatException("File corrupt: too many speed bins " +
11874 NSB);
11875 }
11876
Sudheer Shankaaf857412017-07-21 00:14:24 -070011877 u.mCpuClusterSpeedTimesUs[cluster] = new LongSamplingCounter[NSB];
Adam Lesinski6832f392015-09-05 18:05:40 -070011878 for (int speed = 0; speed < NSB; speed++) {
11879 if (in.readInt() != 0) {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011880 u.mCpuClusterSpeedTimesUs[cluster][speed] = new LongSamplingCounter(
Adam Lesinski6832f392015-09-05 18:05:40 -070011881 mOnBatteryTimeBase);
Sudheer Shankaaf857412017-07-21 00:14:24 -070011882 u.mCpuClusterSpeedTimesUs[cluster][speed].readSummaryFromParcelLocked(in);
Adam Lesinski6832f392015-09-05 18:05:40 -070011883 }
11884 }
Adam Lesinskia57a5402015-09-28 10:21:33 -070011885 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011886 u.mCpuClusterSpeedTimesUs[cluster] = null;
Adam Lesinski6832f392015-09-05 18:05:40 -070011887 }
11888 }
11889 } else {
Sudheer Shankaaf857412017-07-21 00:14:24 -070011890 u.mCpuClusterSpeedTimesUs = null;
Adam Lesinski06af1fa2015-05-05 17:35:35 -070011891 }
11892
Sudheer Shanka59f5c002017-05-15 10:57:15 -070011893 u.mCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
11894 in, mOnBatteryTimeBase);
11895 u.mScreenOffCpuFreqTimeMs = LongSamplingCounterArray.readSummaryFromParcelLocked(
11896 in, mOnBatteryScreenOffTimeBase);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070011897
11898 if (in.readInt() != 0) {
Adam Lesinski5f056f62016-07-14 16:56:08 -070011899 u.mMobileRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
11900 u.mMobileRadioApWakeupCount.readSummaryFromParcelLocked(in);
11901 } else {
11902 u.mMobileRadioApWakeupCount = null;
11903 }
11904
11905 if (in.readInt() != 0) {
11906 u.mWifiRadioApWakeupCount = new LongSamplingCounter(mOnBatteryTimeBase);
11907 u.mWifiRadioApWakeupCount.readSummaryFromParcelLocked(in);
11908 } else {
11909 u.mWifiRadioApWakeupCount = null;
11910 }
11911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011912 int NW = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070011913 if (NW > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011914 throw new ParcelFormatException("File corrupt: too many wake locks " + NW);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011916 for (int iw = 0; iw < NW; iw++) {
11917 String wlName = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070011918 u.readWakeSummaryFromParcelLocked(wlName, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011919 }
11920
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011921 int NS = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070011922 if (NS > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011923 throw new ParcelFormatException("File corrupt: too many syncs " + NS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011924 }
11925 for (int is = 0; is < NS; is++) {
11926 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070011927 u.readSyncSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011928 }
11929
11930 int NJ = in.readInt();
Dianne Hackborncb99a722016-10-03 17:00:02 -070011931 if (NJ > (MAX_WAKELOCKS_PER_UID+1)) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011932 throw new ParcelFormatException("File corrupt: too many job timers " + NJ);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011933 }
11934 for (int ij = 0; ij < NJ; ij++) {
11935 String name = in.readString();
Dianne Hackbornd953c532014-08-16 18:17:38 -070011936 u.readJobSummaryFromParcelLocked(name, in);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011937 }
11938
Dianne Hackborn94326cb2017-06-28 16:17:20 -070011939 u.readJobCompletionsFromParcelLocked(in);
11940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011941 int NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080011942 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011943 throw new ParcelFormatException("File corrupt: too many sensors " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011945 for (int is = 0; is < NP; is++) {
11946 int seNumber = in.readInt();
11947 if (in.readInt() != 0) {
Bookatz867c0d72017-03-07 18:23:42 -080011948 u.getSensorTimerLocked(seNumber, true).readSummaryFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011949 }
11950 }
11951
11952 NP = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080011953 if (NP > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011954 throw new ParcelFormatException("File corrupt: too many processes " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011956 for (int ip = 0; ip < NP; ip++) {
11957 String procName = in.readString();
11958 Uid.Proc p = u.getProcessStatsLocked(procName);
11959 p.mUserTime = p.mLoadedUserTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011960 p.mSystemTime = p.mLoadedSystemTime = in.readLong();
Jeff Sharkey3e013e82013-04-25 14:48:19 -070011961 p.mForegroundTime = p.mLoadedForegroundTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011962 p.mStarts = p.mLoadedStarts = in.readInt();
Dianne Hackborn1e01d162014-12-04 17:46:42 -080011963 p.mNumCrashes = p.mLoadedNumCrashes = in.readInt();
11964 p.mNumAnrs = p.mLoadedNumAnrs = in.readInt();
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011965 p.readExcessivePowerFromParcelLocked(in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011966 }
11967
11968 NP = in.readInt();
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011969 if (NP > 10000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011970 throw new ParcelFormatException("File corrupt: too many packages " + NP);
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070011971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011972 for (int ip = 0; ip < NP; ip++) {
11973 String pkgName = in.readString();
11974 Uid.Pkg p = u.getPackageStatsLocked(pkgName);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070011975 final int NWA = in.readInt();
11976 if (NWA > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011977 throw new ParcelFormatException("File corrupt: too many wakeup alarms " + NWA);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070011978 }
11979 p.mWakeupAlarms.clear();
11980 for (int iwa=0; iwa<NWA; iwa++) {
11981 String tag = in.readString();
Bookatz98d4d5c2017-08-01 19:07:54 -070011982 Counter c = new Counter(mOnBatteryScreenOffTimeBase);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070011983 c.readSummaryFromParcelLocked(in);
11984 p.mWakeupAlarms.put(tag, c);
11985 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070011986 NS = in.readInt();
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080011987 if (NS > 1000) {
Adam Lesinski9ae9cba2015-07-08 17:09:34 -070011988 throw new ParcelFormatException("File corrupt: too many services " + NS);
Dianne Hackborn7b9c56f2010-12-07 11:14:53 -080011989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011990 for (int is = 0; is < NS; is++) {
11991 String servName = in.readString();
11992 Uid.Pkg.Serv s = u.getServiceStatsLocked(pkgName, servName);
11993 s.mStartTime = s.mLoadedStartTime = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011994 s.mStarts = s.mLoadedStarts = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011995 s.mLaunches = s.mLoadedLaunches = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011996 }
11997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011998 }
11999 }
12000
12001 /**
12002 * Writes a summary of the statistics to a Parcel, in a format suitable to be written to
12003 * disk. This format does not allow a lossless round-trip.
12004 *
12005 * @param out the Parcel to be written to.
12006 */
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012007 public void writeSummaryToParcel(Parcel out, boolean inclHistory) {
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080012008 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012009
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012010 // Pull the clock time. This may update the time and make a new history entry
12011 // if we had originally pulled a time before the RTC was set.
12012 long startClockTime = getStartClockTime();
12013
Joe Onoratoabded112016-02-08 16:49:39 -080012014 final long NOW_SYS = mClocks.uptimeMillis() * 1000;
12015 final long NOWREAL_SYS = mClocks.elapsedRealtime() * 1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012016
12017 out.writeInt(VERSION);
12018
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012019 writeHistory(out, inclHistory, true);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012021 out.writeInt(mStartCount);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012022 out.writeLong(computeUptime(NOW_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012023 out.writeLong(computeRealtime(NOWREAL_SYS, STATS_SINCE_CHARGED));
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012024 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070012025 out.writeString(mStartPlatformVersion);
12026 out.writeString(mEndPlatformVersion);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012027 mOnBatteryTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
12028 mOnBatteryScreenOffTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012029 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012030 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070012031 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012032 out.writeInt(mCurrentBatteryLevel);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012033 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070012034 out.writeInt(mMinLearnedBatteryCapacity);
12035 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborne4a59512010-12-07 11:08:07 -080012036 out.writeInt(getLowDischargeAmountSinceCharge());
12037 out.writeInt(getHighDischargeAmountSinceCharge());
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012038 out.writeInt(getDischargeAmountScreenOnSinceCharge());
12039 out.writeInt(getDischargeAmountScreenOffSinceCharge());
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012040 mDischargeStepTracker.writeToParcel(out);
12041 mChargeStepTracker.writeToParcel(out);
12042 mDailyDischargeStepTracker.writeToParcel(out);
12043 mDailyChargeStepTracker.writeToParcel(out);
Adam Lesinski67c134f2016-06-10 15:15:08 -070012044 mDischargeCounter.writeSummaryFromParcelLocked(out);
12045 mDischargeScreenOffCounter.writeSummaryFromParcelLocked(out);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012046 if (mDailyPackageChanges != null) {
12047 final int NPKG = mDailyPackageChanges.size();
12048 out.writeInt(NPKG);
12049 for (int i=0; i<NPKG; i++) {
12050 PackageChange pc = mDailyPackageChanges.get(i);
12051 out.writeString(pc.mPackageName);
12052 out.writeInt(pc.mUpdate ? 1 : 0);
12053 out.writeInt(pc.mVersionCode);
12054 }
12055 } else {
12056 out.writeInt(0);
12057 }
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012058 out.writeLong(mDailyStartTime);
12059 out.writeLong(mNextMinDailyDeadline);
12060 out.writeLong(mNextMaxDailyDeadline);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012061
12062 mScreenOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070012063 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012064 mScreenBrightnessTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn617f8772009-03-31 15:04:46 -070012065 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070012066 mInteractiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070012067 mPowerSaveModeEnabledTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070012068 out.writeLong(mLongestLightIdleTime);
12069 out.writeLong(mLongestFullIdleTime);
12070 mDeviceIdleModeLightTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12071 mDeviceIdleModeFullTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12072 mDeviceLightIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012073 mDeviceIdlingTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012074 mPhoneOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Wink Saville52840902011-02-18 12:40:47 -080012075 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012076 mPhoneSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070012077 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012078 mPhoneSignalScanningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070012079 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012080 mPhoneDataConnectionsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn627bba72009-03-24 22:32:56 -070012081 }
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012082 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080012083 mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
12084 mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012085 }
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012086 mMobileRadioActiveTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12087 mMobileRadioActivePerAppTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012088 mMobileRadioActiveAdjustedTime.writeSummaryFromParcelLocked(out);
Dianne Hackbornd45665b2014-02-26 12:35:32 -080012089 mMobileRadioActiveUnknownTime.writeSummaryFromParcelLocked(out);
12090 mMobileRadioActiveUnknownCount.writeSummaryFromParcelLocked(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012091 mWifiOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12092 mGlobalWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080012093 for (int i=0; i<NUM_WIFI_STATES; i++) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012094 mWifiStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornca1bf212014-02-14 14:18:36 -080012095 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070012096 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12097 mWifiSupplStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12098 }
12099 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12100 mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12101 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080012102 mWifiActivity.writeSummaryToParcel(out);
12103 mBluetoothActivity.writeSummaryToParcel(out);
12104 mModemActivity.writeSummaryToParcel(out);
12105 out.writeInt(mHasWifiReporting ? 1 : 0);
12106 out.writeInt(mHasBluetoothReporting ? 1 : 0);
12107 out.writeInt(mHasModemReporting ? 1 : 0);
12108
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012109 out.writeInt(mNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070012110 mFlashlightOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012111 mCameraOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012112 mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012113
Evan Millarc64edde2009-04-18 12:26:32 -070012114 out.writeInt(mKernelWakelockStats.size());
12115 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
12116 Timer kwlt = ent.getValue();
12117 if (kwlt != null) {
12118 out.writeInt(1);
12119 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012120 kwlt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12121 } else {
12122 out.writeInt(0);
12123 }
12124 }
12125
12126 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012127 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
12128 SamplingTimer timer = ent.getValue();
12129 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012130 out.writeInt(1);
12131 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012132 timer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Evan Millarc64edde2009-04-18 12:26:32 -070012133 } else {
12134 out.writeInt(0);
12135 }
12136 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012137
James Carr3a226052016-07-01 14:49:52 -070012138 out.writeInt(mKernelMemoryStats.size());
12139 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
12140 Timer kmt = mKernelMemoryStats.valueAt(i);
12141 if (kmt != null) {
12142 out.writeInt(1);
12143 out.writeLong(mKernelMemoryStats.keyAt(i));
12144 kmt.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12145 } else {
12146 out.writeInt(0);
12147 }
12148 }
12149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012150 final int NU = mUidStats.size();
12151 out.writeInt(NU);
12152 for (int iu = 0; iu < NU; iu++) {
12153 out.writeInt(mUidStats.keyAt(iu));
12154 Uid u = mUidStats.valueAt(iu);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012155
Bookatz867c0d72017-03-07 18:23:42 -080012156 u.mOnBatteryBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatzc8c44962017-05-11 12:12:54 -070012157 u.mOnBatteryScreenOffBackgroundTimeBase.writeSummaryToParcel(out, NOW_SYS, NOWREAL_SYS);
Bookatz867c0d72017-03-07 18:23:42 -080012158
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012159 if (u.mWifiRunningTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012160 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012161 u.mWifiRunningTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012162 } else {
12163 out.writeInt(0);
12164 }
12165 if (u.mFullWifiLockTimer != null) {
12166 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012167 u.mFullWifiLockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012168 } else {
12169 out.writeInt(0);
12170 }
Nick Pelly6ccaa542012-06-15 15:22:47 -070012171 if (u.mWifiScanTimer != null) {
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012172 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012173 u.mWifiScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012174 } else {
12175 out.writeInt(0);
12176 }
Robert Greenwalta029ea12013-09-25 16:38:12 -070012177 for (int i = 0; i < Uid.NUM_WIFI_BATCHED_SCAN_BINS; i++) {
12178 if (u.mWifiBatchedScanTimer[i] != null) {
12179 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012180 u.mWifiBatchedScanTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Robert Greenwalta029ea12013-09-25 16:38:12 -070012181 } else {
12182 out.writeInt(0);
12183 }
12184 }
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012185 if (u.mWifiMulticastTimer != null) {
12186 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012187 u.mWifiMulticastTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012188 } else {
12189 out.writeInt(0);
12190 }
12191 if (u.mAudioTurnedOnTimer != null) {
12192 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012193 u.mAudioTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012194 } else {
12195 out.writeInt(0);
12196 }
12197 if (u.mVideoTurnedOnTimer != null) {
12198 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012199 u.mVideoTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012200 } else {
12201 out.writeInt(0);
12202 }
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012203 if (u.mFlashlightTurnedOnTimer != null) {
12204 out.writeInt(1);
12205 u.mFlashlightTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12206 } else {
12207 out.writeInt(0);
12208 }
12209 if (u.mCameraTurnedOnTimer != null) {
12210 out.writeInt(1);
12211 u.mCameraTurnedOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12212 } else {
12213 out.writeInt(0);
12214 }
Jeff Sharkey3e013e82013-04-25 14:48:19 -070012215 if (u.mForegroundActivityTimer != null) {
12216 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012217 u.mForegroundActivityTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Jeff Sharkey3e013e82013-04-25 14:48:19 -070012218 } else {
12219 out.writeInt(0);
12220 }
Michael Wachenschwanzb05a3c52017-07-07 17:47:04 -070012221 if (u.mForegroundServiceTimer != null) {
12222 out.writeInt(1);
12223 u.mForegroundServiceTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12224 } else {
12225 out.writeInt(0);
12226 }
Bookatzc8c44962017-05-11 12:12:54 -070012227 if (u.mAggregatedPartialWakelockTimer != null) {
12228 out.writeInt(1);
12229 u.mAggregatedPartialWakelockTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12230 } else {
12231 out.writeInt(0);
12232 }
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012233 if (u.mBluetoothScanTimer != null) {
12234 out.writeInt(1);
12235 u.mBluetoothScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12236 } else {
12237 out.writeInt(0);
12238 }
Bookatzb1f04f32017-05-19 13:57:32 -070012239 if (u.mBluetoothUnoptimizedScanTimer != null) {
12240 out.writeInt(1);
12241 u.mBluetoothUnoptimizedScanTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12242 } else {
12243 out.writeInt(0);
12244 }
Bookatz956f36bf2017-04-28 09:48:17 -070012245 if (u.mBluetoothScanResultCounter != null) {
12246 out.writeInt(1);
12247 u.mBluetoothScanResultCounter.writeSummaryFromParcelLocked(out);
12248 } else {
12249 out.writeInt(0);
12250 }
Bookatzb1f04f32017-05-19 13:57:32 -070012251 if (u.mBluetoothScanResultBgCounter != null) {
12252 out.writeInt(1);
12253 u.mBluetoothScanResultBgCounter.writeSummaryFromParcelLocked(out);
12254 } else {
12255 out.writeInt(0);
12256 }
Dianne Hackborn61659e52014-07-09 16:13:01 -070012257 for (int i = 0; i < Uid.NUM_PROCESS_STATE; i++) {
12258 if (u.mProcessStateTimer[i] != null) {
12259 out.writeInt(1);
12260 u.mProcessStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12261 } else {
12262 out.writeInt(0);
12263 }
12264 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -080012265 if (u.mVibratorOnTimer != null) {
12266 out.writeInt(1);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012267 u.mVibratorOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackborna06de0f2012-12-11 16:34:47 -080012268 } else {
12269 out.writeInt(0);
12270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012271
Dianne Hackborn617f8772009-03-31 15:04:46 -070012272 if (u.mUserActivityCounters == null) {
12273 out.writeInt(0);
12274 } else {
12275 out.writeInt(1);
12276 for (int i=0; i<Uid.NUM_USER_ACTIVITY_TYPES; i++) {
12277 u.mUserActivityCounters[i].writeSummaryFromParcelLocked(out);
12278 }
12279 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012280
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080012281 if (u.mNetworkByteActivityCounters == null) {
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012282 out.writeInt(0);
12283 } else {
12284 out.writeInt(1);
12285 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
Dianne Hackborn57ed6a62013-12-09 18:15:56 -080012286 u.mNetworkByteActivityCounters[i].writeSummaryFromParcelLocked(out);
12287 u.mNetworkPacketActivityCounters[i].writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012288 }
Dianne Hackbornd45665b2014-02-26 12:35:32 -080012289 u.mMobileRadioActiveTime.writeSummaryFromParcelLocked(out);
12290 u.mMobileRadioActiveCount.writeSummaryFromParcelLocked(out);
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070012291 }
12292
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012293 u.mUserCpuTime.writeSummaryFromParcelLocked(out);
12294 u.mSystemCpuTime.writeSummaryFromParcelLocked(out);
12295
Sudheer Shankaaf857412017-07-21 00:14:24 -070012296 if (u.mCpuClusterSpeedTimesUs != null) {
Adam Lesinski6832f392015-09-05 18:05:40 -070012297 out.writeInt(1);
Sudheer Shankaaf857412017-07-21 00:14:24 -070012298 out.writeInt(u.mCpuClusterSpeedTimesUs.length);
12299 for (LongSamplingCounter[] cpuSpeeds : u.mCpuClusterSpeedTimesUs) {
Adam Lesinski6832f392015-09-05 18:05:40 -070012300 if (cpuSpeeds != null) {
12301 out.writeInt(1);
12302 out.writeInt(cpuSpeeds.length);
12303 for (LongSamplingCounter c : cpuSpeeds) {
12304 if (c != null) {
12305 out.writeInt(1);
12306 c.writeSummaryFromParcelLocked(out);
12307 } else {
12308 out.writeInt(0);
12309 }
12310 }
12311 } else {
12312 out.writeInt(0);
12313 }
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012314 }
Adam Lesinski6832f392015-09-05 18:05:40 -070012315 } else {
12316 out.writeInt(0);
Adam Lesinski06af1fa2015-05-05 17:35:35 -070012317 }
12318
Sudheer Shanka59f5c002017-05-15 10:57:15 -070012319 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mCpuFreqTimeMs);
12320 LongSamplingCounterArray.writeSummaryToParcelLocked(out, u.mScreenOffCpuFreqTimeMs);
Sudheer Shanka9b735c52017-05-09 18:26:18 -070012321
Adam Lesinski5f056f62016-07-14 16:56:08 -070012322 if (u.mMobileRadioApWakeupCount != null) {
12323 out.writeInt(1);
12324 u.mMobileRadioApWakeupCount.writeSummaryFromParcelLocked(out);
12325 } else {
12326 out.writeInt(0);
12327 }
12328
12329 if (u.mWifiRadioApWakeupCount != null) {
12330 out.writeInt(1);
12331 u.mWifiRadioApWakeupCount.writeSummaryFromParcelLocked(out);
12332 } else {
12333 out.writeInt(0);
12334 }
12335
Dianne Hackbornd953c532014-08-16 18:17:38 -070012336 final ArrayMap<String, Uid.Wakelock> wakeStats = u.mWakelockStats.getMap();
12337 int NW = wakeStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012338 out.writeInt(NW);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012339 for (int iw=0; iw<NW; iw++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070012340 out.writeString(wakeStats.keyAt(iw));
12341 Uid.Wakelock wl = wakeStats.valueAt(iw);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012342 if (wl.mTimerFull != null) {
12343 out.writeInt(1);
12344 wl.mTimerFull.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12345 } else {
12346 out.writeInt(0);
12347 }
12348 if (wl.mTimerPartial != null) {
12349 out.writeInt(1);
12350 wl.mTimerPartial.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12351 } else {
12352 out.writeInt(0);
12353 }
12354 if (wl.mTimerWindow != null) {
12355 out.writeInt(1);
12356 wl.mTimerWindow.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12357 } else {
12358 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012359 }
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070012360 if (wl.mTimerDraw != null) {
Adam Lesinski9425fe22015-06-19 12:02:13 -070012361 out.writeInt(1);
Jeff Brown6a8bd7b2015-06-19 15:07:51 -070012362 wl.mTimerDraw.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Adam Lesinski9425fe22015-06-19 12:02:13 -070012363 } else {
12364 out.writeInt(0);
12365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012366 }
12367
Bookatz2bffb5b2017-04-13 11:59:33 -070012368 final ArrayMap<String, DualTimer> syncStats = u.mSyncStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070012369 int NS = syncStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012370 out.writeInt(NS);
12371 for (int is=0; is<NS; is++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070012372 out.writeString(syncStats.keyAt(is));
12373 syncStats.valueAt(is).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012374 }
12375
Bookatzaa4594a2017-03-24 12:39:56 -070012376 final ArrayMap<String, DualTimer> jobStats = u.mJobStats.getMap();
Dianne Hackbornd953c532014-08-16 18:17:38 -070012377 int NJ = jobStats.size();
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012378 out.writeInt(NJ);
12379 for (int ij=0; ij<NJ; ij++) {
Dianne Hackbornd953c532014-08-16 18:17:38 -070012380 out.writeString(jobStats.keyAt(ij));
12381 jobStats.valueAt(ij).writeSummaryFromParcelLocked(out, NOWREAL_SYS);
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012382 }
12383
Dianne Hackborn94326cb2017-06-28 16:17:20 -070012384 u.writeJobCompletionsToParcelLocked(out);
12385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012386 int NSE = u.mSensorStats.size();
12387 out.writeInt(NSE);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012388 for (int ise=0; ise<NSE; ise++) {
12389 out.writeInt(u.mSensorStats.keyAt(ise));
12390 Uid.Sensor se = u.mSensorStats.valueAt(ise);
12391 if (se.mTimer != null) {
12392 out.writeInt(1);
12393 se.mTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
12394 } else {
12395 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012396 }
12397 }
12398
12399 int NP = u.mProcessStats.size();
12400 out.writeInt(NP);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012401 for (int ip=0; ip<NP; ip++) {
12402 out.writeString(u.mProcessStats.keyAt(ip));
12403 Uid.Proc ps = u.mProcessStats.valueAt(ip);
12404 out.writeLong(ps.mUserTime);
12405 out.writeLong(ps.mSystemTime);
12406 out.writeLong(ps.mForegroundTime);
12407 out.writeInt(ps.mStarts);
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012408 out.writeInt(ps.mNumCrashes);
12409 out.writeInt(ps.mNumAnrs);
Dianne Hackborn61659e52014-07-09 16:13:01 -070012410 ps.writeExcessivePowerToParcelLocked(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012411 }
12412
12413 NP = u.mPackageStats.size();
12414 out.writeInt(NP);
12415 if (NP > 0) {
12416 for (Map.Entry<String, BatteryStatsImpl.Uid.Pkg> ent
12417 : u.mPackageStats.entrySet()) {
12418 out.writeString(ent.getKey());
12419 Uid.Pkg ps = ent.getValue();
Dianne Hackborn1e725a72015-03-24 18:23:19 -070012420 final int NWA = ps.mWakeupAlarms.size();
12421 out.writeInt(NWA);
12422 for (int iwa=0; iwa<NWA; iwa++) {
12423 out.writeString(ps.mWakeupAlarms.keyAt(iwa));
12424 ps.mWakeupAlarms.valueAt(iwa).writeSummaryFromParcelLocked(out);
12425 }
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012426 NS = ps.mServiceStats.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012427 out.writeInt(NS);
Dianne Hackborn1e725a72015-03-24 18:23:19 -070012428 for (int is=0; is<NS; is++) {
12429 out.writeString(ps.mServiceStats.keyAt(is));
12430 BatteryStatsImpl.Uid.Pkg.Serv ss = ps.mServiceStats.valueAt(is);
12431 long time = ss.getStartTimeToNowLocked(
12432 mOnBatteryTimeBase.getUptime(NOW_SYS));
12433 out.writeLong(time);
12434 out.writeInt(ss.mStarts);
12435 out.writeInt(ss.mLaunches);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012436 }
12437 }
12438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439 }
12440 }
12441
12442 public void readFromParcel(Parcel in) {
12443 readFromParcelLocked(in);
12444 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012446 void readFromParcelLocked(Parcel in) {
12447 int magic = in.readInt();
12448 if (magic != MAGIC) {
Dianne Hackbornfdb19562014-07-11 16:03:36 -070012449 throw new ParcelFormatException("Bad magic number: #" + Integer.toHexString(magic));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012450 }
12451
Dianne Hackbornae384452011-06-28 12:33:48 -070012452 readHistory(in, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012454 mStartCount = in.readInt();
Dianne Hackborn5f4a5f92014-01-24 16:59:34 -080012455 mStartClockTime = in.readLong();
Dianne Hackborncd0e3352014-08-07 17:08:09 -070012456 mStartPlatformVersion = in.readString();
12457 mEndPlatformVersion = in.readString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012458 mUptime = in.readLong();
12459 mUptimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012460 mRealtime = in.readLong();
12461 mRealtimeStart = in.readLong();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012462 mOnBattery = in.readInt() != 0;
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012463 mEstimatedBatteryCapacity = in.readInt();
Jocelyn Dangc627d102017-04-14 13:15:14 -070012464 mMinLearnedBatteryCapacity = in.readInt();
12465 mMaxLearnedBatteryCapacity = in.readInt();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012466 mOnBatteryInternal = false; // we are no longer really running.
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012467 mOnBatteryTimeBase.readFromParcel(in);
12468 mOnBatteryScreenOffTimeBase.readFromParcel(in);
12469
Jeff Browne95c3cd2014-05-02 16:59:26 -070012470 mScreenState = Display.STATE_UNKNOWN;
Joe Onoratoabded112016-02-08 16:49:39 -080012471 mScreenOnTimer = new StopwatchTimer(mClocks, null, -1, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012472 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012473 mScreenBrightnessTimer[i] = new StopwatchTimer(mClocks, null, -100-i, null,
12474 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012475 }
Dianne Hackborn29325132014-05-21 15:01:03 -070012476 mInteractive = false;
Joe Onoratoabded112016-02-08 16:49:39 -080012477 mInteractiveTimer = new StopwatchTimer(mClocks, null, -10, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012478 mPhoneOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080012479 mPowerSaveModeEnabledTimer = new StopwatchTimer(mClocks, null, -2, null,
12480 mOnBatteryTimeBase, in);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070012481 mLongestLightIdleTime = in.readLong();
12482 mLongestFullIdleTime = in.readLong();
Joe Onoratoabded112016-02-08 16:49:39 -080012483 mDeviceIdleModeLightTimer = new StopwatchTimer(mClocks, null, -14, null,
12484 mOnBatteryTimeBase, in);
12485 mDeviceIdleModeFullTimer = new StopwatchTimer(mClocks, null, -11, null,
12486 mOnBatteryTimeBase, in);
12487 mDeviceLightIdlingTimer = new StopwatchTimer(mClocks, null, -15, null,
12488 mOnBatteryTimeBase, in);
12489 mDeviceIdlingTimer = new StopwatchTimer(mClocks, null, -12, null, mOnBatteryTimeBase, in);
12490 mPhoneOnTimer = new StopwatchTimer(mClocks, null, -3, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012491 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012492 mPhoneSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -200-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012493 null, mOnBatteryTimeBase, in);
12494 }
Joe Onoratoabded112016-02-08 16:49:39 -080012495 mPhoneSignalScanningTimer = new StopwatchTimer(mClocks, null, -200+1, null,
12496 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012497 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012498 mPhoneDataConnectionsTimer[i] = new StopwatchTimer(mClocks, null, -300-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012499 null, mOnBatteryTimeBase, in);
12500 }
12501 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
12502 mNetworkByteActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
12503 mNetworkPacketActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
12504 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012505 mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Joe Onoratoabded112016-02-08 16:49:39 -080012506 mMobileRadioActiveTimer = new StopwatchTimer(mClocks, null, -400, null,
12507 mOnBatteryTimeBase, in);
12508 mMobileRadioActivePerAppTimer = new StopwatchTimer(mClocks, null, -401, null,
12509 mOnBatteryTimeBase, in);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012510 mMobileRadioActiveAdjustedTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012511 mMobileRadioActiveUnknownTime = new LongSamplingCounter(mOnBatteryTimeBase, in);
12512 mMobileRadioActiveUnknownCount = new LongSamplingCounter(mOnBatteryTimeBase, in);
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012513 mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012514 mWifiOn = false;
Joe Onoratoabded112016-02-08 16:49:39 -080012515 mWifiOnTimer = new StopwatchTimer(mClocks, null, -4, null, mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012516 mGlobalWifiRunning = false;
Joe Onoratoabded112016-02-08 16:49:39 -080012517 mGlobalWifiRunningTimer = new StopwatchTimer(mClocks, null, -5, null,
12518 mOnBatteryTimeBase, in);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012519 for (int i=0; i<NUM_WIFI_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012520 mWifiStateTimer[i] = new StopwatchTimer(mClocks, null, -600-i,
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012521 null, mOnBatteryTimeBase, in);
12522 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070012523 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012524 mWifiSupplStateTimer[i] = new StopwatchTimer(mClocks, null, -700-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070012525 null, mOnBatteryTimeBase, in);
12526 }
12527 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
Joe Onoratoabded112016-02-08 16:49:39 -080012528 mWifiSignalStrengthsTimer[i] = new StopwatchTimer(mClocks, null, -800-i,
Dianne Hackborn3251b902014-06-20 14:40:53 -070012529 null, mOnBatteryTimeBase, in);
12530 }
Adam Lesinski33dac552015-03-09 15:24:48 -070012531
Adam Lesinski21f76aa2016-01-25 12:27:06 -080012532 mWifiActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
12533 NUM_WIFI_TX_LEVELS, in);
12534 mBluetoothActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
12535 NUM_BT_TX_LEVELS, in);
12536 mModemActivity = new ControllerActivityCounterImpl(mOnBatteryTimeBase,
12537 ModemActivityInfo.TX_POWER_LEVELS, in);
12538 mHasWifiReporting = in.readInt() != 0;
12539 mHasBluetoothReporting = in.readInt() != 0;
12540 mHasModemReporting = in.readInt() != 0;
12541
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012542 mNumConnectivityChange = in.readInt();
12543 mLoadedNumConnectivityChange = in.readInt();
12544 mUnpluggedNumConnectivityChange = in.readInt();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070012545 mAudioOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012546 mAudioOnTimer = new StopwatchTimer(mClocks, null, -7, null, mOnBatteryTimeBase);
Dianne Hackborn10eaa852014-07-22 22:54:55 -070012547 mVideoOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012548 mVideoOnTimer = new StopwatchTimer(mClocks, null, -8, null, mOnBatteryTimeBase);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012549 mFlashlightOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012550 mFlashlightOnTimer = new StopwatchTimer(mClocks, null, -9, null, mOnBatteryTimeBase, in);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012551 mCameraOnNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012552 mCameraOnTimer = new StopwatchTimer(mClocks, null, -13, null, mOnBatteryTimeBase, in);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012553 mBluetoothScanNesting = 0;
Joe Onoratoabded112016-02-08 16:49:39 -080012554 mBluetoothScanTimer = new StopwatchTimer(mClocks, null, -14, null, mOnBatteryTimeBase, in);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012555 mDischargeUnplugLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012556 mDischargePlugLevel = in.readInt();
Evan Millar633a1742009-04-02 16:36:33 -070012557 mDischargeCurrentLevel = in.readInt();
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012558 mCurrentBatteryLevel = in.readInt();
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012559 mLowDischargeAmountSinceCharge = in.readInt();
12560 mHighDischargeAmountSinceCharge = in.readInt();
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012561 mDischargeAmountScreenOn = in.readInt();
12562 mDischargeAmountScreenOnSinceCharge = in.readInt();
12563 mDischargeAmountScreenOff = in.readInt();
12564 mDischargeAmountScreenOffSinceCharge = in.readInt();
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012565 mDischargeStepTracker.readFromParcel(in);
12566 mChargeStepTracker.readFromParcel(in);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012567 mDischargeCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
12568 mDischargeScreenOffCounter = new LongSamplingCounter(mOnBatteryTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012569 mLastWriteTime = in.readLong();
12570
Evan Millarc64edde2009-04-18 12:26:32 -070012571 mKernelWakelockStats.clear();
12572 int NKW = in.readInt();
12573 for (int ikw = 0; ikw < NKW; ikw++) {
12574 if (in.readInt() != 0) {
12575 String wakelockName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080012576 SamplingTimer kwlt = new SamplingTimer(mClocks, mOnBatteryScreenOffTimeBase, in);
Evan Millarc64edde2009-04-18 12:26:32 -070012577 mKernelWakelockStats.put(wakelockName, kwlt);
12578 }
12579 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012580
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012581 mWakeupReasonStats.clear();
12582 int NWR = in.readInt();
12583 for (int iwr = 0; iwr < NWR; iwr++) {
12584 if (in.readInt() != 0) {
12585 String reasonName = in.readString();
Joe Onoratoabded112016-02-08 16:49:39 -080012586 SamplingTimer timer = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012587 mWakeupReasonStats.put(reasonName, timer);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012588 }
12589 }
12590
James Carr3a226052016-07-01 14:49:52 -070012591 mKernelMemoryStats.clear();
12592 int nmt = in.readInt();
12593 for (int imt = 0; imt < nmt; imt++) {
12594 if (in.readInt() != 0) {
12595 Long bucket = in.readLong();
12596 SamplingTimer kmt = new SamplingTimer(mClocks, mOnBatteryTimeBase, in);
12597 mKernelMemoryStats.put(bucket, kmt);
12598 }
12599 }
12600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012601 mPartialTimers.clear();
12602 mFullTimers.clear();
12603 mWindowTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012604 mWifiRunningTimers.clear();
12605 mFullWifiLockTimers.clear();
Nick Pelly6ccaa542012-06-15 15:22:47 -070012606 mWifiScanTimers.clear();
Robert Greenwalta029ea12013-09-25 16:38:12 -070012607 mWifiBatchedScanTimers.clear();
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012608 mWifiMulticastTimers.clear();
Dianne Hackborn10eaa852014-07-22 22:54:55 -070012609 mAudioTurnedOnTimers.clear();
12610 mVideoTurnedOnTimers.clear();
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012611 mFlashlightTurnedOnTimers.clear();
12612 mCameraTurnedOnTimers.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012613
12614 int numUids = in.readInt();
12615 mUidStats.clear();
12616 for (int i = 0; i < numUids; i++) {
12617 int uid = in.readInt();
Joe Onoratoabded112016-02-08 16:49:39 -080012618 Uid u = new Uid(this, uid);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012619 u.readFromParcelLocked(mOnBatteryTimeBase, mOnBatteryScreenOffTimeBase, in);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012620 mUidStats.append(uid, u);
12621 }
12622 }
12623
12624 public void writeToParcel(Parcel out, int flags) {
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012625 writeToParcelLocked(out, true, flags);
12626 }
12627
12628 public void writeToParcelWithoutUids(Parcel out, int flags) {
12629 writeToParcelLocked(out, false, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012630 }
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012631
12632 @SuppressWarnings("unused")
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012633 void writeToParcelLocked(Parcel out, boolean inclUids, int flags) {
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012634 // Need to update with current kernel wake lock counts.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012635 pullPendingStateUpdatesLocked();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012636
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012637 // Pull the clock time. This may update the time and make a new history entry
12638 // if we had originally pulled a time before the RTC was set.
12639 long startClockTime = getStartClockTime();
12640
Joe Onoratoabded112016-02-08 16:49:39 -080012641 final long uSecUptime = mClocks.uptimeMillis() * 1000;
12642 final long uSecRealtime = mClocks.elapsedRealtime() * 1000;
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012643 final long batteryRealtime = mOnBatteryTimeBase.getRealtime(uSecRealtime);
12644 final long batteryScreenOffRealtime = mOnBatteryScreenOffTimeBase.getRealtime(uSecRealtime);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012646 out.writeInt(MAGIC);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012647
Dianne Hackborn0068d3dc2014-08-06 19:20:25 -070012648 writeHistory(out, true, false);
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012650 out.writeInt(mStartCount);
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012651 out.writeLong(startClockTime);
Dianne Hackborncd0e3352014-08-07 17:08:09 -070012652 out.writeString(mStartPlatformVersion);
12653 out.writeString(mEndPlatformVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012654 out.writeLong(mUptime);
12655 out.writeLong(mUptimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012656 out.writeLong(mRealtime);
12657 out.writeLong(mRealtimeStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012658 out.writeInt(mOnBattery ? 1 : 0);
Adam Lesinskif9b20a92016-06-17 17:30:01 -070012659 out.writeInt(mEstimatedBatteryCapacity);
Jocelyn Dangc627d102017-04-14 13:15:14 -070012660 out.writeInt(mMinLearnedBatteryCapacity);
12661 out.writeInt(mMaxLearnedBatteryCapacity);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012662 mOnBatteryTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
12663 mOnBatteryScreenOffTimeBase.writeToParcel(out, uSecUptime, uSecRealtime);
12664
12665 mScreenOnTimer.writeToParcel(out, uSecRealtime);
12666 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
12667 mScreenBrightnessTimer[i].writeToParcel(out, uSecRealtime);
12668 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070012669 mInteractiveTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070012670 mPowerSaveModeEnabledTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn08c47a52015-10-15 12:38:14 -070012671 out.writeLong(mLongestLightIdleTime);
12672 out.writeLong(mLongestFullIdleTime);
12673 mDeviceIdleModeLightTimer.writeToParcel(out, uSecRealtime);
12674 mDeviceIdleModeFullTimer.writeToParcel(out, uSecRealtime);
12675 mDeviceLightIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012676 mDeviceIdlingTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012677 mPhoneOnTimer.writeToParcel(out, uSecRealtime);
12678 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
12679 mPhoneSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
12680 }
12681 mPhoneSignalScanningTimer.writeToParcel(out, uSecRealtime);
12682 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
12683 mPhoneDataConnectionsTimer[i].writeToParcel(out, uSecRealtime);
12684 }
12685 for (int i = 0; i < NUM_NETWORK_ACTIVITY_TYPES; i++) {
12686 mNetworkByteActivityCounters[i].writeToParcel(out);
12687 mNetworkPacketActivityCounters[i].writeToParcel(out);
12688 }
12689 mMobileRadioActiveTimer.writeToParcel(out, uSecRealtime);
12690 mMobileRadioActivePerAppTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012691 mMobileRadioActiveAdjustedTime.writeToParcel(out);
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012692 mMobileRadioActiveUnknownTime.writeToParcel(out);
12693 mMobileRadioActiveUnknownCount.writeToParcel(out);
12694 mWifiOnTimer.writeToParcel(out, uSecRealtime);
12695 mGlobalWifiRunningTimer.writeToParcel(out, uSecRealtime);
12696 for (int i=0; i<NUM_WIFI_STATES; i++) {
12697 mWifiStateTimer[i].writeToParcel(out, uSecRealtime);
12698 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070012699 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12700 mWifiSupplStateTimer[i].writeToParcel(out, uSecRealtime);
12701 }
12702 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12703 mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
12704 }
Adam Lesinski21f76aa2016-01-25 12:27:06 -080012705 mWifiActivity.writeToParcel(out, 0);
12706 mBluetoothActivity.writeToParcel(out, 0);
12707 mModemActivity.writeToParcel(out, 0);
12708 out.writeInt(mHasWifiReporting ? 1 : 0);
12709 out.writeInt(mHasBluetoothReporting ? 1 : 0);
12710 out.writeInt(mHasModemReporting ? 1 : 0);
12711
Dianne Hackborn1e01d162014-12-04 17:46:42 -080012712 out.writeInt(mNumConnectivityChange);
12713 out.writeInt(mLoadedNumConnectivityChange);
12714 out.writeInt(mUnpluggedNumConnectivityChange);
Dianne Hackbornabc7c492014-06-30 16:57:46 -070012715 mFlashlightOnTimer.writeToParcel(out, uSecRealtime);
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012716 mCameraOnTimer.writeToParcel(out, uSecRealtime);
Adam Lesinski9f55cc72016-01-27 20:42:14 -080012717 mBluetoothScanTimer.writeToParcel(out, uSecRealtime);
Dianne Hackborn6b7b4842010-06-14 17:17:44 -070012718 out.writeInt(mDischargeUnplugLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012719 out.writeInt(mDischargePlugLevel);
Evan Millar633a1742009-04-02 16:36:33 -070012720 out.writeInt(mDischargeCurrentLevel);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012721 out.writeInt(mCurrentBatteryLevel);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012722 out.writeInt(mLowDischargeAmountSinceCharge);
12723 out.writeInt(mHighDischargeAmountSinceCharge);
Dianne Hackbornc1b40e32011-01-05 18:27:40 -080012724 out.writeInt(mDischargeAmountScreenOn);
12725 out.writeInt(mDischargeAmountScreenOnSinceCharge);
12726 out.writeInt(mDischargeAmountScreenOff);
12727 out.writeInt(mDischargeAmountScreenOffSinceCharge);
Dianne Hackbornd4a8af72015-03-03 10:06:15 -080012728 mDischargeStepTracker.writeToParcel(out);
12729 mChargeStepTracker.writeToParcel(out);
Adam Lesinski3ee3f632016-06-08 13:55:55 -070012730 mDischargeCounter.writeToParcel(out);
12731 mDischargeScreenOffCounter.writeToParcel(out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012732 out.writeLong(mLastWriteTime);
12733
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012734 if (inclUids) {
12735 out.writeInt(mKernelWakelockStats.size());
12736 for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
12737 SamplingTimer kwlt = ent.getValue();
12738 if (kwlt != null) {
12739 out.writeInt(1);
12740 out.writeString(ent.getKey());
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012741 kwlt.writeToParcel(out, uSecRealtime);
12742 } else {
12743 out.writeInt(0);
12744 }
12745 }
12746 out.writeInt(mWakeupReasonStats.size());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012747 for (Map.Entry<String, SamplingTimer> ent : mWakeupReasonStats.entrySet()) {
12748 SamplingTimer timer = ent.getValue();
12749 if (timer != null) {
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012750 out.writeInt(1);
12751 out.writeString(ent.getKey());
Dianne Hackbornc3940bc2014-09-05 15:50:25 -070012752 timer.writeToParcel(out, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012753 } else {
12754 out.writeInt(0);
12755 }
Evan Millarc64edde2009-04-18 12:26:32 -070012756 }
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012757 } else {
12758 out.writeInt(0);
Evan Millarc64edde2009-04-18 12:26:32 -070012759 }
Amith Yamasanie43530a2009-08-21 13:11:37 -070012760
James Carr3a226052016-07-01 14:49:52 -070012761 out.writeInt(mKernelMemoryStats.size());
12762 for (int i = 0; i < mKernelMemoryStats.size(); i++) {
12763 SamplingTimer kmt = mKernelMemoryStats.valueAt(i);
12764 if (kmt != null) {
12765 out.writeInt(1);
12766 out.writeLong(mKernelMemoryStats.keyAt(i));
12767 kmt.writeToParcel(out, uSecRealtime);
12768 } else {
12769 out.writeInt(0);
12770 }
12771 }
12772
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012773 if (inclUids) {
12774 int size = mUidStats.size();
12775 out.writeInt(size);
12776 for (int i = 0; i < size; i++) {
12777 out.writeInt(mUidStats.keyAt(i));
12778 Uid uid = mUidStats.valueAt(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012779
Bookatz867c0d72017-03-07 18:23:42 -080012780 uid.writeToParcelLocked(out, uSecUptime, uSecRealtime);
Dianne Hackborn3bee5af82010-07-23 00:22:04 -070012781 }
12782 } else {
12783 out.writeInt(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012784 }
12785 }
12786
12787 public static final Parcelable.Creator<BatteryStatsImpl> CREATOR =
12788 new Parcelable.Creator<BatteryStatsImpl>() {
12789 public BatteryStatsImpl createFromParcel(Parcel in) {
12790 return new BatteryStatsImpl(in);
12791 }
12792
12793 public BatteryStatsImpl[] newArray(int size) {
12794 return new BatteryStatsImpl[size];
12795 }
12796 };
Jaikumar Ganesh5a1e4cf2010-10-18 17:05:09 -070012797
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012798 public void prepareForDumpLocked() {
12799 // Need to retrieve current kernel wake lock stats before printing.
Dianne Hackborna7c837f2014-01-15 16:20:44 -080012800 pullPendingStateUpdatesLocked();
Dianne Hackborn7d9eefd2014-08-27 18:30:31 -070012801
12802 // Pull the clock time. This may update the time and make a new history entry
12803 // if we had originally pulled a time before the RTC was set.
12804 getStartClockTime();
Dianne Hackborn0ffc9882011-04-13 18:15:56 -070012805 }
12806
Dianne Hackbornc51cf032014-03-02 19:08:15 -080012807 public void dumpLocked(Context context, PrintWriter pw, int flags, int reqUid, long histStart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012808 if (DEBUG) {
Dianne Hackborn97ae5382014-03-05 16:43:25 -080012809 pw.println("mOnBatteryTimeBase:");
12810 mOnBatteryTimeBase.dump(pw, " ");
12811 pw.println("mOnBatteryScreenOffTimeBase:");
12812 mOnBatteryScreenOffTimeBase.dump(pw, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070012813 Printer pr = new PrintWriterPrinter(pw);
12814 pr.println("*** Screen timer:");
12815 mScreenOnTimer.logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070012816 for (int i=0; i<NUM_SCREEN_BRIGHTNESS_BINS; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070012817 pr.println("*** Screen brightness #" + i + ":");
12818 mScreenBrightnessTimer[i].logState(pr, " ");
Dianne Hackborn617f8772009-03-31 15:04:46 -070012819 }
Jeff Browne95c3cd2014-05-02 16:59:26 -070012820 pr.println("*** Interactive timer:");
12821 mInteractiveTimer.logState(pr, " ");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -070012822 pr.println("*** Power save mode timer:");
12823 mPowerSaveModeEnabledTimer.logState(pr, " ");
Dianne Hackborn08c47a52015-10-15 12:38:14 -070012824 pr.println("*** Device idle mode light timer:");
12825 mDeviceIdleModeLightTimer.logState(pr, " ");
12826 pr.println("*** Device idle mode full timer:");
12827 mDeviceIdleModeFullTimer.logState(pr, " ");
12828 pr.println("*** Device light idling timer:");
12829 mDeviceLightIdlingTimer.logState(pr, " ");
Dianne Hackborn88e98df2015-03-23 13:29:14 -070012830 pr.println("*** Device idling timer:");
12831 mDeviceIdlingTimer.logState(pr, " ");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070012832 pr.println("*** Phone timer:");
12833 mPhoneOnTimer.logState(pr, " ");
Wink Saville52840902011-02-18 12:40:47 -080012834 for (int i=0; i<SignalStrength.NUM_SIGNAL_STRENGTH_BINS; i++) {
Dianne Hackborn3251b902014-06-20 14:40:53 -070012835 pr.println("*** Phone signal strength #" + i + ":");
Dianne Hackborn1d442e02009-04-20 18:14:05 -070012836 mPhoneSignalStrengthsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070012837 }
Amith Yamasanif37447b2009-10-08 18:28:01 -070012838 pr.println("*** Signal scanning :");
12839 mPhoneSignalScanningTimer.logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070012840 for (int i=0; i<NUM_DATA_CONNECTION_TYPES; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -070012841 pr.println("*** Data connection type #" + i + ":");
12842 mPhoneDataConnectionsTimer[i].logState(pr, " ");
Dianne Hackborn627bba72009-03-24 22:32:56 -070012843 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070012844 pr.println("*** mMobileRadioPowerState=" + mMobileRadioPowerState);
Dianne Hackborne13c4c02014-02-11 17:18:35 -080012845 pr.println("*** Mobile network active timer:");
12846 mMobileRadioActiveTimer.logState(pr, " ");
Dianne Hackborna1bd7922014-03-21 11:07:11 -070012847 pr.println("*** Mobile network active adjusted timer:");
12848 mMobileRadioActiveAdjustedTime.logState(pr, " ");
Dianne Hackborn0c820db2015-04-14 17:47:34 -070012849 pr.println("*** mWifiRadioPowerState=" + mWifiRadioPowerState);
Dianne Hackborn1d442e02009-04-20 18:14:05 -070012850 pr.println("*** Wifi timer:");
12851 mWifiOnTimer.logState(pr, " ");
12852 pr.println("*** WifiRunning timer:");
Dianne Hackborn58e0eef2010-09-16 01:22:10 -070012853 mGlobalWifiRunningTimer.logState(pr, " ");
Dianne Hackbornca1bf212014-02-14 14:18:36 -080012854 for (int i=0; i<NUM_WIFI_STATES; i++) {
12855 pr.println("*** Wifi state #" + i + ":");
12856 mWifiStateTimer[i].logState(pr, " ");
12857 }
Dianne Hackborn3251b902014-06-20 14:40:53 -070012858 for (int i=0; i<NUM_WIFI_SUPPL_STATES; i++) {
12859 pr.println("*** Wifi suppl state #" + i + ":");
12860 mWifiSupplStateTimer[i].logState(pr, " ");
12861 }
12862 for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
12863 pr.println("*** Wifi signal strength #" + i + ":");
12864 mWifiSignalStrengthsTimer[i].logState(pr, " ");
12865 }
Dianne Hackbornabc7c492014-06-30 16:57:46 -070012866 pr.println("*** Flashlight timer:");
12867 mFlashlightOnTimer.logState(pr, " ");
Ruben Brunk6d2c3632015-05-26 17:32:16 -070012868 pr.println("*** Camera timer:");
12869 mCameraOnTimer.logState(pr, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012870 }
Dianne Hackbornc51cf032014-03-02 19:08:15 -080012871 super.dumpLocked(context, pw, flags, reqUid, histStart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012873}